Question

Or if the if statement doesn't return null - why this particular property can't be assigned to.

Example:

String stringParam = "some string";

MyClass myclass = new MyClass();

myclass.MyProperty = MyMethod(out stringParam ) ? stringParam : String.Empty;

Hitting a breakpoint straight after the above line - I evaluate MyProperty - and it's null!?

I have triple checked the return of MyMethod and it is true (return type is boolean). And stringParam IS being updated within MyMethod.

Supposing what I've just said above is inaccurate or wrong somehow - MyProperty should at least be equal to String.Empty. And if the MyMethod IS true but my string is being updated - MyProperty should be equal to "some string".

Why is it null?

In the MyClass declaration there are no complexities regarding access modifiers. It's a simple:

public class MyClass()
{
public String MyProperty;
}

NOTE: Although I have simplified and altered the code slightly in terms of naming etc. - this code syntactically identical to the code I have.

What I've Tried

I switched the syntax around for this, and surprisingly (to me) it's worked!?

if(MyMethod(out stringParam)) { myclass.MyProperty = stringParam; }

On evaluation, myclass.MyProperty is now equal to the expected, updated stringParam.

I'd love an explanation as to why. Is it the case that inline if statement's behave differently with regards to out parameters?

Était-ce utile?

La solution

If you can change MyMethod, try this:

public bool MyMethod(ref string parameter)
{
    // Do something with parameter here...
    return true;
}

And then call

var stringParam = "some string";
var myClass = new MyClass();

myClass.MyProperty = MyMethod(ref stringParam) ? stringParam : string.Empty;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top