Calculator
Calculator

Reputation: 46

Problem with Interface Implementation When using Inheritance

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

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);
        }
    }
}

Upvotes: 0

Views: 69

Answers (2)

Calculator
Calculator

Reputation: 46

so if you want to use ShallowClone method Explicitly without changing Class

var node = new Node(1, 0, 0, 0);
var node2 = ((IShallowCloneable<Node>)node).ShallowClone();

or if you want implicit implementation you have to Modify ShallowClone() method implementation in Node Class like this

new public Node ShallowClone()
{
    return new Node(Id, X, Y, Z);
}

Additional Reference

C# Interfaces. Implicit implementation versus Explicit implementation

Upvotes: 0

Guru Stron
Guru Stron

Reputation: 142048

Because for Node you've implemented IShallowCloneable<Node> as explicit interface, so it will work only if you cast to it:

// prints Node
Console.WriteLine(((IShallowCloneable<Node>)node).ShallowClone().GetType().Name); 

If you want it to behave as Point3D you need to implement it as you do there ( hiding inherited Point2D implementation with new keyword).

Upvotes: 2

Related Questions