So, this article is written on era of c# 4.0
we’ve got extension method
but no extension property

@Eric Lippert try to explain
http://blogs.msdn.com/b/ericlippert/archive/2009/10/05/why-no-extension-properties.aspx

but there is a workaround…

http://msdn.microsoft.com/en-us/library/bb384054.aspx
if you read the msdn article, the compiler creates a private, anonymous backing field that can only be accessed through the property’s get and set accessors

So, in order to create my version of extension property, we have to create a static variable to keep the value, we can use in memory variable or database etc…

This is naive solution but you get the idea

say you have a class Person, and you want to have extended property called middle name

public static class PersonExtensionProperty
{
private static Dictionary<int, string> middleNames=new Dictionary<int,string>();

public static string MiddleName(this Person person)
{
int key=person.GetHashCode();

if(!middleNames.ContainsKey(key))
{
middleNames.Add(key,string.Empty);
}

return middleNames[key];

}

public static void MiddleName(this Person person, string value)
{
int key=person.GetHashCode();

if(!middleNames.ContainsKey(key))
{
middleNames.Add(key,value);
}

middleNames[key]=value;
}

}
Advertisements