The community is working on translating this tutorial into Hebrew, but it seems that no one has started the translation process for this article yet. If you can help us, then please click "More info".
The right Type
The Type class is the foundation of Reflection. It serves as runtime information about an assembly, a module or a type. Fortunately, obtaining a reference to the Type of an object is very simply, since every class that inherits from the Object class, has a GetType() method. If you need information about a non-instantiated type, you may use the globally available typeof() method, which will do just that. Consider the following examples, where we use both approaches:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace ReflectionTest
{
class Program
{
static void Main(string[] args)
{
string test = "test";
Console.WriteLine(test.GetType().FullName);
Console.WriteLine(typeof(Int32).FullName);
Console.ReadKey();
}
}
}
We use the GetType() method on our own variable, and then we use the typeof() on a known class, the Int32. As you can see, the result in both cases is a Type object, for which we can read the FullName property.
At some point, you might even only have the name of the type that you're looking for. In that case, you will have to get a reference to it from the proper assembly. In the next example, we get a reference to the executing assembly, that is, the assembly from where the current code is being executed from, and then we list all of it's types:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace ReflectionTest
{
class Program
{
static void Main(string[] args)
{
Assembly assembly = Assembly.GetExecutingAssembly();
Type[] assemblyTypes = assembly.GetTypes();
foreach(Type t in assemblyTypes)
Console.WriteLine(t.Name);
Console.ReadKey();
}
}
class DummyClass
{
//Just here to make the output a tad less boring :)
}
}
The output will be the name of the two declared classes, Program and DummyClass, but in a more complex application, the list would probably be more interesting. In this case, we only get the name of the type, but obviously we would be able to do a lot more, with the Type reference that we get. In the next chapters, I will show you a bit more on what we can do with it.