I have created IShallowCloneable interface to create shallow copy of class for All of my class but with inheritance it is not working properly.
Look at Main method, node2 is returning Point3D object Instead of Node.
Details
- Point2D is Base Class
- Point3D Class Derived from Point2D Class
- Node Class Derived from Point3D Class
using System;
namespace ConsoleAppTest
{
internal static class Program
{
private static void Main()
{
try
{
var node = new Node(1, 0, 0, 0);
var node2 = node.ShallowClone();//this code is returing Point3D Object instead of Node
}
catch (Exception)
{
throw;
}
finally
{
Console.ReadLine();
}
}
}
public interface IShallowCloneable<T>
{
T ShallowClone();
}
public class Point2D : IShallowCloneable<Point2D>
{
public int X { get; set; }
public int Y { get; set; }
public Point2D()
{
}
public Point2D(int x, int y)
{
X = x;
Y = y;
}
public Point2D ShallowClone()
{
return new Point2D(X, Y);
}
}
public class Point3D : Point2D, IShallowCloneable<Point3D>
{
public int Z { get; set; }
public Point3D()
{
}
public Point3D(int x, int y,int z):base(x,y)
{
Z = z;
}
new public Point3D ShallowClone()
{
return new Point3D(X, Y,Z);
}
}
public class Node:Point3D, IShallowCloneable<Node>
{
public int Id { get; set; }
public Node()
{
}
public Node(int id,int x, int y, int z):base(x,y,z)
{
Id = id;
}
Node IShallowCloneable<Node>.ShallowClone()
{
return new Node(Id,X, Y, Z);
}
}
}