Jeff Adkins' WebLog

Sr. Software Design Engineer, Microsoft

CSharpBits:Reflection

Reflection

You can obtain information about the type of an object by using a mechanism called reflection.

The reflection mechanism in C# is handled by the System.Reflection namespace in the .NET Framework. This namespace contains classes and interfaces that provide a view of types, methods, and fields.

The System.Type class provides methods for obtaining information about a type declaration, such as the constructors, methods, fields, properties, and events of a class. A Type object that represents a type is unique; that is, two Type object references refer to the same object only if they represent the same type. This allows comparison of Type objects through reference comparisons (the == and != operators).

The typeof Operator

At compile time, you can use the typeof operator to return the type information from a given type name.

The following example retrieves run-time type information for the type byte, and displays the type name to the console.

using System;
using System.Reflection;
Type t = typeof(byte);
Console.WriteLine("Type: {0}", t);

The following example displays more detailed information about a class. Specifically, it lists the methods for that class.

using System;
using System.Reflection;
Type t = typeof(string); // Get type information
MethodInfo[ ] mi = t.GetMethods( );
foreach (MethodInfo m in mi) {
  
Console.WriteLine("Method: {0}", m);
}

GetType Method

The typeof operator only works on classes that exist at compile time. If you need type information at run time, you can use the GetType method of the Object class.

Published Tuesday, February 17, 2004 2:36 PM by Jeff Adkins
Filed under:

Comments

 

Ron said:

Jeff,

If I have two classes in the *same* assembly, is it possible to get the methods/properties of Class B from Class A without using reflection. I can do it with Reflection (thanks to your article) but I read that Reflection is expensive.

Thanks,
-ron
March 15, 2004 1:22 PM
 

Jeff Adkins said:

You don't need to use reflection. If your class and methods/properties in Class B are public or internal, Class A will have access. If you don't want to provide access outside of the assembly, use internal as the access modifier.

An internal member is accessible from within any part of the same Microsoft .NET-based assembly. You can think of it as public at the assembly level and private from outside the assembly.
March 16, 2004 11:23 AM
 

ron said:


I apologize, I should have been more clear.
Is it possible to enumerate the methods/properties of a class without using reflection if both classes are in the same assembly?

Thanks
March 16, 2004 8:24 PM
Anonymous comments are disabled

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker