Is the Extension method similar to the "new" keyword method in C #?

Could we have some relation between extension methods and inheritance?

Or an extension method similar to using new

-keyword in C #?

+3


source to share


4 answers


No for both questions. An extension method is actually a method that takes an object that the extension acts on as the first parameter.

The keyword is new

used to allocate resources for an instance of a class. An extension method works on an instance but cannot act as a new replacement, simply because the first parameter requires an instance (or of null

that type).

Consider:

public static class StringExtensions
{
    public static string Reverse(this string _this)
    {
        // logic to reverse the string
    }
}

      

This static method can be called in two ways:

// as an extension method:
string s = "hello world";
string t = s.Reverse();

// as a static method invocation:
string t = StringExtensions.Reverse(s);

      



In any case, the compiler changes the call to MSIL to match the second call. Once compiled, you won't be able to recognize the extension method from being a static instance without the this

-keyword.

Summing up

  • Extensions are not part of the class
  • Extensions have nothing to do with inheritance, in fact they are static methods that are not inherited
  • Extensions cannot instantiate like a keyword new

    (but inside a method, you can of course instantiate classes).
  • The extension can work on null

    where a method of this class would otherwise have promoted NullReferenceException

    . This follows from the fact that an instance is simply the first parameter in a static method.
  • It is possible to extend private classes (like the one string

    above), which is not possible through inheritance (you cannot get from sealed classes).

EDIT:
Tigran and Florent hinted that this question is about a new modifier and I added that it might even be about a new general limitation .

The extension method has nothing to do with the meaning of the keyword new

. Here are, however, some thoughts in relation to each other. Hope it doesn't bother you anymore. If so, stick to the "EDIT" part above;)

  • In the new modifier:

    • the new modifier is used to hide existing methods. An extension method can never hide existing methods because the declaration is a static method. When you do this, you won't even get a compilation error warning.
    • The new modifier requires the method (or property) to already exist and be available. An extension method can only work if a method with the same signature does not already exist.
    • The new modifier works with extending the class through inheritance, i.e. each method is already inherited. An extension method runs on an instance of the class and has no inheritance relationship with the class.
       
  • In the new generic constraint:

    • the constraint restricts the allowed generic types to those who have a parameterless constructor available. The extension method has nothing to do with generics.
    • the van extension method itself is generic, and the parameters (i.e. the allowed classes it runs on) can be constrained by a new generic constraint:

      // this ext. method will only operate on classes that inherit 
      // from ICollectible and have a public parameterless constructor
      public static int CalculateTotal<T>(this T _collectible)
          where T : ICollectible, new()
      {
          // calculate total
      }
      
            

+9


source


No, an extension method simply extends the functionality of an existing class.

Extension methods allow you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

See MSDN on Extension Methods (C # Programming Guide) .



The keyword is new

required for override

non-virtual and static methods from the base class.

public class A
{
   public virtual void One();
   public void Two();
}

public class B : A
{
   public override void One();
   public new void Two();
}

B b = new B();
A a = b as A;

a.One(); // Calls implementation in B
a.Two(); // Calls implementation in A
b.One(); // Calls implementation in B
b.Two(); // Calls implementation in B

      

Note the reference to new

vsoverride

.

+3


source


Not. An extension method is syntactic sugar for a separate static class that takes an extended object as its first argument. It has nothing to do with inheritance at all. This method only has access to the public members of the extended class, just like any other class.

+1


source


Extension methods are not related to inheritance or keyword new

(or constructors). They allow you to use more convenient code when you want to add some functionality to a class for which you don't have the source code. It also works if you have the source code, but then it's usually better to just change the source code.

For example, you might want to do this:

string text = "this is my string";
int count = text.WordCount();

      

This method does not exist in the class String

and you need to do it like this:

string text = "this is my string";
int count = MyCommon.WordCount(text);

      

where WordCount()

is a static method in your shared library.

But with extension methods, you can also do this:

public static class MyExtensions
{
    public static int WordCount(this String str)
    {
        return str.Split(new char[] { ' ', '.', '?' }, 
                         StringSplitOptions.RemoveEmptyEntries).Length;
    }
}

      

and then text.WordCount()

will work the same as if it was a normal method defined in the class String

. It just makes things more enjoyable to use.

Code taken from here , which I suggest reading as well.

0


source







All Articles