Richard Galvez

Hello MSDN

I am having an issue with Generic functions. I am passing a generic type into a function but once I have done a few things with it I would like to type cast it to a particular type that is stored in a string. I'll show a code snippet to show the logic:

Code Snippet


private void task_StartTask<taskType>(string fileN) where taskType : Task
{
taskType task = Deserialize<taskType>(fileN);

string objType = task.GetType().ToString();

/*

Now we can see that objType has a string representation of task's object type. From here I would like to type cast task with it's own type so I can use methods defined specifically for that datatype like so..

*/


objType.ToObject() obj = new objType.ToObject() (); //


//Or using the type of the object:


task.GetType() obj = (task.GetType())task;

}


Is this possible Many thanks!












Re: Visual C# Language Converting from string to object type: difficult to explain!

Peter Ritchie

You've only got the type name, not an object of that type. The only thing you could do with a type name is create a new instance of that type.




Re: Visual C# Language Converting from string to object type: difficult to explain!

Richard Galvez

OK that's fine, but what would be the syntax for that




Re: Visual C# Language Converting from string to object type: difficult to explain!

UsualDosage

You might try something like the following:

Code Snippet

namespace DynamicObject

{

class Program

{

static void Main(string[] args)

{

Type t = Type.GetType("DynamicObject.TestClass");

object dynamicObject = Activator.CreateInstance(t);

Console.WriteLine(dynamicObject.ToString());

Console.ReadLine();

}

}

class TestClass

{

public override string ToString()

{

return "I'm a dynamic object!";

}

}

}