code_fodder code_fodder - 1 year ago 78
C# Question

c# pass property backing value by reference, is it possible?

Following on from my earlier question: c-sharp-convert-existing-class-to-use-properties-correctly

I have a class like this:

public class TestCaseInfo
public string text { get; set; } = "";
public string requirement_ref { get; set; } = "";
public string given { get; set; } = "";
public string when { get; set; } = "";
public string then { get; set; } = "";
public UInt32 timeLimit { get; set; } = 0;

I was previously populating the structure like this:

if (!getNodeValue(testcase_node.SelectSingleNode("text"), ref testcaseInfo.text))
errStr += nodeError(testcase_node, "Missing 'text' node");

Note: that I am trying to pass it by reference. I have read a load of quetions that all basically say that you can't do this. Fair enough...

So I want to pass in the "real" value (I think its called the backing value?) instead. Something like:

if (!getNodeValue(testcase_node.SelectSingleNode("text"), ref testcaseInfo._text)) // where '_text' should be the 'backing' value.
errStr += nodeError(testcase_node, "Missing 'text' node");

But I am missing two things (probably more!):

  1. What is the backing value called?

  2. I assume its private? - can I make it protected and make it a friend class? (that might be C++ talk... not sure if there is the same idea in C#)?

Answer Source

There is no valid identifier for the backing field for that property. You could not use an auto property, and instead explicitly define the get and set methods of the property, along with your own backing field, thus giving you a valid identifier for the backing field, although it would be very poor design to expose this backing field externally.

What you should do is re-design your code such that you don't need to pass the value by reference in the first place. You should just be passing the string by value and, if the result of this function is the computation of a string, returning it. The caller can then set that string back to the property if that's what they want. That would be the more idiomatic design. (Since you also have a boolean value you'd need to pass both the string and the boolean out, of course.)

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