I loves reflection. I loves reflection all day long 🙂
Just now I found another nice usage of the not-even-real-reflection Object.GetType() method.
Say we got a framework that works with plugins implementing an abstract class:
public abstract class PluginBase { public string ClassName { get { GetType ().Assembly.GetName ().Version.ToString (); } } }
Sure we didn’t have to implement this in the actual PluginBase but if we´d by some reason need to use the class name in the plugin base class its good to know that the GetType() always returns the implementing class type.
So the following code:
public class SubClass1 : PluginBase { } public class SubClass2 : PluginBase { } void IteratePlugins () { var plugins = new PluginBase[] { new SubClass1 (), new SubClass2 () }; foreach (var plugin in plugins) System.Console.WriteLine (plugin.ClassName); }
Would give us the output:
SubClass1 SubClass2
GetType() is among the most useful class you would find when building frameworks in C#. GetType for president!