Home > Geek Tips > Using Extension Methods/Indexers in .Net 3.5

Using Extension Methods/Indexers in .Net 3.5

September 11th, 2009 Harry Leave a comment Go to comments

If you’re not familiar with extension methods in C#, you should probably read http://msdn.microsoft.com/en-us/library/bb383977.aspx.

Long story short, they are a special type of static method that can appear to be an instance method while you’re coding. Normally, if you were to create a special method that performs an operation on a string, you would do something like this:

static string StripDuplicateNumbers( string seriesOfNumbers )
{
	char[] numbers = seriesOfNumbers.ToCharArray();
 
	StringBuilder str = new StringBuilder();
	object exists = new object();
 
	Dictionary<char, object> knownNumbers = new Dictionary<char,object>();
 
	int length = numbers.length;
 
	for ( int i = 0; i < length; i++ )
	{
		char number = numbers[i];
		if ( !knownNumbers.ContainsKey( number ) )
		{
			knownNumbers.Add( number, exists );
			str.Append( number );
		}
	}
 
	return str.ToString();
}

And you would call this method something like this:

string numbers = StripDuplicateNumbers( "1234545366323" );

When you convert this to an extension, the definition would change to look something like this:

static string StripDuplicateNumbers( this string seriesOfNumbers )
{
...
}

And now you would call it like this:

string numbers = "1432545326543";
numbers = numbers.StripDuplicateNumbers();

Now this might not look great from the example, but it can being extremely useful in cleaning up your code and extending the functionality. Similarly, you can use indexers for accessing members of a class. For instance, if you create a class that has different collections in it, you may want to use the array-type indexers to load different things:

class MyClass
{
	private Dictionary<string, int> _strings = new Dictionary<string, int>();
	private Dictionary<int, string> _numbers = new Dictionary<int, string>();
 
	public int this[string s]
	{
		get
		{
			return _strings[s];
		}
		set
		{
			if (!_strings.ContainsKey(s))
				_strings.Add(s, value);
			else
				_strings[s] = value;
		}
	}
 
	public string this[int i]
	{
		get
		{
			return _numbers[i];
		}
		set
		{
			if (!_numbers.ContainsKey(i))
				_numbers.Add(i, value);
			else
				_numbers[i] = value;
		}
	}
}

And you could use it like this:

MyClass m = new MyClass();
m["hi"] = 4;
m[4] = "something else";

Although my examples aren’t the greatest, these features increase readability/usability of your code. If you didn’t know about them already, I hope you’re able to get some use out of these.

Categories: Geek Tips Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Spam protection by WP Captcha-Free