How To Properly Use ?? With Default Values
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..
Related Reading:
Other Interesting Posts
-
Articles
- January 2011
- April 2010
- March 2010
- February 2010
- January 2010
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- February 2009
- December 2008
- November 2008
- October 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
- June 2007
- May 2007
-
Meta







