Extension Methods
- January 16th, 2010
- Write comment
Extension methods are a handy feature that allows you to extend the functionality of existing classes for which you do not have the source. Extension methods must be static and the type following the ‘this’ keyword indicates the type that is extended by this method.
More information on extension methods can be found here
These are just some of the extension methods I commonly use to make everyday coding a little easier and more readable.
/// <summary> /// Reformat a string so that the first letter of every word is capitalised and every other letter is lower case /// </summary> /// <param name="str">String to format</param> /// <returns>Formatted string</returns> public static string ToTitleCase(this string str) { CultureInfo ci = new CultureInfo("en"); TextInfo cc = ci.TextInfo; return cc.ToTitleCase(str); } /// <summary> /// Convert this string to its enum type /// </summary> /// <typeparam name="T">Type of enum</typeparam> /// <param name="enumValue">string value to parse</param> /// <returns>Enum type parsed from string</returns> public static T ConvertToEnum<T>(this string enumValue) where T : struct { if (!typeof(T).IsEnum) throw new InvalidEnumArgumentException("T must be an enum"); return (T)Enum.Parse(typeof(T), enumValue, true); } /// <summary> /// Get the value of a table column from a reader object /// </summary> /// <typeparam name="T">Type of expected return value</typeparam> /// <param name="reader">Reader oject to get the value from</param> /// <param name="columnName">Name of column to retrieve the value from</param> /// <returns>Column Value</returns> /// <exception cref="NullReferenceException">If T is not nullable and the column value is null</exception> public static T GetColumnValue<T>(this IDataReader reader, string columnName) { if (reader.IsDBNull(reader.GetOrdinal(columnName))) { if ( (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>)) || typeof(T) == typeof(string) ) { return default(T); } else throw new NullReferenceException("DB Value is null"); } else return (T)reader[columnName]; } //The above methods are called like this ... string myStr ="exAmple sTrinG"; Console.WriteLine(myStr.ToTitleCase()); //Output --> Example String //assume we have the namespace Microsoft.SqlServer.Management.Smo imported string varChar = "VarChar"; SqlDataType testVrChr = varChar.ConvertToEnum<SqlDataType>(); //where reader is an IDataReader int? value = reader.GetColumnValue<int?>("ColName"); |