Dynamically creating an object (Reflection?)

M

MarkusJNZ

Hi, given a name of an class e.g. "MyClass" which is stored as a string
is it possible to create a new instance of this type dynamically and
then reference the attributes by name in code??

e.g.

If my class is called Person and it has attributes FirstName and
LastName is it possible to do something like this;

public void GeneratePerson()
{

string className = "Person";
(CreateInstanceOfPerson) _person = new (CreateInstanceOfPerson);
_person.FirstName = "fred";
_person.LastName = "smith";
_person.AddName();

}

I did look at using reflection but can't seem to create an instance of
an object just given a string and then populate the object with
attrbutes.

Any help appreciated
Thanks
Markus
=======================
googlenews2006markusj
 
J

Jon Skeet [C# MVP]

Hi, given a name of an class e.g. "MyClass" which is stored as a string
is it possible to create a new instance of this type dynamically and
then reference the attributes by name in code??

e.g.

If my class is called Person and it has attributes FirstName and
LastName is it possible to do something like this;

public void GeneratePerson()
{

string className = "Person";
(CreateInstanceOfPerson) _person = new (CreateInstanceOfPerson);
_person.FirstName = "fred";
_person.LastName = "smith";
_person.AddName();

}

I did look at using reflection but can't seem to create an instance of
an object just given a string and then populate the object with
attrbutes.

You want Activator.CreateInstance to create the instance - or use
Type.GetType to get the type, and then fetch and invoke a constructor.
 
M

MarkusJNZ

Thanks Jon
Regards
Markus said:
You want Activator.CreateInstance to create the instance - or use
Type.GetType to get the type, and then fetch and invoke a constructor.
 
S

Steven Nagy

You also won't be able to get this kind of strong typing in your code:

_person.FirstName = "fred";

Objects created using reflection can have their properties and methods
referenced through a collection however. You can once again use the
string name of the field in order to find it. This code should be
pretty well documented in MSDN.

However, if at design time you know for sure the names of the
properties and methods (but not the class name), you might be able to
extract your common class aspects into an interface, then cast the
dynamically created object as an interface instance, and then use the
strongly typed names.

Hope this makes sense.

Steven
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top