sing .NET reflection we can attempt to access properties and function solely with their name.
The System.Reflection namespace holds a variety of classes and functions that takes C# programming to another level.
we accessed the Location property of myObject. We can also do the same through reflection:
Type t = myObject.GetType();
PropertyInfo p = t.GetProperty("Location");
Point location = (Point)p.GetValue(myObject, null);
Of course, PropertyInfo is location under the System.Reflection namespace. Notice that the code becomes significantly more complicated and susceptible to mistakes. For example, in the first example, trying to access a property that does not exist would trigger a compiler error. On the other hand, the example with Reflection compiles just fine no matter what property we try to access. The error will come up during run-time.
et’s take showMessage from our example above. The function does not return a value and does not take parameters. To call it with .NET reflection it would be done something like so:
Type t = this.GetType();
MethodInfo method = t.GetMethod("showMessage");
method.Invoke(this, null);
A word of warning. If you get a null-object exception that means the method was not found. The method has to be public for it to be able to be invoked through reflection. Also obfuscating the C# application can potentially cause the name of the method to change, which will cause the code to fail. These are just things to keep in mind.
Now let’s try to invoke the multiply function from the example above, which takes parameters and returns a value. The code is not all that different:
Type t = this.GetType();
MethodInfo method = t.GetMethod("multiply");
int result = (int)method.Invoke(this, new object[] { 3, 4 });