Extensions Methods in C#

Pranjal Mehta
Nov 2 · 2 min read

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 :

  1. It is a static method.
  2. It should be in a static class.
  3. In this method, the parameter should contain this keyword to define the type after you want to use it.
  4. To use this method with the define type use Dot(.) after the variable of the same type.
  5. 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.
  6. 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……

Pranjal Mehta

Written by

Software developer at Technovert(keka HR)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade