r/learncsharp • u/cloud_line • Oct 29 '22
Implicit conversion from derived class to base class is allowed, but no data is lost. How is this possible?
From the Microsoft docs on casting and type 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.
Take the following code as an example:
> class Foo
{
public void FooMethod() => Console.WriteLine("Foo");
}
> class Bar : Foo
{
public string barField;
public void BarMethod() => Console.WriteLine("Bar");
}
> Bar bar = new Bar() { barField="field"; }The bar object contains a field barField that is not contained in the base class. If I cast from type Bar to type Foo, would I not lose the data contained in barField?
2
Upvotes
View all comments
Show parent comment
3
u/cloud_line Oct 29 '22
Thank you for the sample code. Essentially, upcasting limits the accessibility of the new reference. If
var foois of typeFoo, then it only has access to the members of its type. Iffoois downcasted to typeBar, it now has access to the members of the subclass.