Legion Legion - 3 months ago 9
C# Question

Can't add TryParseNull extension method to int in C#

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")
?

Answer

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");
Comments