Reputation: 3
I'm studing the UWP coding in C#. I've done a little Grid with some rectangles:
Rectangle r = new Rectangle();
I've done it in many methods of class. I would create a generic type (for example as class or a variable) to fast change all Rectangles in Ellipse (for example), not at runtime. I mean something like:
Type ShapeType = typeof(Rectangle);
and create:
ShapeType figure = new ShapeType(); ...
but tomorrow be able to change
Type ShapeType = typeof(Rectangle);
in
Type ShapeType = typeof(Ellipse);
and change all the shapes in my code. Is this possible? How can I create a class "Rectangle-like" or "Ellipse-like" ?
Thank you
Marked as duplicate of: "Get a new object instance from a Type One may not always know the Type of an object at compile-time, but may need to create an instance of the Type. How do you get a new object instance from a Type?"
Where I've written that I want create an object at runtime? Or also only that i want create an object? My question is about "How to change (from code) easily the type defined in many line of code creating a generic type?"
Upvotes: 0
Views: 111
Reputation: 39102
The simplest solution would be to have a factory method that would create a new instance of the element you decide to use.
It could look like this:
private Shape CreateShape() => new Rectangle();
Because all Shape
elements in UWP have Shape
as a base class, you can use it as the return type of your method and as a "base" type in all places you use the shape.
You can now replace all the lines, where you created instances of Rectangle
with the following:
var shape = CreateShape();
If you later decide that you want to change the type to Ellipse
, you just change the code in one place - in the CreateShape
method:
private Shape CreateShape() => new Ellipse();
Upvotes: 1