RSS

Adding Extension Methods To Every Object in C#

28 Feb

Extension methods in C# are great tools at some locations they are especially helpful when extending types that are not owned by the caller.
Extension methods provide three major advantages,
1. Centralizing common code by providing domain specific language.
2. Extending types without using inheritance or composition.
3. Extending external codebases.
If you need to extend every object how would you do it? Well you can extend “Object” type and “Type” classes since every object in C# inherits from “Object” type and “Object” type contains “GetType()” method which returns “Type”. This means extending “Object” and “Type” will propagate to all objects if you import the correct namespace.
In following implementation I am writing extension method to serialize any object to JSON format. This sort of implementations are very useful in crosscutting concerns like logging.

namespace System
{
	public static class ObjectExtensions
	{
		public static string ToJson(this Object obj)
		{
			return JsonConvert.SerializeObject(obj);
		}
	}
}

In above code I am extending Object type so that every object might be able to use provided that the assembly referenced and since I am defining this in “System” namespace that is the only requirement. If you define this in any other namespace then you have to import that namespace to use as an object extension.
Usage for the JSON convert is simple as shown below.

namespace Extensions.Tests
{
	[TestFixture]
	public class ObjectExtentionTests
	{
		[Test]
		public void Object_Extention_ConvertToJSON_Test()
		{
			var p = new Person() { FirstName = "Dimuthu", LastName = "Perera"};
			Debug.Write(p.ToJson());
		}
	}

	public class Person
	{
		public string FirstName { get; set; }
		public string LastName { get; set; }
	}
}

When you access intelisense for object, Visual Studio will show the extension method as an option in the list as shown below.
Extension method intelisense support for every object

So output will be when JSON serialized in above code will be as following,

{"FirstName":"Dimuthu","LastName":"Perera"}
Advertisements
 
Leave a comment

Posted by on February 28, 2014 in .NET, C#, Visual Studio

 

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: