Generic function creates generic object of arguments base

I have the following code:

public class Foo
{
    public void DoSomething()
    {
        DoSomething(this);
    }

    private static void DoSomething<T>(T obj)
    {
        var generic = new Generic<T>();
    }
}

public class Bar : Foo
{
    // properties/methods
}

public class Generic<T>
{
    // properties/methods
}

public class Test
{
    public void TestMethod()
    {
        var bar = new Bar();
        bar.DoSomething(); // instantiates Generic<Foo> instead of Generic<Bar>
    }
}

Is it possible to instantiate a generic class from a derived method with the current type instead of the base type?

Jon Skeet
people
quotationmark

The compile-time type of this within Foo.DoSomething is just Foo, so the compiler can only infer the type argument as Foo.

The simplest way of getting it to do it based on the execution-time type is probably:

DoSomething((dynamic) this);

Alternatively, you could call it with reflection yourself.

people

See more on this question at Stackoverflow