Question

I can illustrate this problem best with an example.

I have an interface that forces developers to implement a specific function. I would also like this interface to force the users to implement a set or get property that sets the name of the derived class in a string stored within the class. So if a developer creates a new class that derives from this interface they are forced to:

  1. Create a definition for the the method.
  2. Store the name of the derived class in a string called "derivedType"

I would like to store the name as a string in the derived type because I would like to do some type checking at runtime on objects that implement this interface.

public interface someInterface
{
   int someMethod(int x);
   string derivedType {get; set;}
}

public derivedClass : someInterface
{
   public int someMethod (int x) {...};
   public string derivedType
   {
      get {return this.derivedType;}
      set {derivedType = "derivedClass";}
   }
}
Was it helpful?

Solution

There are two things - first, your example implementation is not correct. It will raise a StackOverflowException if you try to get derivedType (since it's returning itself). In general, a setter would not be required here:

public interface ISomeInterface
{
   int SomeMethod(int x);
   string DerivedType {get;}
}

public class DerivedClass : ISomeInterface
{
   public int DomeMethod (int x) {...};
   public string DerivedType
   {
      get {return "derivedType"; }
   }
}

That being said, there is no way to force the implementer to do this correctly. If you want to guarantee that the name will be correct, you could just use reflection instead of putting this into the interface (object.GetType().Name).

OTHER TIPS

You should use GetType() instead.

ISomeInterface myObject = new DerivedClass();
Type myType = myObject.GetType();
string typeName = myType.Name; // "DerivedClass"

Try this:

public interface someInterface
{
   int someMethod(int x);
   string derivedType {get;}
}

public derivedClass : someInterface
{
   public int someMethod (int x) {...};
   public string derivedType
   {
      get {return "derivedType";}
   }
}

That is, make the property read-only, and implement it to return the hard-coded string. Refactor as necessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top