Mou
Mou

Reputation: 16282

Type inference with generic methods

here is the code

class Program
{
    public static bool IsGreaterThan<T>(T x, T y) where T : IComparable<T>
    {
        return (x.CompareTo(y) > 0);
    }

    static void Main(string[] args)
    {
        var result = IsGreaterThan(20,10);
        Console.WriteLine(result); 
    }

}

Just see when calling a generic method like IsGreaterThan(20,10); then type INT is not passing... so how is it working? They should call it like IsGreaterThan<int>(20,10)

If the method signature would be like public static bool IsGreaterThan<INT>(T x, T y) where T : IComparable<T> then should it work or not if we call method without specifying type like IsGreaterThan(20,10); this way? ....thanks

Upvotes: 0

Views: 1238

Answers (2)

hungryMind
hungryMind

Reputation: 6999

You should declare method like this

public static bool IsGreaterThan<T>(T x, T y) where T : IComparable { return (x.CompareTo(y) > 0); }

otherwise you will get compile error "Constraints are not allowed on non-generic declarations"

To call the method, you can pass the type

    var result = IsGreaterThan<int>(20, 10);
    Console.WriteLine(result);

You can however ignore Type int while calling, if parameters are of same type. Compiler takes care of type resolver as explained by Jon

Upvotes: 1

Jon Grant
Jon Grant

Reputation: 11530

You can omit the type argument and the compiler will infer it.

The same rules for type inference apply to static methods as well as instance methods. The compiler is able to infer the type parameters based on the method arguments you pass in; it cannot infer the type parameters solely from a constraint or return value. Therefore type inference does not work with methods that have no parameters. Type inference takes place at compile time before the compiler attempts to resolve any overloaded method signatures. The compiler applies type inference logic to all generic methods that share the same name. In the overload resolution step, the compiler includes only those generic methods on which type inference succeeded.

http://msdn.microsoft.com/en-us/library/twcad0zb(v=vs.80).aspx

Upvotes: 1

Related Questions