//Main method
Belle jhbh = new();
IOpera kujb = (IOpera)jhbh;
interface IOpera {
}
interface IFire:IOpera {
}
class Belle :fff,IFire {
}
Can you please tell me, how does the casting work?
To me the following two variants would do the same thing:
1. IOpera kujb = (IOpera)jhbh;
2. IOpera kujb = jhbh;
I mean, at the end of the day It is kujb
that decides what member is accessible and what is not, right.
and since, In both cases, kujb
points to the same object, what is the point of casting then?
I think I am getting something horribly wrong.
CodePudding user response:
class Belle
and interface IOpera
are:
- two different types
- the point of the interface is that it guarantees that what ever implements it will provide the methods declared within it.
what is the point of casting then?
As these are two different types.
IOpera kujb = (IOpera)jhbh;
These kinds of operations are called type conversions. In C#, you can perform the following kinds of conversions:
Explicit conversions (casts): Explicit conversions require a cast expression. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons. Typical examples include numeric conversion to a type that has less precision or a smaller range, and conversion of a base-class instance to a derived class.
UPDATE:
Upcasting can be done without explicit cast. So:
Engineer engineer = new Engineer();
IEmployee employee = engineer;