How To Properly Use ?? With Default Values
May 25th, 2007 by Sameer | Filed under .NET articles.Let’s define a nullable. You can declare a variable as nullable, for example
int ? x;
You are saying that the int might have a value, or it might have a null value. This is convenient
Now in your code you might want to check and see if its actually null and if it is, give it some default Value. There is a shortcut for this in C# which is ??. The ?? shortcut does not apply only to nullable values. You can use it with anything that may be null.
Here is an example of how to use it. In the following case, our ViewState for the key "readonly" might be null (i.e. we did not put anything in there yet), and we want to get a default value of true if it is null. Here is how we can cast it
myName.Visible = (
However, this will give you:
CS0019: Operator '??' cannot be applied to operands of type 'bool' and 'bool'
bool)(ViewState["readonly"]) ?? true;
So what can we do?
myName.Visible = (
With VB.NET, you would have to do something like
myName.Visible = IsNothing(ViewState("readonly"))
Or if you needed more than just a boolean,
myString = IIf(IsNothing(ViewState("isAdude")), "dude!" , "not a dude!")
Read more about nullables and the ?? operator
bool)(ViewState["readonly"] ?? true); This way you have said if its null, it will be true, then casted the whole thing. That way you use this as 1 value on a single line rather than having a complicated if null then do this otherwise set it to this, yada yada..
