There are a couple!
The ternary operator:
testvar2 = testVar1 != null ? testvar1 : testvar2;
Would be exactly the same logic.
Or, as commented you can use the null coalescing operator:
testVar2 = testVar1 ?? testVar2
(although now that's been commented as well)
Or a third option: Write a method once and use it how you like:
public static class CheckIt
{
public static void SetWhenNotNull(string mightBeNull,ref string notNullable)
{
if (mightBeNull != null)
{
notNullable = mightBeNull;
}
}
}
And call it:
CheckIt.SetWhenNotNull(test1, ref test2);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…