Shorthand for create new instance if null?

后端 未结 5 1671
庸人自扰
庸人自扰 2021-01-12 13:49

In Javascript I can do this:

var myVar = returnNull() || new MyObject();

In C# I am currenly doing this:

var myVar = returnObjec         


        
相关标签:
5条回答
  • 2021-01-12 14:17

    use ?? operator

    foo ?? new Foo();
    

    Or in your case

    var myVar = returnObjectOrNull() ?? new MyObject();
    

    The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.

    0 讨论(0)
  • 2021-01-12 14:33

    Yes there is, it's called the null coalescing operator:

    var myVar = returnObjectOrNull() ?? new MyObject();
    

    Note that this operator will not evaluate the right-hand side if the left-hand side is not null, which means that the above line of code will not create a new MyObject unless it has to.

    Here's an example LINQPad program to demonstrate:

    void Main()
    {
        var myVar = returnObjectOrNull() ?? new MyObject();
    }
    
    public MyObject returnObjectOrNull()
    {
        return new MyObject();
    }
    
    public class MyObject
    {
        public MyObject()
        {
            Debug.WriteLine("MyObject created");
        }
    }
    

    This will output "MyObject created" once, meaning that there is only one object being created, in the returnObjectOrNull method, not the one in the ?? statement line.

    0 讨论(0)
  • 2021-01-12 14:36

    Use the null-coalescing operator:

    var myvar = returnObjectOrNull() ?? new MyObject();
    
    0 讨论(0)
  • 2021-01-12 14:38

    You can use ?? Operator (C# Reference) operator like;

    var myVar = returnObjectOrNull() ?? new MyObject();
    

    The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.

    0 讨论(0)
  • 2021-01-12 14:42

    Use the null coalescing operator

    var myVar = returnObjectOrNull();
    
    myVar = myVar ?? new MyObject();
    
    0 讨论(0)
提交回复
热议问题