Lee Yi
Lee Yi

Reputation: 527

C# Cannot find extension method for char struct

Basically, I have this extension method written up:

public static class Extensions 
{
    public static bool IsMaths(this Char it)
    {
        if (char.IsDigit(it) || char.IsControl(it)) { return true; }
        foreach (char each in new char[] { '-', '+', '(', ')', '/', '*', '%', '^', '.' })
        {
            if (each.Equals(it)) { return true; }
        }
        return false;
    }
}

When I try to call it:

else if (!Char.IsMaths(e.KeyChar)) { e.Handled = true; }

Visual Studio gives me the error that 'char' does not contain a definition for 'IsMaths'. Why is this so?

Upvotes: 3

Views: 221

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

Visual Studio gives me the error that 'char' does not contain a definition for 'IsMaths'. Why is this so?

Because an Extension Method works on an instance of a type, not the type itself. You're using static char methods, which is why it isn't possible.

You want to do:

else if (!e.KeyChar.IsMaths()) { e.Handled = true; }

Upvotes: 12

Related Questions