C# as is

Both is and as are keywords in C#.

Syntax:

<Object> is <Type>

The above is expression returns true if the object <Object> is an instance of the type <Type> or a type which derives from <Type>; Otherwise returns false.

The is keyword is an operator in C# and cannot be overloaded.

Example 01-90-01

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;

class A {}
class B {}

public class Program
{
    static void Main()
    {
        object[] obj = new object[6];
        obj[0] = 1;
        obj[1] = new object();
        obj[2] = 2.0D;
        obj[3] = new A();
        obj[4] = new B();
        obj[5] = 3.0F;

        Console.WriteLine("Total = {0}", getTotal(obj));
        Console.Read();
    }

    static double getTotal(object[] o)
    {
        double total = 0D;

        foreach (object ob in o)
        {
            if (ob is A)
            {
                Console.WriteLine("A class");
            }
            else if (ob is B)
            {
                Console.WriteLine("B class");
            }
            else if (ob is double)
            {
                total += (double)ob;
            }
        }

        return total;
    }
}

Output

A class
B class
Total = 2

Explanation

  • Line 3-4: Define 2 empty classes.
  • Line 10: Declare an object array which is initialized with 6 elements.
  • Line 11-16: Assign the 6 elements with the values of different types.
  • Line 18: Call the method getTotal() to get the total of all the double-typed values.
  • Line 26-40: use the foreach loop to process each element of the array.
  • Line 28: "ob is A" returns true if ob is an instance of class A. Actually it is true when the element defined in line 14 is processed.
  • Line 36: double is a struct type. "ob is double" returns true whenever the element defined in line 13 is reached. Pay attention, the elements defined in line 11 and line 16 are integer and float type. They will not be converted to double type implicitly. So "ob is double" returns false to the integer and float elements.

Before introducing as operator, Let's see the following example.

Example 01-90-02

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;

class A {}
class B : A {}

public class Program
{
    static void Main()
    {
        A a = new A();

        try
        {
           B b = (B)a;
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception:{0}",e.Message);
        }
        
        Console.Read();
    }
}

Output

Exception:Unable to cast object of type 'A' to type 'B'.

Explanation

  • Line 3-4: Define class A and its derived class B.
  • Line 14: An InvalidCastException is thrown here. It is not allowed to cast an object of a base class to that of its derived class.
  • Line 18: The exception is caught and output the error message here.

Now it is time to introduce the as operator. The as operator is to cast an object to a specific type. If the conversion fails, it will return a null instead of raising an exception.

Syntax:

<Object> as <Type>

It is equivalent to the following expression.

<Object> is <type> ? (<type>)<Object> : null

Now we'll change the example 01-99-02 to the following.

Example 01-90-03

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;

class A {}
class B : A {}

public class Program
{
    static void Main()
    {
        A a = new A();

        B b = a as B;
        if (b == null)
        {
            Console.WriteLine("Wrong conversion!");
        }
        else
        {
            Console.WriteLine(b.ToString());
        }
        
        Console.Read();
    }
}

Output

Wrong conversion!

Explanation

  • Line 12: The as operator is used here and "a as B" returns null.
  • Line 15: Output the error message.
Note Note
The as operator must be used with a reference type or nullable type.

For example, the following code will issue a compile time error.

double d = 3.1416D;
int i = d as int;

Because int is not a reference type. In this case, explicit casting can be used. The code can be corrected as follows.

double d = 3.1416D;
int i = (int)d;

The nullable type will be introduced in later section.