Possible Duplicate:
Hidden Features of C#?
What is it? Is it useful? Where?
??
This is the null-coalescing operator and allows you to set a default value if the object is null.
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
object o = someObject ?? anotherObject;
is the same
object o;
if(someObject == null)
o = anotherObject;
else
o = someObject;
*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.
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; }
}