USING THIS IN PARAMETERS OF STATIC METHODS IN STATIC CLASS?

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
C# 
C#
 859  View(s)
Ratings:
Rate this:

Why should I use 'this' in static functions of static classes to objects in parameter? I mean is the real difference between using those 2 methods?

public static class Extensions

{

    public static string AsJson(this object obj)

    public static string AsJson2(object obj)

}

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Using this in parameters of static methods in static class?

    Hi Ankit,


    The first one is an extension method, whereas the second one is just a static method.

    The difference is in how you can call them:

    object myObj = new object();

    var result = myObj.AsJson();

    var result2 = Extensions.AsJson2(myobj);

    Note that you can also use the first one as a simple static method:

    var result3 = Extensions.AsJson(myObj);

    Essentially, it's just syntactical sugar. Upon compilation, the first statement will be transformed into the last one.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!