2

Good day,

I've been searching around the google and stackoverflow quite some time, but havent got the answer yet. (At least not the answer i would like :) )

So, here's a quick example of my underlying code:

public interface IITem<IdType>
{
    IdType Id { get; set; }
}

public class Item<IdType> : IITem<IdType>
{
    public IdType Id { get; set; }
}    

public class MyItem : Item<Guid>
{
}

Now, i would like to create a generic ID getter, something like this:

private static TId GetId<TItem, TId>(TItem e) where TItem : IITem<TId>
{
    return e.Id;
}

So far it's good, but now, when i want to use it like next example, i get an error mentioned in title:

var item = new MyItem()
{
    Id = Guid.NewGuid()
};
var id = GetId(item);

It does work, when i explicitly say all the types for it like that:

var id = GetId<MyItem, Guid>(item);

But i don't want to name my item, and even less the ID type (that is defined inside MyItem and not seeable directly in GetId() usage scope) which can be completely different for some objects.

Is there any kind of syntax fix i could make so i would get this GetId() working without hinting any types for it?

Thank you!

GigAHerZ
  • 53
  • 6

1 Answers1

1

What purpose do the generic constraints serve on GetId?

Just use the generic interface type directly:

private static TId GetId<TId>(IITem<TId> e)
{
    return e.Id;
}
Jacob Krall
  • 28,341
  • 6
  • 66
  • 76
  • It's part of a bigger project. I stripped the code down to only leave the actual problem into the example. But thank you! It seems i have been overthinking, getting too much types involved. Seems to be working great! – GigAHerZ Jul 03 '18 at 18:29
  • Glad to help. See https://stackoverflow.com/a/8511493/3140 for another question about the C# type inferencer ignoring generic constraints. – Jacob Krall Jul 03 '18 at 18:31