tags:

views:

133

answers:

1

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?

+5  A: 

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.

Mehrdad Afshari
Thanks you. I didn't think of making the complete class generic in the way you descibe, but it works and causes little syntax overhead.
Thies