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