tags:

views:

102

answers:

2

The method is this one, EntityBase.Get:

public class EntityBase
{
    public int Id;

    public static T Get<T>(int id) where T : EntityBase
    {
        DataContextExtender extender = new DataContextExtender();
        return extender.DataContext.GetTable<T>().Where(t => t.Id == id).FirstOrDefault();
    }
}

How I want to use it:

Event ev = Event.Get(EventId)

, where Event inherits EntityBase.

The method compiles by itself, like it is, but I get an error message if I want to use it that way:

The type arguments for method 'RiotingBits.Data.Entities.EntityBase.Get(int)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

I know I can use it like Event.Get<Event>(EventId), but I really want to use it 'my way'. The code for the method doesn't matter, I suspect there might be a way to hint the method how to infere the right type.

+3  A: 

I don't think so. I believe that types are only inferred based on the parameters to the method. So I think you're stuck with specifying the type of the class explicitly. See MSDN for more information.

Andy
+7  A: 

No, you can't. Type inference in C# doesn't take into account what you're trying to do with the returned value, nor does it take into account the class you used to refer to a static method. Type inference is horribly complicated, but ultimately it boils down to the static types of the arguments you've used to invoke the method.

If you only want to do it in a single type (Event) you could always create a new GetEvent static method in Event, which just called Get<Event>.

Jon Skeet
I liked you answer better simply because it was formulated more.. convincing :)But Andy got also a +1.Thanks.
Dan Dumitru
I wanted to do it, of course, in more types, all inheriting EntityBase. And having the Get method declared only once, in EntityBase, and using it for them all.But it looks I won't be able, at least the way I imagined it.
Dan Dumitru