The beauty of language extensions is that they are scope based. If there is a static class "nearby" that happens to work on an object of the type with which you're working - the extension will be available. If the extension is not in scope, either because it hasn't been referenced or because you haven't included the extension's namespace with a
using... clause, then the extension is unavailable.
As far as I can tell, VB requires you to throw a bunch of ugly attributes on your classes to make them extensions. In C#, all you have to do is add the
this keyword to the first parameter of your extension method, and you have extended the data type of that parameter.
For example, to extend the string class, just create a static class like so:
static class StringExtender
{
public static string DoSomethingFancy(this string input)
{
...
}
}
This creates a language extension on all string objects, so you can then do:
"Hello".DoSomethingFancy();
or
myString.DoSomethingFancy();
Simply by having your extension be scope-visible to the code in which you are invoking the extension.
Here's an example of a class I wrote that adds an
InAlternateCulture(string culture) method to the string class to force a string to display in a given culture without regard for the current thread's culture:
using System;
using System.Collections.Generic;
using System.Text;
using System.Query;
using System.Data.DLinq;
using System.Globalization;
namespace languageExtensions
{
public static class StringCultureExtender
{
public static string InAlternateCulture(this string sourceString, string altCulture)
{
CultureInfo ci = new CultureInfo(altCulture);
return Strings.ResourceManager.GetString(sourceString, ci);
}
}
}
That's it. All you have to do in order to switch a string is send the string's resource keyword as follows:
Console.WriteLine("Hello".InAlternateCulture("en-AU")) can print something like "G'day".
Here's a screenshot from a program that displays strings in Hindi or English:

tags: cultureinfo csharp30 languageextensions linq
links: digg this del.icio.us technorati reddit