Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between these two casts

I'm really not fully familiar with casting. So feel free to edit or comment changes to my question.

Let's say I have a class that implements an interface:

public class Class1: Interface1
{
}

Whats the difference between these two?:

Interface1 myObject = new Class1();

and

Class1 myClassObject = new Class1();
Interface1 myObject = (Interface1) myClassObject;

Is the first one also a form of casting?

Edit:

What does each one do?

like image 287
klce Avatar asked Feb 20 '26 21:02

klce


2 Answers

The first one is indeed an implicit cast. To cite Microsoft:

For reference types, an implicit conversion always exists from a class to any one of its direct or indirect base classes or interfaces. No special syntax is necessary because a derived class always contains all the members of a base class.

The second cast is an explicit conversion, and as already mentioned is not necessary for the reason stated above. Explicit conversions are necessary when some of the information could/would get lost during the casting and tells the compiler how to handle that.

Microsoft has a nice article about casting: http://msdn.microsoft.com/en-us/library/ms173105.aspx

like image 200
Sascha Hennig Avatar answered Feb 22 '26 09:02

Sascha Hennig


The first is a polymorphism feature (though still implicit casting), because Class1 implements Interface1 . The second is explicit casting, and is not required as, MyClass1 is already an Interface1 (a matter of saying it) .

like image 38
Freeman Avatar answered Feb 22 '26 09:02

Freeman



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!