C# how to avoid typecasting to subclass?

.net, c#, subtyping

Solution

You can use generics for this, even without reflection. This sample uses the parameterless constructor filter on `T` (sample altered from Adil):

public T GetShape<T>() where T : Shape, new()
{
    return new T();
}

Problem

Let's say I have a base class called Shape. And then some sub classes such as circle and square. Let's then create a method in another class called GetShape: ``` public Shape GetShape() { return new Circle(); } ``` Alright, so the idea is, that I can pass in a shapeType and then get a strongly typed Shape subclass returned. The above example is a massive simplification of real code, but I think it gets the point across. So how when I call this method it would look like ``` var shapeCreator = new ShapeCreator(); Circle myCircle = shapeCreator.GetShape(); ``` Only problem is it won't even run, since it requires a cast. This would actually work: ``` Circle myCircle = (Circle) shapeCreator.GetShape(); ``` I'm not wild about that cast, how can I avoid it and still accomplish a way to have a method return a baseclass so that I can return any compatible subclass.

Original source