typeof C# with Example



typeof C# with Example

Gets System.Type object for a type. 
System.Type type = typeof(Point) //System.Drawing.Point 
System.Type type = typeof(IDisposable) //System.IDisposable 
System.Type type = typeof(Colors) //System.Drawing.Color 
System.Type type = typeof(List<>) //System.Collections.Generic.List`1[T] 
To get the run-time type, use GetType method to obtain the System.Type of the current instance. 
Operator typeof takes a type name as parameter, which is specified at compile time. 
public class Animal {} 
public class Dog : Animal {} 
var animal = new Dog(); 
Assert.IsTrue(animal.GetType() == typeof(Animal)); // fail, animal is typeof(Dog) 
Assert.IsTrue(animal.GetType() == typeof(Dog)); // pass, animal is typeof(Dog) 
Assert.IsTrue(animal is Animal); // pass, animal implements Animal 

0 Comment's

Comment Form