Reputation: 285
//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.
Upvotes: 0
Views: 55
Reputation: 38094
class Belle
and interface IOpera
are:
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:
Implicit conversions: No special syntax is required because the conversion always succeeds and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.
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.
User-defined conversions: User-defined conversions are performed by special methods that you can define to enable explicit and implicit conversions between custom types that do not have a base class–derived class relationship. For more information, see User-defined conversion operators.
Conversions with helper classes: To convert between non-compatible types, such as integers and System.DateTime objects, or hexadecimal strings and byte arrays, you can use the System.BitConverter class, the System.Convert class, and the Parse methods of the built-in numeric types, such as Int32.Parse. For more information, see How to convert a byte array to an int, How to convert a string to a number, and How to convert between hexadecimal strings and numeric > types.
UPDATE:
Upcasting can be done without explicit cast. So this is an example of implicit cast:
Engineer engineer = new Engineer();
IEmployee employee = engineer;
Upvotes: 1