The right way to use the is and as operators in C#



The is and the as operators in C# provide help to to keep away from runtime exceptions whereas enhancing the readability of your code. Whereas the is operator is used to confirm compatibility between sorts, the as operator is used for casting an object of 1 sort to a different sort.

This text discusses the usage of the is and as operators in C#, and exhibits how we are able to work with them utilizing code examples. To work with the code examples offered on this article, you need to have Visible Studio 2022 put in in your system. If you happen to don’t have already got a replica, you may obtain Visible Studio 2022 right here.

Create a console utility undertaking in Visible Studio

First off, let’s create a .NET Core console utility undertaking in Visible Studio. Assuming Visible Studio 2022 is put in in your system, comply with the steps outlined beneath to create a brand new .NET Core console utility undertaking.

  1. Launch the Visible Studio IDE.
  2. Click on on “Create new undertaking.”
  3. Within the “Create new undertaking” window, choose “Console App (.NET Core)” from the record of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new undertaking” window, specify the identify and placement for the brand new undertaking.
  6. Click on Subsequent.
  7. Within the “Further data” window, select “.NET 7.0 (Customary Time period Assist)” because the Framework model you wish to use.
  8. Click on Create.

We’ll use this .NET 7 console utility undertaking to work with the is and as operators within the subsequent sections of this text.

What are operators in C#?

An operator is a key phrase that works on an operand. An operand can both be a price or a relentless. The C# programming language comprises many operators that provide help to to guage expressions.

These operators are categorized into three classes: the unary, binary, and ternary operators. Because the identify suggests, a unary operator is one which works on a single operand solely. A binary operator requires two operands, and a ternary operator works based mostly on a situation.

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 outline a boolean situation. The primary assertion after ? is evaluated if the situation is true. In any other case, the subsequent assertion is executed. Mainly, a ternary operator provides you a shorter means of writing an if-else assertion.

There are a number of different forms of operators similar to bitwise operators, equality operators, project operators, and user-defined conversion operators. You possibly can be taught extra in regards to the operators in C# in Microsoft’s documentation right here.

Utilizing the is operator in C#

The is operator within the C# programming language is used to examine for compatibility of the runtime sort of an object with a given sort. Whether it is suitable, the expression evaluates to true, false in any other case.

Listed below are the traits of the is operator in C#:

  1. The is operator is used to examine if the run-time sort of an expression result’s suitable with a given sort.
  2. When an is operator is used, the expression both evaluates to true if the kinds are the identical, or false if the kinds differ.
  3. The is operator is used just for boxing, unboxing, and reference conversions.

Notice the the is operator won’t throw any exception if the sort compatibility fails. Allow us to perceive this with a code instance. Take into account the next C# courses.

public class Individual
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Deal with { get; set; }
    public string Metropolis { get; set; }
    public string PostalCode { get; set; }
    public string Nation { get; set; }
    public string Cellphone { get; set; }
public class Creator: Individual
    public int Id { get; set; }
    public Checklist<E-book> Books { get; set; }
public class E-book
    public int Id { get; set; }
    public string Title { get; set; }  
    public string Description { get; set; }
    public string ISBN { get; set; }
public class Worker: Individual
    public int Id { get; set; }
    public string Division { get; set; }
    public double Fundamental { get; set; }
    public double Allowance { get; set; }
    public double Tax { get; set; }
    public double NetSalary { get; set; }

Now, in the event you write the next code to carry out an specific forged, you’ll be greeted with an error saying “Can’t convert sort ‘Creator’ to sort ‘Worker’.”

var writer = new Creator();
var worker = (Worker)writer;

Now, write the next code within the Program.cs file to examine for compatibility of sorts utilizing the is operator.

bool checkCompatibilityAuthor = (writer is Creator);
bool checkCompatibilityEmployee = (worker is Creator);

Once you execute the applying, you will note the primary assertion evaluates to true and the second to false. Nevertheless, there can be no exceptions, i.e. no compile-time or run-time errors.

Utilizing the as operator in C#

The as operator in C# lets you explicitly convert the results of an expression to a given reference sort or a nullable worth sort. If the conversion isn’t attainable, as returns null.

Listed below are the traits of the as operator in C#:

  1. The as operator is used when you should convert suitable reference forms of nullable sorts.
  2. When the as operator is used, the expression on the right-hand aspect of the project operator doesn’t consider to a boolean worth.
  3. When the as operator is used, the expression returns the article if the objects are suitable and returns null if no conversion if attainable.
  4. You should utilize the as operator just for boxing, reference, and nullable conversions.

The next code snippet exhibits how the as operator can be utilized in C#.

var obj = new Creator();
var individual = obj as Individual;

The article named individual will now be of sort Individual however it can consult with the occasion obj of the Creator class.

When to make use of is and as

The is operator lets you examine for null values utilizing human-readable code. The as operator additionally lets you examine for null values, however as a substitute of returning true or false it returns a suitable sort or null. Bear in mind, checking for null references is way more cost effective by way of useful resource overhead than writing exception blocks and throwing exceptions in your code.

The is and as operators present a pleasant option to cope with the casting of objects. Most significantly, you’ll not run into compile-time or run-time errors if the conversions fail. Nevertheless, I counsel you to not use too many casts in an utility as a result of casts are detrimental to efficiency because of the boxing and unboxing overhead.

Copyright © 2023 IDG Communications, Inc.