Moment @ Nullable in .Net
| Posted in C# | Posted on 23-03-2010
0
Nullable value…why are we introducing …
in studying of object oriented concepts, we know that we have two data type Value type & Reference type the famous difference between the two is the.
- value type contain the actual value of variable but,
- reference type contain the address (reference) of the object
but there is another difference which may be some people don’t know it
- value type can’t contain null value, if it hasn’t value, it will be default value (for example, int data type if it doesn’t have any value it will be Zero).
- reference type allow null value.
now you get the difference, let ask you a question, Do we need null in value type ? …thinking… the answer is yes, we need it. let’s imagine that we have database contain employee which consist some columns may be allow null like Salary and so on, how you can map this @code, if you use default value … so you didn’t get the actual meaning of your business @your code. null value doesn’t means zero or empty string, it means that you don’t have enough information . so there are difference … the solution is Nullable Value. Nullable value is new generic type which allow nullability of value type, Nullable<T>.
Nullable @C#
- ? is new modifier means Nullable so when you need to define Nullable value type int? i;
- ?? operator can convert from Nullable type to non-Nullable type with default value. So “ int x; int? y; x = y ?? 0“ will assign the value of y to x if it is not null, and will assign the value 0 to x otherwise.
- if you try to add two Nullable values and one of two is null value so the result of final addition will be NULL
- For comparison operators, comparing two nullable types is always going to result in a bool value, not a bool? value.
int? nullableInt; int? nullValue = null; int? notNull = 123; bool? answer1 = true; bool? answer2 = false; bool? answer3 = null;
int? nullableInt; int? copy = nullableInt; // Invalid as nullableInt is not yet assignedint standardInteger = 123; int? nullableInteger; decimal standardDecimal = 12.34M; // Implicit conversion from int to int? nullableInteger = standardInteger; // Explicit conversion from int? to int standardInteger = (int)nullableInteger; // Explicit cast from decimal to int? nullableInteger = (int?)standardDecimal;int? a = 55; int? n = null; int? result; result = a * 2; // result = 110 result = a * n; // result = nullbool? result; result = true & null; // result = null result = false & null; // result = false result = true | null; // result = true result = false | null; // result = null result = true ^ null; // result = null result = false ^ null; // result = null
My Source: http://www.blackwasp.co.uk/CSharpNullableDataTypes.aspx





Use the Highlighter
This website now has an AutoPublish widget:

