Partially Available Extension Methods in C#

Posted in software by Christopher R. Wirz on Sun Sep 18 2016



Some C# 3 features can be used in .NET 2.0 with a declaration. Extension methods require an attribute which is normally part of .NET 3.5. However, this is an example of features which can be enabled.

Extension methods usually take the following form:


namespace Extensions
{
	public static partial class DateTimeExtensions
	{
		/// <summary>
		/// 	Creates a string in the Hammer format from a DateTime object
		/// </summary>
		/// <param name="dateTime">The DateTime object.</param>
		/// <returns>A string in the Hammer format</returns>
		public static string ToHammerTimeString(this DateTime dateTime)
		{
			return dateTime.ToString("ddHHmm'Hammer'MMMyyyy");
		}

		/// <summary>
		/// 	Creates a new instance of a DateTime object from a string in the Hammer format
		/// </summary>
		/// <param name="dateTime">The DateTime object.</param>
		/// <param name="input">The input sting.</param>
		/// <returns>A DateTime object</returns>
		public static DateTime CreateFromHammerTimeString(this DateTime dateTime, string input)
		{
			try
			{
				if (input.Length == "ddHHmmHammerMMMyyyy".Length &&
					input.Split(
						new string[] {"Hammer"},
						StringSplitOptions.RemoveEmptyEntries
					).Length == 2
				)
				{
					DateTime returnDateTime;
					if (DateTime.TryParseExact(
						input,
						"ddHHmm'Hammer'MMMyyyy",
						CultureInfo.CurrentCulture,
						DateTimeStyles.None,
						out returnDateTime)
					)
					{
						return returnDateTime;
					}
				}
			}
			catch
			{
				// ignored
			}
			return default(DateTime);
		}
	}
}

However, if your .Net target is less than 3.5, you may not be able to compile. This is where the attribute declaration is required.

Note: some use LINQBridge is an implementation of LINQ to Objects for .NET 2.0.

Add the following declaration to your project, either in a new .cs file or at the bottom of the extensions file:


namespace System.Runtime.CompilerServices
 {
     [AttributeUsageAttribute(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)]
     public class ExtensionAttribute : Attribute
     {
     }
 }

Assuming this was the only thing preventing the project from compiling, extension methods should now be available. Also, you can now use the defined extension methods as follows:


using Extensions;

namespace SampleApplication
{
    class Program
    {
		static int Main(string[] args)
		{
			DateTime originalDateTime = DateTime.Now;
			string str = originalDateTime.ToHammerTimeString();
			Console.WriteLine(str);

			DateTime newDateTimeObject = originalDateTime.CreateFromHammerTimeString(str);
			return 0;
		}
    }
}