C # method to return type

I have a couple of classes that are identified by some identifier (which is a unique integer for each class). Then I need a method that takes an integer (ID) as an argument and returns the corresponding class type. So far I have come to this:

public static Type GetById(int id) { switch (id) { case 1: return (new ClassA()).GetType(); case 2: return (new ClassB()).GetType(); case 3: return (new ClassC()).GetType(); // ... and so on } } 

At the moment it seems that it works, but for some reason I don’t like that I need to instantiate the class to get its type. Could this cause problems?

Another solution that I found is to use the Type.GetType (classNameAsString) method, but I assume that this can lead to some errors or runtime errors if the class name changes (i.e. I change the class name, but forgot update the GetById method).

Is there a better way to do this?

+6
source share
3 answers

Use typeof instead

 public static Type GetById(int id) { switch (id) { case 1: return typeof(ClassA); case 2: return typeof(ClassB); case 3: return typeof(ClassC); // ... and so on } } 

As a side note, I would seriously question this whole design - it seems strange to me to compare types with integers.

+19
source

Why don't you just declare a dictionary?

  private static Dictionary<int, Type> types = new Dictionary<int, Type>() { {1, typeof(ClassA)}, {2, typeof(ClassB)}, {3, typeof(ClassC)}, ... and so on }; public static Type GetById(int id) { Type result = null; if (types.TryGetValue(id, out result)) return result; return null; // or throw exception } 
+13
source

Another alternative could be to create enum :

 public enum ClassType { ClassA = 1, ClassB = 2, ClassC = 3 } 

And then changing your method to accept this enum and return the type:

 public static Type GetById(ClassType id) { //Will return null if the Type is not found, //Add true as a second parameter to throw if not found return Type.GetType(id.ToString()); } 

This will remove the magic numbers from your code, but will only work as long as the class names match the enum parameters. This will make your code much smaller, but as pointed out by others, you should really question your application design because it is not entirely correct.

+1
source

All Articles