C# Keywords Tutorial Part 3: as

C# Keywords Tutorial Part 3: as

Casting, often known as explicit type conversion, is done in C# with the “as” keyword. In particular when working with inheritance and interfaces, it is a safer technique to change the type of an object.

We’ll examine the “as” keyword’s functionality in C# and present code samples to demonstrate how to use it in this blog post.

What is explicit type conversion?

The process of changing a value’s type is known as type conversion. Type conversion in C# can be either implicit or explicit.

When the compiler can convert a value from one type to another without sacrificing information, implicit type conversion takes place automatically. For instance, the compiler will automatically convert an integer value if you assign it to a float variable.

Conversely, explicit type conversion needs a cast operator to complete the conversion. When converting between types that are incompatible or when changing a derived class into a base class or vice versa, explicit type conversion is required.

What is the “as” keyword?

The “as” keyword in C# is used to perform explicit type conversion in a safe way. It attempts to cast an object to a specific type and returns null if the object cannot be cast to that type.

Here’s an example:

object obj = "Hello World";
string str = obj as string;

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

In this example, we have an object called “obj” that contains a string value. We want to convert this object to a string variable called “str”. We use the “as” keyword to attempt the conversion and assign the result to the “str” variable.

The “as” keyword returns null if the conversion fails. In the example above, if the “obj” object cannot be converted to a string, the “str” variable will be null.

The “as” keyword is useful when dealing with inheritance and interfaces. For example, let’s say we have a class hierarchy like this:

public class Animal { }

public class Dog : Animal { }

We can create an instance of the “Dog” class and cast it to the “Animal” class using the “as” keyword:

Dog dog = new Dog();
Animal animal = dog as Animal;

if (animal != null)
{
    Console.WriteLine("Conversion successful");
}
else
{
    Console.WriteLine("Conversion failed");
}

In this example, we create a new instance of the “Dog” class and cast it to the “Animal” class using the “as” keyword. The “as” keyword returns a reference to the “Animal” object if the conversion is successful, or null if it fails.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *