Sunday, 28 April 2013

Can I get the name of a type at runtime? | C#.Net Interview Questions

Yes, use the GetType method of the object class (which all types inherit from).
For example:
using System;
class CTest
{
class CApp
{
public static void Main()
{
  long i = 10;
  CTest ctest = new CTest();
  DisplayTypeInfo( ctest );
  DisplayTypeInfo( i );
}
static void DisplayTypeInfo( object obj )
{
Console.WriteLine("Type name={0}, full type name={1}", obj.GetType(), 
obj.GetType().FullName );
}
}
}
produces the following output:
Type name = CTest, full type name = CTest
Type name = Int64, full type name = System.Int64

No comments: