3

Possible Duplicate:
Hidden Features of C#?

What is it? Is it useful? Where?

??
Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
WishToBePro
  • 183
  • 1
  • 2
  • 11

5 Answers5

8

This is the null-coalescing operator and allows you to set a default value if the object is null.

http://msdn.microsoft.com/en-us/library/ms173224.aspx

Aim Kai
  • 2,934
  • 1
  • 22
  • 34
7

It work this way;

Object a = otherObject ?? "otherObject is null";

It means otherObject will be assigned to "a" if it is not null. If it is null the object at right will be assigned to "a".

Its useful for me when I wanna set default values;

public class MyClass
{
    private Object b;
    public MyClass(Object a)
    {
        b = a ?? "Deafult Value";
    }
}

Official documentation can also be found here; MSDN

Renato Gama
  • 16,431
  • 12
  • 58
  • 92
3
object o = someObject ?? anotherObject;

is the same

object o;
if(someObject == null)
  o = anotherObject;
else
  o = someObject;
Stecya
  • 22,896
  • 10
  • 72
  • 102
1

*The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand. http://msdn.microsoft.com/en-us/library/ms173224.aspx

    // Assign i to return value of method, unless
    // return value is null, in which case assign
    // default value of int to i.
    int i = GetNullableInt() ?? default(int);

*

Maybe you can use it to simplify some repetitive code pieces.

Sebastjan
  • 142
  • 1
  • 5
  • 13
1

This is called the null coalescing operator ( http://msdn.microsoft.com/en-us/library/ms173224.aspx ).

You can use it to return the right hand side of it, if the left hand side is null; otherwise, it will return left hand side.

For example, you can use it to simplify this (in an ASP.NET application):

public string SessionStore
{
    get 
    { 
        if( Session["MyData"] == null )
        {
            return "default value";
        }

        return (string)(Session["MyData"]);
    }
    set { Session["MyData"] = value; }
}

Into this :

public string SessionStore
{
    get { return (string)(Session["MyData"]) ?? "default value"; }
    set { Session["MyData"] = value; }
}
mathieu
  • 30,974
  • 4
  • 64
  • 90