.NET: from string to object

I read some properties from the XML file, including a string that refers to an llblgen object, for example, an article. At the moment, I set a pretty long

Select Case myString Case "article" return New ArticleEntity() 

Etc. which gets pretty ugly as it gets longer and longer;). Is there a better way to do this?

(the above is vb.net, but C # examples are also great)

+4
source share
5 answers

you can create dictionary matching strings using factory methods like

 Dictionary<string, Func<Animal>> _map = new Dictionary { ("cat", () => new Cat()), ("dog", () => new Dog()) ... } 

Then your case statement will be

 return _map[myString](); 
+3
source

You can save type names in a file and use:

 return Activator.CreateInstance(Type.GetType("Some.Type.String")); 

(This will work as long as Some.Type.String has a constructor with no parameters, no parameters.)

+2
source

Lines exactly indicate the type name of the object. If so, you can probably do it.

  Object obj = Activator.CreateInstance("AssemblyName", "TypeName"); 

so if you have types returning from a list you can do ...

 List<object> list = new List<object>(); foreach(string typename in GetFromXMLFile()) { list.Add(Activator.CreateInstance("AssemblyName", typename); } 
+1
source

Note that Activator.CreateInstance has a generic version that makes throwing into the base class unnecessary (if such a base class or interface is available):

 public static IMyTrait MakeMyTrait(Type t) { return Activator.CreateInstance<IMyTrait>(t); } 
0
source

Ah, very nice. Not sure if the objects are exactly the same as in the file, but I rather edited this file than continue to use this ugly case of choice.

Thanks for the suggestions!

0
source

All Articles