Tuesday, July 18, 2006
C# 2.0 Syntax - the nullable type operand ?
Since the last post was about C# syntax I thought I would continue the subject by introducing another not so well document feature, the question mark. I stumbled upon this one when looking through some generated code by VS and was really puzzled by it. So here is what the line of code looked like:
private int? number;
I looked this up and after some effort I finally found my answer. The question mark following the datatype declaration means this variable is nullable type, that is, it says the value of this variable can either be an int or it can be null.
This is the first step towards making the language more friendly for code geared towards database manipulation.
Hand in hand with the addition of the ? operator is the ?? operator which is used like this:
public int myNumber = number??18;
Since number is of nullable type, it's possible this would throw an exception if number was in fact null and we tried to assign it to an int variable of non-nullable type. So what the ?? operator does is say "if number is null then return 18 otherwise return the value of number".
Since the last post was about C# syntax I thought I would continue the subject by introducing another not so well document feature, the question mark. I stumbled upon this one when looking through some generated code by VS and was really puzzled by it. So here is what the line of code looked like:
private int? number;
I looked this up and after some effort I finally found my answer. The question mark following the datatype declaration means this variable is nullable type, that is, it says the value of this variable can either be an int or it can be null.
This is the first step towards making the language more friendly for code geared towards database manipulation.
Hand in hand with the addition of the ? operator is the ?? operator which is used like this:
public int myNumber = number??18;
Since number is of nullable type, it's possible this would throw an exception if number was in fact null and we tried to assign it to an int variable of non-nullable type. So what the ?? operator does is say "if number is null then return 18 otherwise return the value of number".
