Extension Methods

As per the Microsoft, Extension methods are defined as " Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type". For more information on Extension methods, check here.

Following are some useful extension methods written in C#

1) To convert the given date time to the given timezone
public static DateTime LocalTime(this DateTime dt, string timeZone)
{
 TimeZoneInfo oTZInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZone.Trim());
 return TimeZoneInfo.ConvertTime(dt, oTZInfo);
}

2) To convert the given string to Title case
public static string TitleCase(this string word)
{
 TextInfo objTextInfo = new System.Globalization.CultureInfo("en-US").TextInfo;
 return objTextInfo.ToTitleCase(word.ToLower());
}

3)  To convert the datetime to EpochTime/UnixTime  format
public static long EpochTime(this DateTime dateTime)
{
 return new DateTimeOffset(dateTime).ToUnixTimeSeconds();
}

4) To convert the datetime stored as string to EpochTime/UnixTime format
public static long EpochTime(this string dateTime)
{
 DateTime.TryParse(dateTime, out DateTime dateTime2);

 return new DateTimeOffset(dateTime2).ToUnixTimeSeconds();
}

5) To convert the EpochTime/UnixTime to datetime
public static DateTime ToDateTime(this long unixDateTime)
{
 return DateTimeOffset.FromUnixTimeSeconds(unixDateTime).DateTime.ToLocalTime();
}

6) To remove the session variable safely (without raising issue when session variable not exists)
public static void Remove(this HttpSessionState session, string key)
{
 if (session[key] != null)
  session.Remove(key);
}

7) To get bytes array from stream
public static byte[] GetBytes(this Stream stream)
{
 // Create a byte array of file stream length
 byte[] byteData = new byte[stream.Length];

 //Read block of bytes from stream into the byte array
 stream.Read(byteData, 0, System.Convert.ToInt32(stream.Length));

 //Close the File Stream
 stream.Close();
 
 //return the byte data
 return byteData; 
}

8) To check any property value of an object is empty or null
public static bool IsAnyNullOrEmptyProperty(this object myObject)
{
 foreach (PropertyInfo pi in myObject.GetType().GetProperties())
 {
  if (pi.PropertyType == typeof(string))
  {
   string value = (string)pi.GetValue(myObject);
   if (string.IsNullOrEmpty(value))
    return true;
  }
 }
 return false;
}

Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment