DooDoo
DooDoo

Reputation: 13447

Declare Generic method in non generic interface

Please consider this code:

public interface ImyInterface
{
    T GetEntity<T>(T t,int MasterID);
}

I declare a class name : MyEntity and it has a property with name A_1

public class BL_Temp : ImyInterface
{
    public MyEntity GetEntity<MyEntity>(MyEntity t, int MasterID)
    {
        t.A_1 = ""; //Error
        return t;
    }
}

the error is :

'MyEntity' does not contain a definition for 'A_1' and no extension method 'A_1' accepting a first argument of type 'MyEntity' could be found (are you missing a using directive or an assembly reference?)

Does it possible to declare a generic method in non generic interface?

where is my mistakes?

thanks


Edit1)

Consider MyEntity declaration is :

public class MyEntity
{
    public string A_1 {set; get;}
}

Upvotes: 5

Views: 8548

Answers (2)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73452

You can declare, but your method will be generic and not a specific type. I mean MyEntity is generic parameter, it is not your entity type.

You can add constraint to your entity like this, This allows you to to access Entity specific members..

public interface ImyInterface
{
    T GetEntity<T>(T t,int MasterID) where T : Entity;
}    

public class BL_Temp : ImyInterface
{
    public T GetEntity<T>(T t, int MasterID) where T : Entity
    {
        t.MyEntityProperty = "";
        return t;
    }
}

I know this is a sample code, but I felt worth mentioning that Your method shouldn't lie. Method name is GetEntity but it mutates the parameter which client may not be knowing (I'd say it lied). IMO you should atleast rename the method or don't mutate the parameter.

Upvotes: 15

Sergey Krusch
Sergey Krusch

Reputation: 1938

Even though you have class MyEntity, in this code

public MyEntity GetEntity<MyEntity>(MyEntity t, int MasterID)

MyEntity is treated as generic parameter. It looks like you want to achieve generic specialization. If so, read this: How to do template specialization in C#

Upvotes: 1

Related Questions