Hello everyone, there is the following example:
public abstract class Shape { } public class Circle : Shape { } public interface IContainer<out T> { T Figure { get; } } public class Container<T> : IContainer<T> { private T figure; public Container(T figure) { this.figure = figure; } public T Figure { get { return figure; } } } class Program { static void Main() { Circle circle = new Circle(); IContainer<Shape> container = new Container<Circle>(circle); Console.WriteLine(container.Figure.ToString()); // Delay. Console.ReadKey(); } } I'm interested in this line
IContainer<Shape> container = new Container<Circle>(circle); - an instance of circle (passed as a constructor argument) is not reduced to any type in this case - because type T (I know that the type of place to fill with type T is correct, but just "type T" will be shorter) for the class We closed the Container with the same type as this instance (and I mean, because they have the same types, there’s nothing to do with it.)
So, we first type Container to the IContainer type, and the figure field of the Circle type is reduced to the Shape type.
Why is the figure field inside a Container class cast to a Shape?
so my assumptions are:
1) the instance passed as an argument is nothing to do with it - as it was said above, the instance itself is not given to anyone.
2) Due to the fact that the Container type we led to the IContainer type - the type T from which we closed the Shape type
- and another question arises from here: at the same time, we have two UpCast events simultaneously: Container - IContainer;
Circle-Shape; - which of them, so to speak, affects the constructor argument passed — our instance of circle (yes, I know that I wrote above that UpCast -a instance of circle does not occur - just in the previous example, the instance is cast to the Shape type)
IContainer<Shape> container = new Container<Shape>(circle); - but, since the field figure changes its type, a link to this field is stored in this instance, which we pass as a constructor argument.
My guess is that since we type T in Container (Circle) - the type of which and the constructor argument of the circle - are cast to the type T in IContainer (Shape), then this argument of the Circle constructor is also implicitly UpCast - following " changes to its type — and accordingly, there will be UpCast types within this instance, including the figure field — which will change its Circle type to Shape.