Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast Interface And Class Objects

What is the difference between cast object to interface cast object to class like this example.

namespace ConsoleApplication1
{
    interface IAnimal
    {
        string Sound();
    }

    class Animal : IAnimal
    {
        public string Sound()
        {
            return "Animal sound";
        }
    }

    class Lion : Animal, IAnimal
    {
        public string Sound()
        {
            return "Roarrrrr";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Lion lion = new Lion();
            IAnimal animal = (Animal)lion; // variant 1

            IAnimal animal2 = (IAnimal)lion; // variant 2

            Console.WriteLine(animal.Sound());
        }
    }
}

What is the difference between variant 1 and variant 2 ?

like image 707
theChampion Avatar asked Mar 31 '26 05:03

theChampion


2 Answers

The only difference is in how the compiler checks that the casts are allowed.

In the first variant the compiler checks how Lion can be cast to Animal, then it checks how Animal can be cast to IAnimal. As both cast can be done safely as Lion is an Animal and Animal is an IAnimal, the compiler generates no code for casting at all, it's just an assignment.

In the second variant the compiler checks how Lion can be cast to IAnimal, then it checks if IAnimal is the same as IAnimal. As the cast can be done safely it generates no code for casting there either, it's also just an assignment.

As Lion is an IAnimal you don't need to do any casting at all, you can just assign it to the variable:

IAnimal animal3 = lion;

In that case the compiler will check how Lion can be cast to IAnimal, and as that can be done safely it doesn't generate any code for casting, just the assignment.

like image 174
Guffa Avatar answered Apr 02 '26 19:04

Guffa


In

IAnimal animal = (Animal)lion;

there's an implicit conversion going on because animal is declared as IAnimal, and Animal is convertible to IAnimal (because the class implements the interface).

It corresponds to writing

Lion lion = new Lion();
Animal a = lion;
IAnimal ia = a;

All these conversions are possible.

However, you could also just have written:

IAnimal lion = new Lion();

On the other hand, if you had written

var animal = (Animal)lion;

animal would have been an instance of Animal.

like image 28
Mark Seemann Avatar answered Apr 02 '26 18:04

Mark Seemann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!