Sunday, January 15, 2012

in C# call .GetType() on any object to make a new object of the type of Type

In writing some code with Azadeh today, Reflection started to make more sense to me. One may call .GetType() on any object to make a new object of the type of Type. The new object will have properties such as FullName which reveals the name of the original object and methods like GetMethods() which returns an array of MethodInfo objects that have data notes for each of the methods hanging off the object. Cool stuff. This was one of those ah-ha moments for me.

public void Whatever()

{

   Person person = new Person();

   MakeSenseOfObject(person);

}

   

public void MakeSenseOfObject(object obj)

{

   Type type = obj.GetType();

   string nameOfObject = type.FullName;

   MethodInfo[] methods = type.GetMethods();

   foreach (MethodInfo method in methods)

   {

      string methodName = method.Name;

      
more code follows and goes where you'd like...

No comments:

Post a Comment