tags:

views:

201

answers:

5

I read some properties from an xml file, amongst which is a string that refers to an llblgen object for example 'article'. For now I have set up a rather long

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

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

(the above is vb.net, but c# examples are fine as well)

+2  A: 

You could store the type names in the file and use:

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

(that would work as long as Some.Type.String has a default parameterless constructor.)

cfeduke
+1  A: 

Do the strings exactly represent the name of the object type. If so you could probably do.

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

so if you had the types coming back from a list you could do...

List<object> list = new List<object>();


foreach(string typename in GetFromXMLFile())
{
   list.Add(Activator.CreateInstance("AssemblyName", typename);
}
Eoin Campbell
A: 

Notice that Activator.CreateInstance has got a generic version that makes a cast to a base class unnecessary (if such a base class or interface is available):

public static IMyTrait MakeMyTrait(Type t) {
    return Activator.CreateInstance<IMyTrait>(t);
}
Konrad Rudolph
A: 

Ah very nice. Not sure if the objects are exactly as in the file, but I rather edit that file than keep on using that ugly select case thingy :).

Thanks for the suggestions !

Morph
+3  A: 

you could create a dictionary mapping strings to factory methods eg

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

Then your case statement becomes

return _map[myString]();
Oliver Hallam