Decase
Decase

Reputation: 25

Show method only under certain conditions

I created a .net extension method that converts an string to an integer and throws an InvalidCastException if the passed string isn't an integer:

public static int ToInt32(this String str)
    {
        int result;

        // string is not a valid 32 bit integer
        if (!Int32.TryParse(str, out result))
            throw new InvalidCastException();

        return result;
    }

Is it possible do don't show up / offer the method on the string object if it isn't an integer?

Upvotes: 1

Views: 177

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70681

Is it possible do don't show up / offer the method on the string object if it isn't an integer?

No. Even if the parameter were a literal, the C# language doesn't have a mechanism for restricting method overloads according to parameter values. And of course, there's no requirement you can make that the method argument be provided as a literal. A variable or other expression used to provide the argument could be literally any string, and the compiler has no way to identify the nature of the argument (i.e. check whether it could be parsed as an integer).

Depending on what you're trying to do, you might be able to solve the broader problem with a Roslyn code analyzer. That's a whole other "ball of wax" though.

Upvotes: 1

Related Questions