Dev

How to use the is and as operators in C#


The is and the as operators in C# help you to avoid runtime exceptions while enhancing the readability of your code. While the is operator is used to verify compatibility between types, the as operator is used for casting an object of one type to another type.

This article discusses the use of the is and as operators in C#, and shows how we can work with them using code examples. To work with the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create a console application project in Visual Studio

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2022 is installed in your system, follow the steps outlined below to create a new .NET Core console application project.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “Console App (.NET Core)” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Next.
  7. In the “Additional information” window, choose “.NET 7.0 (Standard Term Support)” as the Framework version you would like to use.
  8. Click Create.

We’ll use this .NET 7 console application project to work with the is and as operators in the subsequent sections of this article.

What are operators in C#?

An operator is a keyword that works on an operand. An operand can either be a value or a constant. The C# programming language contains many operators that help you to evaluate expressions.

These operators are categorized into three categories: the unary, binary, and ternary operators. As the name suggests, a unary operator is one that works on a single operand only. A binary operator requires two operands, and a ternary operator works based on a condition.

Typical examples of the unary operator are the pre-increment (++x), post-increment (x++), pre-decrement (--x), and post-decrement (x--) operators. Typical examples of binary operators are the arithmetic operators +, -, *, /, and %.

A ternary operator is used to define a boolean condition. The first statement after ? is evaluated if the condition is true. Otherwise, the next statement is executed. Basically, a ternary operator gives you a shorter way of writing an if-else statement.

There are several other types of operators such as bitwise operators, equality operators, assignment operators, and user-defined conversion operators. You can learn more about the operators in C# in Microsoft’s documentation here.

Using the is operator in C#

The is operator in the C# programming language is used to check for compatibility of the runtime type of an object with a given type. If it is compatible, the expression evaluates to true, false otherwise.

Here are the characteristics of the is operator in C#:

  1. The is operator is used to check if the run-time type of an expression result is compatible with a given type.
  2. When an is operator is used, the expression either evaluates to true if the types are the same, or false if the types differ.
  3. The is operator is used only for boxing, unboxing, and reference conversions.

Note the the is operator will not throw any exception if the type compatibility fails. Let us understand this with a code example. Consider the following C# classes.

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string PostalCode { get; set; }
    public string Country { get; set; }
    public string Phone { get; set; }
}
public class Author: Person
{
    public int Id { get; set; }
    public List<Book> Books { get; set; }
}
public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }  
    public string Description { get; set; }
    public string ISBN { get; set; }
}
public class Employee: Person
{
    public int Id { get; set; }
    public string Department { get; set; }
    public double Basic { get; set; }
    public double Allowance { get; set; }
    public double Tax { get; set; }
    public double NetSalary { get; set; }
}

Now, if you write the following code to perform an explicit cast, you’ll be greeted with an error saying “Cannot convert type ‘Author’ to type ‘Employee’.”

var author = new Author();
var employee = (Employee)author;

Now, write the following code in the Program.cs file to check for compatibility of types using the is operator.

bool checkCompatibilityAuthor = (author is Author);
bool checkCompatibilityEmployee = (employee is Author);

When you execute the application, you will see the first statement evaluates to true and the second to false. However, there will be no exceptions, i.e. no compile-time or run-time errors.

Using the as operator in C#

The as operator in C# allows you to explicitly convert the result of an expression to a given reference type or a nullable value type. If the conversion isn’t possible, as returns null.

Here are the characteristics of the as operator in C#:

  1. The as operator is used when you need to convert compatible reference types of nullable types.
  2. When the as operator is used, the expression on the right-hand side of the assignment operator doesn’t evaluate to a boolean value.
  3. When the as operator is used, the expression returns the object if the objects are compatible and returns null if no conversion if possible.
  4. You can use the as operator only for boxing, reference, and nullable conversions.

The following code snippet shows how the as operator can be used in C#.

var obj = new Author();
var person = obj as Person;

The object named person will now be of type Person but it will refer to the instance obj of the Author class.

When to use is and as

The is operator helps you to check for null values using human-readable code. The as operator also helps you to check for null values, but instead of returning true or false it returns a compatible type or null. Remember, checking for null references is much less costly in terms of resource overhead than writing exception blocks and throwing exceptions in your code.

The is and as operators provide a nice way to deal with the casting of objects. Most importantly, you will not run into compile-time or run-time errors if the conversions fail. However, I advise you not to use too many casts in an application because casts are detrimental to performance due to the boxing and unboxing overhead.

Copyright © 2023 IDG Communications, Inc.



READ SOURCE

This website uses cookies. By continuing to use this site, you accept our use of cookies.