Reputation: 984
I have a C#
-Class Point
with two Subclasses ColorPoint
and AmountPoint
.
Point-Class
public class Point
{
double x; // Position x
double y; // Position y
public Point(double pos_x, double pos_y) // Constructor
{
this.x = pos_x;
this.y = pos_y;
}
}
public class ColorPoint : Point
{
double color; // White value (0 to 255)
}
public class AmountPoint : Point
{
int amount; // Amount of Persons standing at this point
}
Now in my main
class I want to create a new Point in the List
This should than look something like this:
public class main
{
public main()
{
List<ColorPoint> colorList = new List<ColorPoint>(4);
AddPoint<ColorPoint>(colorList);
}
public List<T> AddPoint<T>(List<T> pointList)
where T : Point
{
pointList.Add(new T(0, 0)); // DOES NOT WORK (Cannot create instance of variable type 'T')
pointList.Add(new Point(0, 0)); // DOES NOT WORK (Cannot convert Point to T)
}
}
The variables color
or amount
can be left as null
in both cases.
Upvotes: 0
Views: 601
Reputation: 5389
Your code doesn't compile. I can't imagine why you would want to do what you are trying to do. But the closest you can get to a legitimate implementation is:
class Program
{
static void Main(string[] args)
{
List<ColorPoint> colorList = new List<ColorPoint>(4);
AddPoint<ColorPoint>(colorList);
}
public static List<T> AddPoint<T>(List<T> pointList)
where T : Point, new()
{
pointList.Add(new T());
return pointList;
}
}
public class Point
{
double x; // Position x
double y; // Position y
public Point() : this(0, 0)
{
}
public Point(double pos_x, double pos_y) // Constructor
{
this.x = pos_x;
this.y = pos_y;
}
}
public class ColorPoint : Point
{
double color; // White value (0 to 255)
public ColorPoint()
{
}
public ColorPoint(double pos_x, double pos_y) : base(pos_x, pos_y)
{
}
}
public class AmountPoint : Point
{
int amount; // Amount of Persons standing at this point
public AmountPoint()
{
}
public AmountPoint(double pos_x, double pos_y) : base(pos_x, pos_y)
{
}
}
Upvotes: 1