I have some classes that all implement a certain interface. I want to store a unique string in each class that I can get without creating an object for that class. I searched through a lot of posts here already and couldn’t find an answer.
If I create an object for each class, then what I want is simply:
class X:IBase{ string m = "x";}
class Y:IBase{string m = "x";}
class Z:IBase{string m = "x";}
class interface IBase{ string m;}
static int Main(){
IBase[] arr = {new X(), new Y(), new Z()};
foreach(IBase b in arr){
Console.WriteLine(b.m);
}
}
But I want to do this without creating an object. So I want to do this:
class X:IBase{ static string m = "x";}
class Y:IBase{ static string m = "x";}
class Z:IBase{ static string m = "x";}
class interface IBase{ //no static fields allowed}
static int Main(){
Type[] arr = {X, Y, Z};
foreach(Type t in arr){
Console.WriteLine(t.m); //error, cannot resolve symbol m
}
}
Am I missing something obvious or is this just impossible?
The reason I don’t want to create an object is because I want to display this string at the start, when I don’t need any objects. I only create an object when I need to to save space.
Reflection is your friend:
Note how
Type[] arr = {X, Y, Z};has been changed intoType[] arr = { typeof(X), typeof(Y), typeof(Z) };in order to get theTypeobject for each of the types.