Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();                
        }
    }
like image 306
Matt Avatar asked Jun 06 '19 21:06

Matt


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.


1 Answers

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);
like image 140
Austin T French Avatar answered Oct 11 '22 13:10

Austin T French