Forum C# Dynamically create instance of a class.

Dynamically create instance of a class.

Postby Vania » August 16th, 2011, 6:54 pm

Stackoverflow recommended something like this:

void someMethod(Type t)
{
object myInstance = (t.GetConstructor(null)).Invoke(null)
}

or like this:

void someMethod<T>(T type) where T : new()
{
object myInstance = new T();
}

but none of these methods work because they use classes forbidden by playerio.
Anyone know some way to do this that is compatible with playerio?
Vania
 
Posts: 198
Joined: March 24th, 2010, 9:01 pm

Re: Dynamically create instance of a class.

Postby Oliver » August 29th, 2011, 3:56 am

Hey,

Reflection is not allowed in Player.IO code. What are you trying to accomplish? Can you give some more context?

Best,
Oliver
User avatar
Oliver
.IO
 
Posts: 1159
Joined: January 12th, 2010, 8:29 am

Re: Dynamically create instance of a class.

Postby Vania » August 29th, 2011, 5:26 am

I was just trying to write a bytearray serializer,
the serializer would read an Integer which tells it the type of the object that's coming next, then uses that type to look into a Hashtable for the appropiate class. Then it would create a new instance of that class and initialize it ( the class implements an interface to provide the serialization methods )
Vania
 
Posts: 198
Joined: March 24th, 2010, 9:01 pm

Re: Dynamically create instance of a class.

Postby Henrik » August 29th, 2011, 7:32 pm

Vania wrote:I was just trying to write a bytearray serializer,
the serializer would read an Integer which tells it the type of the object that's coming next, then uses that type to look into a Hashtable for the appropiate class. Then it would create a new instance of that class and initialize it ( the class implements an interface to provide the serialization methods )

Will you really have that many different types of objects? I'd just make a switch statement and hardcode each class in there.

Slightly unrelated, this is a seriaizer/deserializer for primitives that we're using: http://code.google.com/p/beitmemcached/ ... ializer.cs
Henrik
.IO
 
Posts: 1880
Joined: January 4th, 2010, 1:53 pm


Return to C#