Note that there are some explanatory texts on larger screens.

plurals
  1. POLambda expressions / delegate assign variable
    text
    copied!<p>Actually I can not even say exactly how that thing is called correctly but I need something that can assign variables / properties / fields in one method. I will try to explain... I have the following code:</p> <pre><code>txtBox.Text = SectionKeyName1; //this is string property of control or of any other type if (!string.IsNullOrEmpty(SectionKeyName1)) { string translation = Translator.Translate(SectionKeyName1); if (!string.IsNullOrEmpty(translation)) { txtBox.Text = translation; } } stringField = SectionKeyName2; //this is class scope string field if (!string.IsNullOrEmpty(SectionKeyName2)) { string translation = Translator.Translate(SectionKeyName2); if (!string.IsNullOrEmpty(translation)) { stringField = translation; } } stringVariable = SectionKeyName3; //this is method scope string variable if (!string.IsNullOrEmpty(SectionKeyName3)) { string translation = Translator.Translate(SectionKeyName3); if (!string.IsNullOrEmpty(translation)) { stringVariable = translation; } } </code></pre> <p>As I see, this code can be refactored to one method, that receives the "object" to set and SectionKeyName. So it can be something like:</p> <pre><code>public void Translate(ref target, string SectionKeyName) { target = SectionKeyName; if (!string.IsNullOrEmpty(SectionKeyName)) { string translation = Translator.Translate(SectionKeyName); if (!string.IsNullOrEmpty(translation)) { target = translation; } } } </code></pre> <p><strong>BUT</strong>: I will can not use that method in case when I want to assign texBox.Text, since properties can not be passed byref.... <a href="https://stackoverflow.com/questions/1402803/passing-properties-by-reference-in-c-sharp">I found topic on SO where is solution for properties</a>, but it solves the properties and I stuck with fields / variables....</p> <p>Please help me to find the way to write a single method that will handle all of my cases...</p> <pre><code>//This method will work to by varFieldProp = Translate(SectionKeyName, SectionKeyName), but would like to see how to do it with Lambda Expressions. public string Translate(string SectionKeyName, string DefaultValue) { string res = DefaultValue; //this is string property of control or of any other type if (!string.IsNullOrEmpty(SectionKeyName)) { string translation = Translator.Translate(SectionKeyName); if (!string.IsNullOrEmpty(translation)) { res = translation; } } return res; } </code></pre> <p>Thank you !!!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload