1

Possible Duplicate:
No type inference with generic extension method

I have a generic function with constrain which returns the first object in a collection:

static T first<T, L>(L list) 
where L : ICollection<T>            
where T : SomeType
{
        T r = default(T);
        if (list != null && list.Count>0)
        {
            if (list.Count == 1)
            {
                r = list.First();
            }
            else
            {
                //throw some exception ...
            }
        }
        return r;
 }

But when I use it against a collection the code won't compile and give me a "type cannot be inferred from usage" error:

ICollection<SomeType> list = funcReturnCollectionOfSomeType();
SomeType o = first(list);

Could not figure out why, is there anyone can help? Thank you.

Community
  • 1
  • 1
murphytalk
  • 1,297
  • 1
  • 9
  • 14

1 Answers1

2

It can't infer the type T backwards from the type L. Use a single generic parameter:

static T first<T>(ICollection<T> list) 
where T : SomeType
{
  ...
Guffa
  • 687,336
  • 108
  • 737
  • 1,005