2

In Delphi, when i want to create an object from uncertain derived class, i was using class of statement;

TShape = class
public
  procedure Draw;
end;

TCircle = class(TShape)
public
  procedure Draw;
end;

TShapeClassRef = class of TShape;

and i was creating object as;

var
  ref:TShapeClassRef;
  drawing:TShape;
begin
  ref:=TCircle;
  drawing:=ref.Create;
  drawing.draw; //this is a circle object, and it draws circle
end;

I couldn't find anything like that in c#.

2
  • 1
    Are you looking for something like Activator.CreateInstance(yourTypeGoesHere)? Commented Jul 8, 2015 at 6:39
  • C# does not have metaclasses. So no direct analog. Yes you can use reflection but I really don't like that. I personally think the best way is as I wrote in an answer at the linked dupe: And yet another option is to replace your dictionary of classes with a dictionary of delegates that return a new instance of your object. With lambda syntax that option yields very clean code. Commented Jul 8, 2015 at 7:11

1 Answer 1

3

Use Type like this:

public class TShape { }

And:

Type t = typeof(TShape);

To initialize an object through t variable, use Activator.CreateInstance(t):

Shape shp = (Shape)Activator.CreateInstance(t);
Sign up to request clarification or add additional context in comments.

4 Comments

that's just the half of my question, how should i initialize an object through "t" variable Type t = typeof(TCircle); Shape shp = new t(); ?
Like this: Shape shp = (Shape)Activator.CreateInstance(t); see my Updated answer.
thank you so much, you've been realy helpfull :)
How to pass parameters to the constructor?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.