c# shorthand for if not null then assign value
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);
I googled "c# shorthand set if null" and first landed here, so just for others. The question was "shorthand for if NOT null then assign value", the following is "shorthand for if null then assign value".
In C# 8.0+ you can use ??=
:
// Assign to testVar1, if testVar2 is null
testVar2 ??= testVar1;
// Which is the same as:
testVar2 = testVar2 ?? testVar1;
// Which is the same as:
if(testVar2 == null)
{
testVar2 = testVar1;
}
And my favorite:
// Create new instance if null:
testVar1 ??= new testClass1();
// Which is the same as:
if(testVar1 == null)
{
testVar1 = new testClass1();
}
Just an example which I use very often:
List<string> testList = null;
// Add new test value (create new list, if it's null, to avoid null reference)
public void AddTestValue(string testValue)
{
testList ??= new List<string>();
testList.Add(testValue);
}