#647 – A struct Can Implement an Interface

You’ll most often see an interface implemented by a class, but a struct can also implement an interface.

struct implements an interface in the same way as a class–by listing the name of the interface after the name of the struct and then by providing implementations of the members in the interface.

Suppose that we had the following interface:

    public interface IBoxCalcs
    {
        double CalcVolume();
        double CalcSurfaceArea();
    }

We can then implement this interface in a struct.

    public struct BoxSize : IBoxCalcs
    {
        public double x;
        public double y;
        public double z;

        // Constructor that fully initializes the object
        public BoxSize(double x, double y, double z)
        {
            this.x = x;
            this.y = y;
            this.z = z;
        }

        public double CalcVolume()
        {
            return x * y * z;
        }

        public double CalcSurfaceArea()
        {
            return (2 * x * y) + (2 * x * z) + (2 * y * z);
        }
    }