SoFunction
Updated on 2025-03-08

Example analysis of is and as usage examples in C#

This article describes the usage of is and as in C#, which is helpful for deepening the understanding of is and as usage. The details are as follows:

Let’s take a look at an example:

public class User
{
}
public class Group
{
}
class Program
{
    static void Main(string[] args)
    {
      Object oUser = new User();
      Object user = (Group)oUser;
    }
}

This will report an error (InvalidCastException), and due to the C# security mechanism, it will make a judgment once. We have made illegal conversions here.

Is make judgments:is to determine whether the object is the type you want (here it is User)

The modified examples are as follows:

class Program
{
    static void Main(string[] args)
    {
      Object obj = new User();
      if (obj is User)
      {
        User user = (User)obj;
      }
    }
}

In this case, we made a judgment in obj is User. As we just said, the (User)obj (cast) compiler will do another operation, which will cause performance consumption. Let’s take a look at AS.

AS Operation:If you change the object, you will convert it, and if you don't, you will return null.

class Program
{
    static void Main(string[] args)
    {

      Object obj = new User();

      User user = obj as User;
      if(user==null)
      {
        // handle error
        //....
      }
    }
}

Note: I personally prefer to use As, which simplifies operations and improves performance. It is also very convenient to make a NULL judgment and directly deal with this exception.

I hope that the methods described in this article will have some help and reference value for everyone's C# programming.