Extensions Methods in C#
Extension methods are the additional methods that can be used with existing types in .NET to give them more functionalities. An Extension Method is a static method to the existing static class. Extension methods can be added to your custom class, .NET framework classes, or third party classes or interfaces.
An Existing method is :
- It is a static method.
- It should be in a static class.
- In this method, the parameter should contain this keyword to define the type after you want to use it.
- To use this method with the define type use Dot(.) after the variable of the same type.
- Try to define the method in the same namespace or if you don’t define in the same namespace then import the namespace where you are using this method.
- This method can be used anywhere in your application by including the namespace of the extension method.
Now we will create Json Extension methods.
public static JsonExtensions{
public static string ToJson(this object obj)
{
return Json.Serialization(obj); // For converting object to JsonString.
} public static T FromJson(this string str)
{
return Json.Deserialization<T>(str); // For converting JsonString to generic type object.
}
}
Now we will use this extension methods with our types:
public Program{
static void Main()
{
string s,s1;
List<string> li = new List<string>();
List<string> strList = new List<string>();
strList = s.FromJson<List<string>>(); // It will convert JsonString to List Object s1 = li.ToJson(); // It will convert list to JsonString
}
}
Note:- Json.Serialization and Json.Deserialization is present in Newton.Json Package.
Note:- The key difference between the normal method and extension method is that the first parameter of the extension method specifies the type that it is going to an operator on, preceded by this keyword.
EAT -> SLEEP -> CODE ->EAT -> SLEEP -> CODE………….
If you liked this article please Share among all tech Geeks and make a CLAP for this article.
THANK YOU……
