Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference current class type using generics

Tags:

c#

generics

I have a base class, with a method, where I would like to use generics to force the coder to use a generic expression on the current class:

public class TestClass
{
    public void DoStuffWithFuncRef<T>(Expression<Func<T, object>> expression) where T : TestClass
        {
            this.DoStuffWithFuncRef(Property<T>.NameFor(expression));
        }
}

Now, I would like to force T to be of the type of the instantiated class, which I hope will the cause the C# compiler to automatically understand the generic type to use. E.g. I would like to avoid coding the doStuff method below, where I have to specify the correct type - but rather use the doStuffILikeButCannotGetToWork method:

public class SubTestClass : TestClass
{
    public string AProperty { get; set; }

    public void doStuff()
    {
        this.DoStuffWithFuncRef<SubTestClass>(e => e.AProperty);
    }

    public void doStuffILikeButCannotGetToWork()
    {
        this.DoStuffWithFuncRef(e => e.AProperty);
    }
}

Is this possible? Should I be doing this in a different way?

like image 885
Thies Avatar asked Jan 15 '10 10:01

Thies


1 Answers

Make the base class itself generic:

public class TestClass<T> where T : TestClass<T>
{
    public void DoStuffWithFuncRef(Expression<Func<T, object>> expression)
    {
        this.DoStuffWithFuncRef(Property<T>.NameFor(expression));
    }
}

and derive from it:

public class SubTestClass : TestClass<SubTestClass> {
     // ...
}

If you need to have an inheritance hierarchy with a single root, inherit the generic base class from another non-generic version:

public class TestClass { ... }
public class TestClass<T> : TestClass where T : TestClass<T>

Of course you should probably make the base classes abstract.

like image 152
mmx Avatar answered Sep 21 '22 01:09

mmx