Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# shorthand for if not null then assign value

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();                
        }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...