C# As Tutorial – Complete Guide

Welcome to this comprehensive tutorial on the utility and application of ‘as’ in C#. If you’re an aspiring coder or game developer, or simply want to enhance your programming skills, this tutorial is the right place for you. In this lesson, we’ll delve into the nitty-gritty of the often-overlooked keyword and its paramount importance in coding.

What is ‘as’ in C#?

In C#, ‘as’ is a keyword used in type conversion. It is an operator that attempts to convert an object to a specified type without throwing an exception. If the conversion is not possible, ‘as’ will return null instead of causing an error.

What is it For?

You may wonder why you need to learn about ‘as’. The ‘as’ operator is instrumental in ensuring safe type conversion. It’s commonly used in cases where you’re dealing with inheritance or interfaces, or when you need to confirm if an object is of a specific type.

Why Should I Learn It?

Understanding how to use ‘as’ in C# can be a significant advantage for both game developers and coders. The ability to safely convert types opens up more possibilities for the manipulation and utilization of objects within your code. Whether you are a beginner or seasoned coder, having this tool in your programming toolkit is undoubtedly beneficial.

First Steps with ‘as’ in C#

Let’s begin with a simple code snippet to showcase how ‘as’ works.

// Initial object declaration 
object obj = "Zenva";

// 'as' operator for type conversion
string str = obj as string;

// Output
Console.WriteLine(str);

In the above code, we’re declaring an object ‘obj’ with a value “Zenva”. We then use the ‘as’ operator to try and convert this object into a string, and store the result in variable ‘str. When outputted, if the conversion is successful, ‘str’ will print out as “Zenva”.

Moving Further with ‘as’

// Create a simple class Person
class Person  
{  
    public string Name = "John Doe";  
}  

// Our main Program
class Program  
{  
    static void Main(string[] args)  
    {  
        object obj = new Person();

        Person p = obj as Person;  

        Console.WriteLine(p.Name);  
    }  
}

In the above code, an instance of the class Person is created and stored as an object. The ‘as’ operator is then used to attempt a conversion of this object back into a Person class instance. If the conversion is successful, it will print out the person’s name.

Complex Usage

Sometimes, you might need to confirm if an object is of a certain type. ‘as’ can be used for this too. Let’s take an example.

class Animal {}

class Cat : Animal 
{
    public string SayMiaow() 
    {
        return "Miaow!";
    }
}

class Dog : Animal {}

// Our main Program
class Program 
{
    static void Main(string[] args) 
    {
        Animal animal = GetRandomAnimal();

        Cat cat = animal as Cat;

        if (cat != null) 
        {
            // if animal is a Cat, will print "Miaow!"
            // if not, this won't run
            Console.WriteLine(cat.SayMiaow());
        }
    }
}

In this code, we have an animal and we want to know if it’s a cat. If it is, it will say “Miaow!”, if not – the program won’t do anything.

Continue Your Learning Journey with Zenva

We at Zenva believe in empowering individuals with the right tools and knowledge to excel in the field of programming, game creation, and artificial intelligence. If you found this tutorial useful and wish to dive deeper, we encourage you to explore our Unity Game Development Mini-Degree.

Conclusion

The ‘as’ operator in C# is a powerful feature for safe type conversion. Whether you’re handling inheritance, interfaces, or merely ensuring an object converts safely to a new type, ‘as’ comes in handy. By now, you have a comprehensive understanding of ‘as’, its function in the C# language, and usage examples ranging from simple to complex.

The adventure of learning never ends. We encourage you to continue expanding your knowledge and pioneering in the field of game development and programming. Don’t forget to check out our Unity Game Development Mini-Degree for more extensive learning materials to help fuel your growth.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Assessing the Result of ‘as’ Conversion

It’s crucial to note that ‘as’ will return null if the conversion is not possible. This feature can be wielded to determine whether or not a conversion is successful.

class Bird 
{
    public string Fly() 
    {
        return "I can fly!";
    }
}

class Program 
{
    static void Main(string[] args) 
    {
        object obj = new Bird();
        string str = obj as string;

        if (str == null) 
        {
            Console.WriteLine("Conversion unsuccessful");
        } 
        else 
        {
            Console.WriteLine(str);
        }
    }
}

In the program above, the conversion will fail because a Bird object cannot be converted into a string. The ‘as’ operator will return null, and the program will print out ‘Conversion unsuccessful’.

Checking Multiple Types

Let’s extend our animal example to illustrate how to use ‘as’ for checking multiple types.

class Animal {}

class Bird : Animal 
{
    public string SayTweet() 
    {
        return "Tweet!";
    }
}

class Cat : Animal 
{
    public string SayMiaow() 
    {
        return "Miaow!";
    }
}

// Our main Program
class Program 
{
    static void Main(string[] args) 
    {
        Animal animal = GetRandomAnimal();

        // check if it's a bird
        Bird bird = animal as Bird;

        if (bird != null) 
        {
            Console.WriteLine(bird.SayTweet());
        }

        // check if it's a cat
        Cat cat = animal as Cat;

        if (cat != null) 
        {
            Console.WriteLine(cat.SayMiaow());
        }
    }
}

This program checks whether an animal object is either a Bird or a Cat. If successful, it will print the respective sound of the animal. If unsuccessful, it won’t do anything.

‘as’ with Null Objects

Take note of how the ‘as’ behaves with null objects. Can we operate on null objects with ‘as’? Let’s see:

class Person  
{  
    public string Name = "John Doe";  
}  

static void Main(string[] args)  
{  
    object p = null ;  
    Person person = p as Person;  

    if (person == null) 
    {
        Console.WriteLine("The object is null");
    }
}

If the object we’re trying to convert is null, ‘as’ will also return null. This is an important case to handle to avoid any potential issues in our code.

‘as’ with Value Types

While ‘as’ is primarily used with reference types, it can also be used with nullable value types. Let’s see how this works:

int? num = 10;
object obj = num;
int? num2 = obj as int?;

Console.WriteLine(num2); // Outputs: 10

Here, we have a nullable int ‘num’. We convert it to an object, and then using ‘as’, we convert it back to a nullable int. The ‘as’ operator works perfectly well in such cases.

‘as’ with Arrays

The ‘as’ operator is equally useful while working with arrays, especially when handling arrays of different derived classes.

// Array of Animals
Animal[] animals = { new Bird(), new Cat() };

// Attempted conversion
Bird[] birdArray = animals as Bird[];

if (birdArray == null) 
{
    Console.WriteLine("Unable to convert Animal array to Bird array");
}

This code is attempting to convert an array of Animals, which contains different types of animals, into an array of Birds. The ‘as’ operator will return null because not all Animals in the array can be converted into Birds. The null check then allows the code to print an error message.

Using ‘as’ with User-defined Conversions

Another useful aspect of the ‘as’ operator is its compatibility with user-defined conversions. Let’s explore this with a simple example:

class A 
{
    public static implicit operator B(A a) 
    {
        return new B();
    }
}

class B {}

class Program 
{
    static void Main(string[] args) 
    {
        A a = new A();

        // Using 'as' with user-defined conversion
        B b = a as B;

        if (b != null) 
        {
            Console.WriteLine("Conversion successful!");
        }
    }
}

In this code, we have a user-defined implicit conversion from class A to class B. We then create an instance of A and try and convert it to B using ‘as’. The code will print ‘Conversion successful!’ if the conversion occurs without any issues.

‘as’ in Inheritance

Inheritance is a key area where the ‘as’ operator shines. It allows safe downcasting from a base type to a derived type. Let’s see a quick example:

class Animal
{
    public void Breathe() 
    {
        Console.WriteLine("Breathing...");
    }
}

class Bird : Animal 
{
    public void Fly() 
    {
        Console.WriteLine("Flying...");
    }
}

class Program 
{
    static void Main(string[] args) 
    {
        Animal animal = new Bird();

        // Using 'as' for downcasting
        Bird bird = animal as Bird;

        if (bird != null) 
        {
            bird.Fly();
        }
    }
}

Here, we first create a Bird object but store it in an Animal variable. We then attempt to downcast it back to a Bird object using ‘as’. If the cast is successful, the bird will begin to fly.

‘as’ with Interfaces

Let’s close out our exploration of ‘as’ with a look at its role with interfaces. The ‘as’ operator allows you to safely cast an instance to an interface.

interface IFlyable
{
    void Fly();
}

class Bird : IFlyable
{
    public void Fly()
    {
        Console.WriteLine("Flying...");
    }
}

class Program
{
    static void Main(string[] args)
    {
        Bird bird = new Bird();

        // Using 'as' for casting to interface
        IFlyable flyable = bird as IFlyable;

        if (flyable != null)
        {
            flyable.Fly();
        }
    }
}

In this program, an instance of Bird is safely cast to the IFlyable interface using ‘as’. If the cast is successful, it will be able to call the Fly method from the interface.

‘as’ vs ‘is’

The ‘as’ keyword in C# is often contrasted with the ‘is’ keyword. While both are used for type conversion, their approaches and applications are different. Understanding these differences can help you choose the right tool for the job.

// 'as' returns null when conversion fails
string strObj = "Hello Zenva";
object obj = strObj;
int? num = obj as int?;

if (num == null) 
{
    Console.WriteLine("Conversion failed with 'as'");
}

// 'is' returns false when conversion fails
if (obj is int)
{
    Console.WriteLine("Conversion successful with 'is'");
} 
else 
{
    Console.WriteLine("Conversion failed with 'is'");
}

‘as’ will return null if the conversion fails, allowing for a null check to handle this case. On the other hand, ‘is’ will return a boolean indicating whether or not the conversion is possible.

‘as’ with Lists

The ‘as’ operator is not limited to arrays – it can also be used with Lists.

List animals = new List() { new Bird(), new Cat() };

List birds = animals as List;

if (birds == null) 
{
    Console.WriteLine("Unable to convert Animal List to Bird List");
}

Similar to the array example, this conversion will fail because the List of Animals contains different types, all of which cannot be converted to Birds.

‘as’ with Multidimensional Arrays

‘as’ can also handle more complex data structures like multidimensional arrays.

Animal[,] animals = { { new Bird(), new Cat() }, { new Bird(), new Cat() } };

Bird[,] birds = animals as Bird[,];

if (birds == null) 
{
    Console.WriteLine("Unable to convert Animal multidimensional array to Bird multidimensional array");
}

Like previous examples, not all the Animals in the multidimensional array are Birds, so the ‘as’ operator will return null.

‘as’ and Performance

The ‘as’ operator can be more performant than using a direct cast, especially with large code bases or complex applications.

// Direct casting
object obj = new Bird();
Bird bird1 = (Bird)obj;

// Casting with 'as'
Bird bird2 = obj as Bird;

When you use a direct cast, there is a performance cost for the runtime to check if the conversion is valid and throw an exception if it is not. The ‘as’ operator, however, can perform the same process more efficiently by returning null instead of throwing an exception.

‘as’ and Null Coalescent Operator

The ‘as’ operator and the null coalescent operator can be used together for cleaner and more fail-safe code.

object obj = GetSomeObject();

// Using 'as' with the null coalescent operator
string str = obj as string ?? "";

In this code, if the object cannot be converted to a string, the ‘as’ operator will return null, causing the null coalescent operator (??) to take over and assign an empty string instead. This keeps your code safe from null reference exceptions.

‘as’ and Chaining

Lastly, the ‘as’ operator can be used in chaining to progressively try multiple conversions.

object obj = GetSomeObject();

// Chaining 'as' for multiple conversions
Bird bird = obj as Bird;
Cat cat = obj as Cat;

if (bird != null)
{
    bird.Fly();
} 

if (cat != null) 
{
    cat.SayMiaow();
}

In case the object can be converted to multiple types, we can chain ‘as’ operators to attempt these conversions. This gives you the flexibility to handle objects that may belong to multiple types.

Continue Your Learning Journey with Zenva

We at Zenva strongly believe that your journey in the world of programming and game development is far from over – it has only begun! There’s always more to explore, and to support your ongoing education, we offer a broad range of beginner to professional courses in programming, game development, and AI. With over 250 globally recognized courses available, you can boost your career, learn new coding skills, delve into the nuances of game creation, and earn deserved certificates.

A great next step is our comprehensive Unity Game Development Mini-Degree. This splendid collection of 20 self-paced courses offers detailed insights into game development using Unity, one of the most renowned and versatile game engines worldwide. Here, you get to learn about game mechanics, audio effects, cinematic cutscenes, and much more. What’s more, the skills you acquire aren’t limited to game development – they extend to various industries such as education, healthcare, film and animation, and architecture.

Remember, becoming proficient in coding and game development is a marathon, not a sprint. Your continuous growth and learning are what matter the most. You’ve taken excellent first steps here; keep the momentum going! For an even broader selection of Unity-focused courses, you can check out our entire Unity collection. Happy coding!

Conclusion

Congratulations on completing this comprehensive guide on using ‘as’ in C#! This versatile operator plays a crucial role in ensuring type safety and preventing unexpected exceptions in your code. We’ve covered simple and advanced examples, making you comfortable with its usage in your future programming endeavors.

This tutorial is only the tip of the iceberg when it comes to all the valuable coding lessons and educational content we have to offer on Zenva. We hope that it has ignited your curiosity and inspired you to continue learning. If you can’t wait to dig deeper into coding, game development, and beyond, our Unity Game Development Mini-Degree is ready to take your skills to the next level. Keep coding, keep exploring, and let learning be your lifelong companion!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.