0

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?"

LaVINCENT
  • 3
  • 2
  • 2
    You're looking for generics. – SLaks Nov 02 '16 at 01:39
  • 1
    @SLaks have a good suggestion.But I have a suggestion that you can try use ctrl + H. – lindexi Nov 02 '16 at 02:57
  • Your question is really unclear, could you explain a bit more? From what I've gathered you want to replace *the code* all at once? That's a question about your editor, really. – Rob Nov 02 '16 at 03:07
  • As @lindexi said, _Find and Replace_ is your friend. As what you said, you are not to do in run-time, which means all codes are just plain text, nothing related to programming. Or you talking inheritance? – Prisoner Nov 02 '16 at 04:10
  • Install ReSharper tool and it'll help you to refactor your code easily. – Aleksei Nov 02 '16 at 04:45

1 Answers1

1

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();
Martin Zikmund
  • 38,440
  • 7
  • 70
  • 91