0

I'm trying to add an extension method to int called TryParseNull that takes a string as input and returns the converted integer if successful or null if the string is not a valid integer.

I followed the doubleMe example from this post: using extension methods on int

My extension method is declared like this:

public static class IntExtensions {
    public static int? TryParseNull(this string s) {
        int dummy;
        int? value;
        if (int.TryParse(s, out dummy)) {
            value = dummy;
        }
        else {
            value = null;
        }
        return value;
    }
}

But when I try to use it like this the compiler complains that it doesn't know what TryParseNull is. I tried both of the below.

int? myNum = int?.TryParseNull("1");
int? myNum = int.TryParseNull("1");

Edit: I think the problem is the parameter this string s, but I'm passing in a string so I'm not sure how to rectify that.

Edit 2: From the answers below I can see what the problem is, but is there a way to have the syntax int.TryParseNull("1")?

Legion
  • 3,922
  • 8
  • 51
  • 95

4 Answers4

3

Extension methods work on instances of their 'this' parameter, not on the types.

Instead of

int? myNum = int?.TryParseNull("1");

Try

int? myNum = "1".TryParseNull();

Edit: Incidentally, you can also call the method statically with the 'this' parameter as the first argument.

int? myNum = IntExtensions.TryParseNull("1");
Kelson Ball
  • 948
  • 1
  • 13
  • 30
3

Try

int? myNum = "1".TryParseNull();

Your method is extending string, not int?. It does return int?

DPac
  • 515
  • 2
  • 8
0

int is a framework provided type and the extension method you added was not originally part of the int implementation, so you cannot call it using the Type directly, you would need to call it on the instance of int as others have pointed.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0

Based on your edit, you're trying to add a static method to an existing class. See the below: Can I "add" static methods to existing class in the .NET API?

Short answer is you can't, extension methods only work for instances.

Community
  • 1
  • 1