简体   繁体   中英

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?

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

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) .

The first case the concept is called polymorphism

In computer science, polymorphism is a programming language feature that allows values of different data types to be handled using a uniform interface. The concept of parametric polymorphism applies to both data types and functions. A function that can evaluate to or be applied to values of different types is known as a polymorphic function. A data type that can appear to be of a generalized type (eg, a list with elements of arbitrary type) is designated polymorphic data type like the generalized type from which such specializations are made.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM