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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: