Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extension method on type and nullable<type>

For sake of simplicity, let's assume I want to write an extension method for the type int? and int:

public static class IntExtentions
{
    public static int AddOne(this int? number)
    {
        var dummy = 0;
        if (number != null)
            dummy = (int)number;

        return dummy.AddOne();
    }

    public static int AddOne(this int number)
    {
        return number + 1;
    }
}

Can this be done using only 1 method?

like image 700
RandomProgrammer Avatar asked Apr 12 '09 20:04

RandomProgrammer


People also ask

Can you call extension method on null?

coalesce operator to help, but still it can be quite a lot of code. Through the use of extension methods a lot of cases can be handled. As extension methods are in reality static methods of another class, they work even if the reference is null . This can be utilized to write utility methods for various cases.

What is extension method with example?

An extension method is actually a special kind of static method defined in a static class. To define an extension method, first of all, define a static class. For example, we have created an IntExtensions class under the ExtensionMethods namespace in the following example.

What is correct extension method?

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.

What is extension method in OOP?

In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are features of some object-oriented programming languages.


2 Answers

Unfortunately not. You can make the int? (or whichever nullable type you are using) method call the non nullable method very easily though, so you don't need to duplicate any logic with 2 methods - e.g.

public static class IntExtensions
{
    public static int AddOne(this int? number)
    {
        return (number ?? 0).AddOne();
    }

    public static int AddOne(this int number)
    {
        return number + 1;
    }
}
like image 124
Steve Willcock Avatar answered Oct 19 '22 09:10

Steve Willcock


No you cannot. This can be verified experimentally by compiling the following code

public static class Example {
  public static int Test(this int? source) {
    return 42;
  }
  public void Main() {
    int v1 = 42;
    v1.Test();  // Does not compile
  }
}

You will need to write an extension method for each type (nullable and not nullable) if you want it used on both types.

like image 27
JaredPar Avatar answered Oct 19 '22 09:10

JaredPar