Javier Carreño
Javier Carreño

Reputation: 3

C# - specific type method declaration inside a generic class

I'm trying to achieve a general purpose "mutable" method using a generic class, i don't know if C# can achieve this. I'll explan the situation: I have a class that represents an entity in a database whose properties are marked with attributes [PrimaryKey] and [Field]. Example:

    public class Car :TableEntity
    {
         [Field]
         [PrimaryKey]
         public string RegNumber{get;set;}
         [Field]
         public string Color{get;set;}
    }

What I try to achieve is that instantiating a generic class using a TableEntity class, the .GetOne() method automatically change its parameters to be those of the primary keys, but I have not been able to find an elegant way to do it.

For example, i have:

public class BusinessObject<T> where T:TableEntity
{
public T GetOne(); //this is the method to modify depending on which type is T
}

and if i do

BusinessObject<Car> BO = new BusinessObject<Car>();

i should see in the Intellisense:

BO.GetOne(string RegNumber);

Is there a way or a workaround to achieve this? I know that using System.Reflection i can extract the parameter names and types which are marked as [PrimaryKey], but i don't know if i can modify a method declaration "on the air".

Thank you very much!

Upvotes: 0

Views: 91

Answers (2)

Siva Gopal
Siva Gopal

Reputation: 3502

C# is statically typed language from CLR point of view, hence for sure it does not allow for on-the-fly changes but if you touch DLR available from .Net4.0 onwards you have to sacrify intellisense luxury.

As an alternative you may modify the core class/interface to accept generic parameter as well along with other parameters.

Upvotes: 0

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51430

You'd have to add a generic parameter and propagate it:

public abstract class TableEntity<TKey>
{
}

public class BusinessObject<TEntity, TKey>
    where T : TableEntity<TKey>
{
    public TEntity GetOne(TKey key)
    {
        // ...
    }
}

Upvotes: 1

Related Questions