Search code examples
c#extension-methodsnullablesignaturetryparse

TryParse for other types


I want to make a method int.TryParse(string, out int number), but the number should be a null if it can't Parse instead of 0.

I have seen some other solutions, but none of them seem to actually allow for an entry type to be defined.

Basically what I'm asking is:

How can I change the "int" in int.TryParse to something else, e.g. int?.TryParse

    public static bool TryParse(this int? i, string input, out int? output)
    {
        var IsNumber = int.TryParse(input, out int result);

        if (!IsNumber)
            output = null;
        else
            output = result;
        return IsNumber; 
    }

This is what I have so far, but now I have to make an object of int? in order to use it instead of just being able to directly use it on the int? type.

What I have:

        var _string = Console.ReadLine();
        int? nInt = null;
        var IsNumber = nInt.TryParse(_string, out int? result);

What I want:

        var _string = Console.ReadLine();
        var IsNumber = int?.TryParse(_string, out int? result);

Stuff I checked:

Convert string to nullable type (int, double, etc...)

TryParse Nullable types generically


Pseudo-Answer:

public class Int
{
    public static bool TryParse(string input, out int? output)
    {
        var IsNumber = int.TryParse(input, out int result);

        if (!IsNumber)
            output = null;
        else
            output = result;
        return IsNumber;
    }
}

which can be then used as

var IsNumber = Int.TryParse(_input, out int? result);

returning a boolean and an instance 'result' having a value of int or null.


Solution

  • You can't overload the Nullable<T> struct where T in an int here. Therefore you have to resolve to another way to be able to call that method.

    You seems to be trying to make an extension method on int?, which actually it should be on string, and then you have to use a string instance to call it:

    public static bool TryParse(this string input, out int? output)
    {
        var IsNumber = int.TryParse(input, out int result);
    
        if (!IsNumber)
            output = null;
        else
            output = result;
        return IsNumber; 
    }
    

    Call it:

    yourStringInstance.TryParse(out int? result);