tmm360 tmm360 - 1 year ago 65
C# Question

Pattern matching with generic arguments in C#

In C# I've a situation like this:

class ModelBase<TKey>
{
TKey Id { get; set; }
}

class Repo<TModel, TKey> :
where TModel : ModelBase<TKey>
{
//code where I access both TModel and TKey types
}


In my Repo class, I need to access both the
TModel
and
TKey
, but when I specific the
TModel
argument, a pattern matching system should be able to extract the
TKey
automatically.

For use the
TKey
generic type, I have to declare it as a generic argument, so every time that I need to create a Repo, I have to specific model and relative key types. How could I remove the need of explicit the key type, and extract it by pattern matching? A solution that uses verification at compile time is preferred.

Answer Source

I think a workaround for this might be declaring a non-generic type with a single property to store the primary key type. Then the generic type could inherit from that and set the property in the constructor.

Something like this:

class ModelBase
{
    public Type KeyType { get; set; }
}

class ModelBase<TKey> : ModelBase
{
    public TKey Id { get; set; }

    public ModelBase()
    {
        KeyType = typeof(TKey);
    }
}

class Repo<TModel> where TModel : ModelBase, new()
{
    // code where I access both TModel and TKey types
    public void Test()
    {
        var modelType = typeof(TModel).Name;
        var keyType = new TModel().KeyType.Name;
        Console.WriteLine($"{modelType}     {keyType}");
    }
}

Would allow you to write code like this:

 class MyIntEntity : ModelBase<int>
{
    public int Id { get; set; }
}

class MyStringEntity : ModelBase<string>
{
    public string Id { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var repoIntegerKey = new Repo<MyIntEntity>();
        var repoStringKey = new Repo<MyStringEntity>();

        repoIntegerKey.Test(); // prints "MyIntEntity        Int32"
        repoStringKey.Test();  // prints "MyStringEntity     String"
        Console.ReadLine();
    }        
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download