Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;}
}
like image 760
Arian Avatar asked Dec 08 '22 07:12

Arian


2 Answers

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.

like image 157
Sriram Sakthivel Avatar answered Dec 11 '22 08:12

Sriram Sakthivel


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#

like image 31
Sergey Krusch Avatar answered Dec 11 '22 06:12

Sergey Krusch