H. Saleh H. Saleh - 1 year ago 82
C# Question

How come Unity's StartCoroutine work with and without assignment?

I tried searching but was lost between all the threads that explain the coroutine system but not this detail. I already know that StartCoroutine returns a Coroutine, so I tried looking if there's some sort of implicit operator overloading for a void return type and even tried it, but it didn't work and I found nothing. That's honestly all I could think of, you can tell i'm a beginner
There's no specific goal of this question, i'm just really interested. thanks in advance

Edit :i apologize for not making my question clear :
How can say both "StartCoroutine(example());" and "Coroutine myCoroutine = StartCoroutine(example());" ? How does the first one work like a void if the return type is Coroutine ?

Answer Source




Coroutine myCoroutine = StartCoroutine(example());

How does the first one work like a void if the return type is Coroutine ?

You've got the rule backwards in your head. The rule in C# is not "A non-void method must have its returned value assigned or used." The rule is the opposite: a void method can only be used as a statement.

If you use a non-void method as a statement, the compiler generates code which discards the returned value.

Whether that is a smart thing to do or not is not for the compiler to decide.

However, it is the case that only certain expressions may be used as statements; unsurprisngly, they are those expressions which are useful for their side effects. They are:

  • method calls
  • assignments (yes, assignments are expressions)
  • increments / decrements
  • constructor invocations ("new") -- this is rare
  • awaits

So you can say:

x = 123;
new Abc();
await someTask;

But not

2 + 2;

and so on.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download