SoFunction
Updated on 2025-03-07

How to explicitly implement interface members in c#

This example declares an interfaceIDimensionsand a classBox, explicitly implements interface membersGetLength andGetWidth. Through interface exampledimensions Visit these members.

interface IDimensions
{
  float GetLength();
  float GetWidth();
}

class Box : IDimensions
{
  float lengthInches;
  float widthInches;

  Box(float length, float width)
  {
    lengthInches = length;
    widthInches = width;
  }
  // Explicit interface member implementation:
  float ()
  {
    return lengthInches;
  }
  // Explicit interface member implementation:
  float ()
  {
    return widthInches;
  }

  static void Main()
  {
    // Declare a class instance box1:
    Box box1 = new Box(30.0f, 20.0f);

    // Declare an interface instance dimensions:
    IDimensions dimensions = box1;

    // The following commented lines would produce compilation
    // errors because they try to access an explicitly implemented
    // interface member from a class instance:
    //("Length: {0}", ());
    //("Width: {0}", ());

    // Print out the dimensions of the box by calling the methods
    // from an instance of the interface:
    ("Length: {0}", ());
    ("Width: {0}", ());
  }
}
/* Output:
  Length: 30
  Width: 20
*/

Reliable programming

  • Please note that the comment is out Main The following lines in the method, as they will generate a compile error. Explicitly implemented interface members cannot be accessed from class instances:
//("Length: {0}", ());
//("Width: {0}", ());
  • Please note also Main The following lines in the method successfully output the box size because these methods are called from the interface instance:
("Length: {0}", ());
("Width: {0}", ());

The above is the detailed content of how to explicitly implement interface members in C#. For more information about explicitly implementing interface members in C#, please pay attention to my other related articles!