I would write a simple extension method which will convert an object to string. In other words I am going to write an equivalent method of ToString().
public static string Str(this object obj)
{
return Convert.ToString(obj);
}
Please note "this" keyword is appended to the first parameter in order to call it on that type. In the above example we can call the extension method on any type because the first parameter is of type obj.
Here is the code to call the above method.
int x=123;
string val=x.Str(); //as good as Convert.ToString(x); Str is a static method but it is called as an instance method.
Simple isn't it? Well the above method is a very simple one, you can write more complex methods and can re-use. Further more you can put all of your extension methods in a dll and re-use across your projects.

No comments:
Post a Comment