Thursday, October 3, 2013

What use of Is & as Operator?

"Is" operator

It is useful when we want to check whether one object belongs to particular class or not?. Have a look on below code using

class Test
{
public string Name { get; set; }
}
class Test1:Test
{
public string Surname { get; set; }
}
class Program
{
public static void Main(String[] args)
{
Test t = new Test();
if (t is Test1)
Console.WriteLine("t is object of Test1");
else
Console.WriteLine("t is not object of Test1");
Console.ReadLine();
}
}

"as" operator

as operator is useful when we want to convert one type to another type. But we have to keep in mind that both type should be compatible. Means by applying boxing and unboxing concept it should possible to convert one type to another type.
Let’s see by example.

class Test
{
public Test() { }
public string Name { get; set; }
} class Test1 : Test
{
public Test1() { }
public string Surname { get; set; }
}
class Program
{
public static void Main(String[] args)
{
Test1 t1 = new Test1();
t1.Name = "Mohan";
t1.Surname = "subramanian";
Test t = new Test();
t = t1 as Test;
Console.WriteLine("Name:-" + t.Name);
Console.ReadLine();
}
}

Here is sample output: Name:- Mohan

No comments:

Post a Comment

Abstract Factory Vs Factory Method

Abstract Factory Provides an interface for creating families of related or dependent objects without specifying their concrete classes ...