Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# how to avoid typecasting to subclass?

Tags:

c#

.net

subtyping

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.

like image 720
JL. Avatar asked Dec 25 '22 08:12

JL.


1 Answers

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();
}
like image 152
Patrick Hofman Avatar answered Jan 03 '23 06:01

Patrick Hofman