user11437113
user11437113

Reputation:

Does 'as' keyword in C# only converts Object type variables to the type I desire?

From the official C# document, I learnt that I can convert from one type to another using the 'as' keyword. However, when I tested it out, it seems like things are not working as it is supposed to (please correct me if I am wrong). When I convert an Object type variable or if the types have "has-relation" (inheritance), then it works fine. But, if I try to convert two different types that are does have a "has-a-relation", then the IDE (visual studio 2019) gives me an error (instead of return null). Please correct me if I am wrong or something I am doing wrong.

Here is the code:

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person();

        Animal animal = person as Animal; // the IDE shows an error under "person as Animal"
    }
}

class Person
{ }

class Animal
{ }

Thank You very much for your response.

Upvotes: 0

Views: 76

Answers (2)

user10243016
user10243016

Reputation:

If Animal is not Person or these two classes not inherit same parent?

Upvotes: 0

Longoon12000
Longoon12000

Reputation: 794

This is because the IDE analyzes your code and knows that it's not possible to cast Person into Animal.

This code wouldn't give you an error and return null instead:

class Program
{
    static void Main(string[] args)
    {
        Object person = new Person();

        Animal animal = person as Animal;
    }
}

class Person
{ }

class Animal
{ }

Note, it will still tell you that this expression will always be null, but it won't be classified as an error.

The reason for this is because Person and Animal are two specific types that are known not to be compatible, however the Object type can contain anything and it's not immediately clear whether it's an incompatible type or not.

Upvotes: 2

Related Questions