Question

I'm trying to apply my ActionScript knowledge to C# and I've been wondering if it's possible to make this kinds of return statements:

return myObject ||= new Object();

Of course I can use a longer version like:

if (!myObject)
myObject = new Object();
return myObject;

and it works fine, but I just want to be able to obfuscate my code and make it a little shorter.

I figured since it's all ECMAScript, it should work, but it doesn't. Could anyone point out if it's possible to use logical operators to mimic if-else instead of usual if-then-else statements?

The .NET version is 3.5 (Unity3d engine)

Was it helpful?

Solution

Yes, there is the coalesce operator in C# that does almost exactly this.

 return myObject ?? new Object();

EDIT: This does not change the variable myObject. If you want to do this as well, you can simply write

 return myObject = myObject ?? new Object();

because an assignment in C# is also an expression that returns the value that has been assigned.

OTHER TIPS

The equivalent in C# is

return myObject ?? new Object();

So it seems like some of the operators are slightly different.

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