Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast interface to its concrete implementation object or vice versa?

Tags:

c#

oop

In C#, when I have an interface and several concrete implementations, can I cast the interface to a concrete type or is concrete type cast to interface?

What are the rules in this case?

like image 316
GurdeepS Avatar asked Feb 12 '09 00:02

GurdeepS


People also ask

What is casting to an interface?

A type cast—or simply a cast— is an explicit indication to convert a value from one data type to another compatible data type. A Java interface contains publicly defined constants and the headers of public methods that a class can define.

Can you cast an interface to a class C#?

If you have an interface, it is possible to cast to the concrete class.

Can you cast an interface to a class Java?

Yes, you can. If you implement an interface and provide body to its methods from a class. You can hold object of the that class using the reference variable of the interface i.e. cast an object reference to an interface reference.

Why interface concept is used in asp net?

Why And When To Use Interfaces? 1) To achieve security - hide certain details and only show the important details of an object (interface). 2) C# does not support "multiple inheritance" (a class can only inherit from one base class).


1 Answers

Both directions are allowed in Java and C#. Downcasting needs an explicit cast and may throw an Exception if the object is not of the correct type. Upcasting, however, needs no explicit cast and is always safe to do.

That is, assuming you have public interface Animal and two implementations of this interface, Cat and Dog....

Animal meowAnimal = new Cat();  // No cast required Animal barkAnimal = new Dog();  // No cast required  Cat myCat = (Cat) meowAnimal; // Explicit cast needed Dog myDog = (Dog) barkAnimal; // Explicit cast needed  Dog myPet = (Dog) meowAnimal; // Will compile but throws an Exception 

and you'll want a try / catch around the explicit casts. In C# you have the useful as keyword:

Dog myDog = barkAnimal as Dog; Dog myPet = meowAnimal as Dog; 

No exception will be thrown, and myDog will be nonNull and myPet will be null. Java does not have an equivalent keyword although you can always use if (meowAnimal instanceof Dog) tests to keep type safety. (I would guess that the "as" keyword generates bytecode that does the if, assigning null of the is fails. But perhaps .NET has a bytecode instruction that does the equivalent of "as".)

like image 179
Eddie Avatar answered Oct 05 '22 15:10

Eddie