Question

I was wondering if there is a way to declare a method (in an interface for example) that supports the use of IEnumerator and Void, without the need to implement both in the subclasses?

public void Start()
public IEnumerator Start()

this is related to my other question: Hold or Wait while Coroutine finishes

i noticed in the Unity context, the default Start() method seems to allow for both.

Was it helpful?

Solution

You can't do that because those methods would have the same signature and the CSC woudn't be able to figure out which method should be statically bound for each call. e.g.:

public class TestClass
{
    public int FooMethod()
    {
        return 1;
    }
    public void FooMethod()
    {
        return;
    }
    public string FooMethod()
    {
        return "foo";
    }
}

static void Main()
{
    TestClass test = new TestClass();

    Console.WriteLine(test.FooMethod()); // which FooMethod should be called here?
}

A method's return type is not considered as part of its signature. What you can do is overload the same method with a different signature to return a different type. Also, in the case of an additional method that differs only in returning void, you can always choose not to use the result returned by the original method.

The case with interfaces is similar. when a class implements an interface it is agreeing to a protocol, that it implements that interface's behaviour which is what consumers of your class expect. So you cannot partly agree with an interface. Although you can throw a NotImplementedException in your implementations you have to at least define all members, which leads to the same problem mentioned in the above example: the C# compiler will not be able to statically bind your method calls and your code will fail to compile.

You can solve your problem by reconsidering your design.

OTHER TIPS

The short answer is no.

The closest you could get to this is using generics, however that would not work for a void, sorry.

public T Start()

One function name + combination of parameters can only be declared once, thus can only have one output.

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