C# Extension methods for everyday usage

C

Following up a previous post: https://devcoons.com/c-nuget-package-with-useful-extension-methods/ , in this post there will be listed some quite useful and commonly used extension methods for simple operations. (Basically, I do not currently maintain the NuGet package -lack-of-time-)

I have various extension methods in my CommonLib file, however, in this post, I will only enumerate some of them.

Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.” One of the most important things that you may have to do, is probably to create your own extensions *dll and keep everything there and up-to-date. It will save your time!

public static byte[] ToByteArray(this object obj)
{
   if (obj == null)
      return null;
   BinaryFormatter bf = new BinaryFormatter();
   using (MemoryStream ms = new MemoryStream())
   {
      bf.Serialize(ms, obj);
      return ms.ToArray();
   }
}

public static string StringReverse(this string s)
{
   char[] charArray = s.ToCharArray();
   Array.Reverse(charArray);
   return new string(charArray);
}

public static void Sort<T>(this ObservableCollection<T> collection, Comparison<T> comparison)
{
   var sortableList = new List<T>(collection);
   sortableList.Sort(comparison);

   for (int i = 0; i < sortableList.Count; i++)
      collection.Move(collection.IndexOf(sortableList[i]), i);
}

public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerable)
{
   var col = new ObservableCollection<T>();
   foreach (var cur in enumerable)
      col.Add(cur);
   return col;
}

public static string ExceptionOccured = "";
public static string SubstringExt(this string arg,int start,int length)
{
   try
   {
      int full_length = arg.Length;

      if (full_length - (start + length) > 0)
         return arg.Substring(start, length);

      return arg.Substring(start, length + (full_length - (start + length)));
    }
    catch(Exception)
    {
       return "";
    }
}

public static T SafeExecutor<T>(Func<T> action)
{
   ExceptionOccured = "";

   try
   {
      return action();
   }
   catch (Exception ex)
   {
      ExceptionOccured = ex.Message.ToString();
   }

   return default(T);
}

public static string SafeExecutorResults()
{
   return ExceptionOccured;
}

public static Stream ToStream(this string s)
{
   var stream = new MemoryStream();
   var writer = new StreamWriter(stream);
   writer.Write(s);
   writer.Flush();
   stream.Position = 0;
   return stream;
}

public static byte[] HexToByteArray(this string hex)
{
   if (hex.Length % 2 == 1)
      return null;

   byte[] arr = new byte[hex.Length >> 1];

   for (int i = 0; i < hex.Length >> 1; ++i)
      arr[i] = (byte)((GetHexVal(hex[i << 1]) << 4) + (GetHexVal(hex[(i << 1) + 1])));

   return arr;
}

private static int GetHexVal(char hex)
{
   return (int)hex - ((int)hex < 58 ? 48 : ((int)hex < 97 ? 55 : 87));
}

public static byte[] Combine(byte[] first, byte[] second)
{
   byte[] ret = new byte[first.Length + second.Length];
   Buffer.BlockCopy(first, 0, ret, 0, first.Length);
   Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
   return ret;
}

public static byte[] CombineWith(this byte[] first, byte[] second)
{
   byte[] ret = new byte[first.Length + second.Length];
   Buffer.BlockCopy(first, 0, ret, 0, first.Length);
   Buffer.BlockCopy(second, 0, ret, first.Length, second.Length);
   return ret;
}

public static T[] SubArrayDeepClone<T>(this T[] data, int index, int length)
{
   try
   {
      T[] arrCopy = new T[(data.Length - index) > length ? length : data.Length - index];
      Array.Copy(data, index, arrCopy, 0, 
                (data.Length - index) > length ? length : data.Length - index);
      using (MemoryStream ms = new MemoryStream())
      {
         var bf = new BinaryFormatter();
         bf.Serialize(ms, arrCopy);
         ms.Position = 0;
         return (T[])bf.Deserialize(ms);
      }
   }
   catch (Exception)
   {
      return default(T[]);
   }
}

public static T[] SubArray<T>(this T[] data, int index, int length)
{
   try
   {
      T[] arrCopy = new T[(data.Length - index) > length ? length : data.Length - index];
      Array.Copy(data, index, arrCopy, 0, 
                 (data.Length - index) > length ? length : data.Length - index);
       return arrCopy;
   }
   catch (Exception)
   {
      return default(T[]);
   }
}

public static bool HasMethod(this object obj, string methodName)
{
   var type = obj.GetType();
   return type.GetMethod(methodName) != null;
}

public static int SumUpBytes(this byte[] t)
{
   int res = 0;
   for (int i = 0; i < t.Length; i++)
       res += t[i];
   return res;
}

public static T FindBasedOn<T>(this List<T> list, string propertyName, object value)
{
   if (list.Count == 0)
      return default(T);

   if (list[0].HasProperty(propertyName) == false)
      return default(T);

   for (int i = 0; i < list.Count; i++)
      if (list[i].GetType().GetProperty(propertyName).GetValue(list[i]).Equals(value) == true)
         return list[i];
   return default(T);
}

public static void InvokeIfRequired(this ISynchronizeInvoke obj,
                                System.Windows.Forms.MethodInvoker action)
{
   if (obj.InvokeRequired)
   {
      var args = new object[0];
      obj.Invoke(action, args);
   }
   else
   {
      action();
   }
}

public static bool HasProperty(this object obj, string propertyName)
{
   return obj.GetType().GetProperty(propertyName) != null;
}

public static T GetValueFromDescription<T>(string description)
{
   var type = typeof(T);
   if (!type.IsEnum) throw new InvalidOperationException();
   foreach (var field in type.GetFields())
   {
      var attribute = Attribute.GetCustomAttribute(field,
                    typeof(DescriptionAttribute)) as DescriptionAttribute;
      if (attribute != null)
      {
         if (attribute.Description == description)
            return (T)field.GetValue(null);
      }
      else
      {
         if (field.Name == description)
            return (T)field.GetValue(null);
      }
   }
   return default(T);
}

public static string GetDescriptionFromValue<T>(T description)
{
   try
   {
      System.Reflection.MemberInfo[] memInfo = 
                                 description.GetType().GetMember(description.ToString());
      DescriptionAttribute attribute = 
                   CustomAttributeExtensions.GetCustomAttribute<DescriptionAttribute>(memInfo[0]);
      return attribute.Description;
   }
   catch (Exception)
   {
      return "";
   }
}
Disclaimer: The present content may not be used for training artificial intelligence or machine learning algorithms. All other uses, including search, entertainment, and commercial use, are permitted.

Categories

Tags