Answer the question
In order to leave comments, you need to log in
Generic Types and UpCast to base interface type(Generic covariance)?
Hello everyone, I have the following code:
public abstract class Shape { }
public class Circle : Shape { }
public interface IContainer<T>
{
T Figure { get; set; }
}
public class Container<T> : IContainer<T>
{
public T Figure { get; set; }
public Container(T figure)
{
this.Figure = figure;
}
}
class Program
{
static void Main()
{
Circle circle = new Circle();
IContainer<Circle> container = new Container<Circle>(circle);
Console.WriteLine(container.Figure.ToString());
// Delay.
Console.ReadKey();
}
}
IContainer<Circle> container = new Container<Circle>(circle);
Answer the question
In order to leave comments, you need to log in
In C#, using interfaces, they implement an important property of OOP - polymorphism. In short, this is the selection of the same properties and methods of objects, without being tied to their type. In simple words, for example, we have a number of objects: a chair, a table, a cup, a sad pug and the Churyumov-Gerasimenko comet. And for example, the task is to track their movement. All objects are of different types and it is impossible to bring them to one common one. This is where interfaces come to the rescue. Describing the properties we need
public interface INotifyCoordinateChanged
{
string Name{get;set;}
double X{get;set;}
double Y{get;set;}
double Z{get;set;}
event Action<INotifyCoordinateChanged> CoordinateChanged;
}
Read about oop with code examples.
In practice, the need and benefit are obvious.
For dynamic languages and slack-typed languages, the conditions are less strict, but the benefits are the same.
Too lazy to chew, maybe the other will not.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question