difference between GetType() method , is operator and typeof operator
-
Can anyone tell me difference between GetType() method, is operator and TypeOf() operator I'll be very much thankful to you. Regards. Ruchir. RuchirDhar Dwivedi Software Engineer Windowmaker Software Pvt.Ltd. Baroda, India.
The typeof operator returns an instance of System.Type corresponding to the class name you passed it to. You can't determine the type of an object using the typeof operator. For example
class Foo{}
class Test
{
public static void Main(string []args)
{
Console.WriteLine(typeof(Foo)); //Prints Foo
Foo f = new Foo();
Console.WriteLine(typeof(Foo)); //Does NOT work.
}
}The
GetType
function gets you the runtime type of an object. Note that it is the *runtime* type and not the static type. For eg.public void SomeFunc()
{
object obj = new Foo();
Console.WriteLine(obj.GetType());
}will print Foo and not Object. The is operator checks the runtime type of the arguments and sees if the LHS is (or can be cast to) the RHS. It returns true if the casting can succeed and false otherwise. For eg
public void SomeFunc()
{
Foo f = new Foo();
Console.WriteLine(f is Foo); //Prints true.
object obj = new Foo();
Console.WriteLine(obj is Foo); //Prints true
object obj2 = new object();
Console.WriteLine(obj2 is Foo); //Prints false
}Hope this helps. Regards Senthil _____________________________ My Blog | My Articles | WinMacro