What are extension methods?
Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type.
How to use extension methods?
An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.
Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.
public static class MyExtension {
public static string ToMyStandard(this string stdString)
{
return "MYSTR-" + stdString;
}
}
string ss = "data";
@ViewBag.MyData = ss.ToMyStandard();
--------------------------------------------------------------------------------------
public class ExtClass
{
public string MyData { get; set; }
public string Print() { return MyData + " Print data"; }
}
public static class MyClassExtension
{
public static string ExtensionPrint(this ExtClass cls)
{
return cls.MyData+ " Extension Print";
}
}
var cls = new ExtClass();
cls.MyData = "Raj";
@ViewBag.MyPrint = cls.Print();
@ViewBag.MyExtPrint = cls.ExtensionPrint();
Comments
Post a Comment