-1

When I have a default implementation of a method in an interface and then have a struct with this interface, the method does not exist as member of the struct. Why? Or what am I understanding wrong? Example:

    using System;

namespace test
{
    public interface ITestInterface
    {
        public bool TestMe() => true;
        public bool TestMe2();
    }

    public struct teststruct : ITestInterface
    {
        public int somevalue;
        // implementing this will create a NEW method but not implement the interface
        // public bool TestMe() => true; 

        public bool TestMe2() => false;
    }

    class a
    {
        public static void Main()
        {
            var ts = new teststruct();
            ts.TestMe(); // this doesnt exist
        }
    }
}

With this example, the method TestMe() is non existent in the struct, but TestMe2() must be implemented (as expected).

Hefaistos68
  • 381
  • 3
  • 9
  • structs and interfaces are a special case with many caveats, read on here: https://learn.microsoft.com/en-us/archive/blogs/abhinaba/c-structs-and-interface – zedling Dec 23 '20 at 10:30
  • This doesnt really explain the problem at hand. – Hefaistos68 Dec 23 '20 at 10:34
  • 1
    You need to manually cast it to `ITestInterface` since it is hidden, and it makes no different if class or struct. highly doubt this statement is correct: `this will create a NEW method but not implement the interface` https://dotnetfiddle.net/ilx9V8 – Rand Random Dec 23 '20 at 10:35
  • `implementing this will create a NEW method but not implement the interface` @RandRandom is correct - this statement is not correct. https://dotnetfiddle.net/dRlZ3Q – mjwills Dec 23 '20 at 10:44

1 Answers1

1

You have to see an interface like a contract of what must have the object that inherits of it.

Your test struct does not have te method TestMe(), the one that contains the implementation is the interface. So it does not exists on the scope of your struct.

If you want to access the method of the interface, you should do:

(ts as ITestInterface).TestMe();

or:

((ITestInterface)ts).TestMe();