Mega Code Archive

 
Categories / C# Book / 09 Reflection
 

0619 Base Types and Interfaces

Type exposes a BaseType property: using System; using System.Reflection; using System.Collections.Generic; class MainClass { static void Main() { Type base1 = typeof(System.String).BaseType; Type base2 = typeof(System.IO.FileStream).BaseType; Console.WriteLine(base1.Name); // Object Console.WriteLine(base2.Name); // Stream } } The output: Object Stream The GetInterfaces method returns the interfaces that a type implements: using System; using System.Reflection; using System.Collections.Generic; class MainClass { static void Main() { foreach (Type iType in typeof(Guid).GetInterfaces()) Console.WriteLine(iType.Name); } } The output: IFormattable IComparable IComparable`1 IEquatable`1 The following code does the static and dynamic interface type checking. using System; using System.Reflection; using System.Collections.Generic; class MainClass { static void Main() { Type target = typeof(IFormattable); bool isTrue = target is IFormattable; // Static C# operator bool alsoTrue = target.IsInstanceOfType(target); // Dynamic equivalent } }