0

Possible Duplicate:
Create class instance in assembly from string name

Using a string representation of the Type MyClass I want to create an instance of MyClass from a string representation of it.

See the comments in my code:

interface MyData
{
    string Value { get; }
}

class MyClass : MyData
{
    public MyClass(string s)
    {
        Value = s;
    }

    public string Value { get; private set; }

    public static explicit operator MyClass(string strRep)
    {
        return new MyClass(strRep);
    }

    public static implicit operator string(MyClass inst)
    {
        return inst.Value;
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyClass inst = new MyClass("Hello World");

        string instStr = inst; //string representation of MyClass
        string instTypeStr = inst.GetType().FullName;

        // I want to be able to do this:
        MyData copyInst = (instTypeStr)instStr; // this would throw an error if instTypeStr did not inherit MyData

        // Then eventually:
        if (instTypeStr.Equals("MyClass"))
        {
            MyClass = (MyClass)copyInst;
        }
    }
}
Community
  • 1
  • 1
Cheetah
  • 13,785
  • 31
  • 106
  • 190
  • possible duplicate of [Create class instance in assembly from string name](http://stackoverflow.com/questions/12433451/create-class-instance-in-assembly-from-string-name) or http://stackoverflow.com/questions/648160/ or http://stackoverflow.com/questions/223952/c-sharp-create-an-instance-of-a-class-from-a-string and so on and so on – David Heffernan Jan 11 '13 at 16:49
  • How's this: http://stackoverflow.com/questions/1044455/c-sharp-reflection-how-to-get-class-reference-from-string – JLRishe Jan 11 '13 at 16:49

2 Answers2

0

You can use Activator.CreateInstance method

Link : http://msdn.microsoft.com/fr-fr/library/d133hta4(v=vs.80).aspx

Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51
0

You should learn about Serialization.

To persist your class data to string you should serialize your MyClass object to string. To retrive your class data from string you should deserialize your MyClass object from string.

XmlSerializer will help you

Alexander Balte
  • 900
  • 5
  • 11