c# shorthand for if not null then assign value

梦想与她 提交于 2021-02-15 05:59:24

问题


Is there any shorthand in c# now that will cutdown the following code:

var testVar1 = checkObject();
if (testVar1 != null)
{
      testVar2 = testVar1;
}

In this situation only want to assign testVar2 if testVar1 is not null from the CheckObject() result (testVar2 has a setter that will fire off code). Was trying to think how could use the null coalesce stuff but not really working out.

Adding on to this testVar2 has code on it's setter to fire, so do not want testVar2 being set to anything if the value is null.

    public MyObj testVar2
    {
        get { return _testVar2; }
        set
        {
            _testVar2 = value;
            RunSomeCode();                
        }
    }

回答1:


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);



回答2:


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);
}



回答3:


You mention that testVar2 has a setter that fires off some event when it gets set. If you aren't checking that testVar2 is being set to itself the event will still fire using the null coalescing operator (or the ternary operator).

I think you'll either have to check for testVar2 being set to itself in its setter, or do what you're doing now.

    public MyObj testVar2
    {
        get { return _testVar2; }
        set
        {
            if (_testVar2 != value)
            {
               _testVar2 = value;
               RunSomeCode();
            }                
        }
    }

I reckon this is totally my opinion but I would leave it how you have it now. I think it communicates the intent better than the short hand.

testVar2 = testVar1 ?? tesrVar2 says, "set testVar2 to testVar1. Unless testVar1 is null. Then set testVar2 to testVar2".

if (testVar1 != null)
{
   testVar2 = testVar1;
}

says, "if testVar1 is not null, set testVar2 to testVar1".




回答4:


You could use the null-coalescing operator, which would look like this: testVar2 = testVar1 ?? testVar2. You can replace ?? testVar2 with whatever you want to set it to if testVar1 is null.




回答5:


If you never want to allow testVar2 to be set to null, then it probably makes more sense to check for null in the setter itself. Otherwise you have to remember to check for null anytime you try to set it.

Note that I also modified the casing to conform to C# standards

private MyObj testVar2;

public MyObj TestVar2
{
    get { return testVar2; }
    set
    {
        if (value == null) return;      // Or throw an ArgumentNullException
        if (testVar2 == value) return;  // No need to RunSomeCode if the value isn't changing

        testVar2 = value;
        RunSomeCode();                
    }
}

Now, if your concern is still to check for null before setting the property (if, for example, you decided to throw an exception in the case of a null value), then there's nothing wrong with your original code (the ternary/null-coalescing solutions seem "wasteful" somehow, in that they may set something to itself), and you can do it in one line:

if (testVar1 != null) SomeClass.TestVar2 = testVar1;

If, however, you're only creating testVar1 in order to capture the result of the call to CheckObject(), then the null-coalescing operator makes a little more sense because you don't have to create a variable to store the value:

SomeClass.TestVar2 = CheckObject() ?? SomeClass.TestVar2;


来源:https://stackoverflow.com/questions/56485596/c-sharp-shorthand-for-if-not-null-then-assign-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!