This question already has answers here:
Nullable integer in .NET
(6 answers)
Closed 8 years ago.
I have been reading a c# tutorial and it has mentioned about nullable types and in that particular context I have gone through this example
int? i1 = i2;
I was unable to understand what does it exactly do and what it mean.
It means, declare a nullable int type and assign it the value of i2.
Because i1 has nullable type int?, i2 can be an int literal like 5, a variable of type int, a variable of type int? or the literal value null.
It creates a nullable integer. Meaning you can set i1 = null; and easily test for its nullity i1.HasValue.
int? i1 means that i1 variable can be null means nullable variable and you are assigning i2 to it whatever the value is in i2.
For Example:
if i have a method like:
public int sum(int? num)
{
return 1;
}
int? means that num is can be passed as null instead of valid integer.
See Nullable Types in C#
It is semantically the same as
Nullable<int> i1 = i2
Related
This question already has answers here:
Nullable types and the ternary operator: why is `? 10 : null` forbidden? [duplicate]
(9 answers)
Closed 5 years ago.
int a = 1;
int? b = a;
Console.WriteLine(b);
The above snippet is fine and will convert int directly to int?, no explicit conversion is required
but
List<int> temp = new List<int>{1};
int? valueVariable = temp!=null && temp.Count>0 ? temp[0] : null ;
Console.WriteLine(valueVariable);
will have compile time error.
to fix this We need to cast to int?
// Working Snippet with int? casting
int? valueVariable = temp!=null && temp.Count > 0 ? (int?) temp[0] : null ;
https://dotnetfiddle.net/0x7ckL
Why we needed casting here,although the same was working for first example?
The reason is that ternary operator must use the SAME type in both branches. So true and false return values must be either int? or int. Cannot use two different types.
This question already has answers here:
convert int to nullable int?
(6 answers)
Closed 7 years ago.
Iam confused by the ChangeType Method of .Net. I wrote a extension method to convert object values (which come from database in my cases) in the expected type. So long iam not using nullable types this works pretty good.
Iam doing this so far:
public static T ConvertTo<T>(this object value)
{
T returnValue = default(T);
if ((value != null) &&
(value != DBNull.Value))
{
returnValue = (T)Convert.ChangeType(value, typeof(T));
}
return returnValue;
}
If i call:
int test = myObject.ConvertTo<int>();
Iam getting the int value or 0 if myObject doesn't contain a int.
Because it is possible to do the following:
int? test = 5;
I thought there is no problem to cast a int to int?. But if i call this:
int? test = myObject.ConvertTo<int?>();
Iam getting System.InvalidCastException. Invalid cast from System.Int32 to System.Nullable`1
The Exception is thrown in the Convert.ChangeType line.
Somebody knows why?
Because int? is shorthand for Nullable<int> which is different to int. Those are two different types in .Net. If you want to cast int? to int or vice versa you have to do it manually.
Edit
Conversion from double to int is defined whereas conversion from nullable types to normal numerical types is not.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# okay with comparing value types to null
I came a cross something I find strange in the C# (4.0) compiler just now.
int x = 0;
if (x == null) // Only gives a warning - 'expression is always false'
x = 1;
int y = (int)null; // Compile error
int z = (int)(int?)null; // Compiles, but runtime error 'Nullable object must have a value.'
If you cannot assign null to an int, why does the compiler allow you to compare them (It gives a warning only)?
Interestingly, the compiler does not allow the following:
struct myStruct
{
};
myStruct s = new myStruct();
if (s == null) // does NOT compile
;
Why does the struct example not compile, but the int example does?
When the comparison is made, the compiler tries to make it so both operands of the comparison have compatible types if possible.
It had an int value and a constant null value (with no particular type). The only compatible type between the two values is int? so they are coerced to int? and compared as int? == int?. Some int value as an int? is definitely non-null and null is definitely null. The compiler realizes that and since a non-null value is not equal to a definite null value, the warning is given.
actually compilation allow comparing 'int?' to 'int' not 'int' to null which make sense
e.g.
int? nullableData = 5;
int data = 10;
data = (int)nullableData;// this make sense
nullableData = data;// this make sense
// you can assign null to int
nullableData = null;
// same as above statment.
nullableData = (int?)null;
data = (int)(int?)null;
// actually you are converting from 'int?' to 'int'
// which can be detected only at runtime if allowed or not
and that's what you are trying to do in int z = (int)(int?)null;
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# using the question mark after a type, for example: int? myVariable; what is this used for?
I saw the ? operator used in many places and tried to Google and StackOverflow it but both search engine exclude it from the query and does not return any good answers.
What is the meaning of this operator? I usually see it after the type declaration like:
int? x;
DateTime? t;
What is the difference between the two following declaration of an int for example:
int? x;
// AND
int x;
This operator is not an operator, but merely the syntactic sugar for a Nullable type:
int? x;
is the same as
Nullable<int> x;
You can read this : Nullable type -- Why we need Nullable types in programming language ?
int? x;//this defines nullable int x
x=null; //this is possible
// AND
int x; // this defines int variable
x=null;//this is not possible
It is not operator, but int? is shortcut for the Nullable<int>. Nullable<> is container that allows to set some value-type variable null value as well.
It called nullable types.
Nullable types are instances of the System.Nullable struct. A nullable
type can represent the normal range of values for its underlying value
type, plus an additional null value.
int? x;
is equivalent to
Nullable<int> x;
? operator indicates the type is nullable.
For example;
int? x = null; //works properly since x is nullable
and
int x = null; //NOT possible since x is NOT nullable
Note that the way you access the value of the variable changes;
int? x = null;
int y = 0;
if (x.HasValue)
{
y = x.Value; // OK
}
And
y = x; //not possible since there is no direct conversion between types.
Diffrence b/w int? and int is int? can store null but int can't.
int? is called nullable operators and its used basically when working with database entities.
more info -http://msdn.microsoft.com/en-us/library/1t3y8s4s(v=vs.80).aspx
hope this helps !!
That operator makes all objects that is non nullable to nullable.
So it means if you will declare a variable int? x, it could be assigned like this:
int? x = null. If without the ? sign, you cannot assign it with a null value.
int n == 0;
if (n == null)
{
Console.WriteLine("......");
}
Is it true that the result of expression (n == null) is always false since
a value of type int is never equal to null of type int? (see warning below)
Warning CS0472 The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?'
If you want your integer variable to allow null values, declare it to be a nullable type:
int? n = 0;
Note the ? after int, which means that type can have the value null. Nullable types were introduced with v2.0 of the .NET Framework.
In C# using an uninitialized variable is not allowed.
So
int i;
Console.Writeline(i);
Results in a compilation error.
You can initialize int with new such as:
int anInt = new int();
This will result in the Default value for int which is 0. In cases where you do wish to have a generic int one can make the int nullable with the syntax
int? nullableInt = null;
Because int is a value type rather than a reference type. The C# Language Specification doesn't allow an int to contain null. Try compiling this statement:
int x = null ;
and see what you get.
You get the compiler warning because it's a pointless test and the compiler knows it.
"Value types" in .NET (like int, double, and bool) cannot, by definition, be null - they always have an actual value assigned. Check out this good intro to value types vs. reference types.
The usage of NULL applies to Pointers and References in general. A value 0 assigned to an integer is not null. However if you can assign a pointer to the integer and assign it to NULL, the statement is valid.
To sum up =>
/*Use the keyword 'null' while assigning it to pointers and references. Use 0 for integers.*/
Very simply put, an int is a very basic item. It's small and simple so that it can be handled quickly. It's handled as the value directly, not along the object/pointer model. As such, there's no legal "NULL" value for it to have. It simply contains what it contains. 0 means a 0. Unlike a pointer, where it being 0 would be NULL. An object storing a 0 would have a non-zero pointer still.
If you get the chance, take the time to do some old-school C or assembly work, it'll become much clearer.
public static int? n { get; set; } = null;
OR
public static Nullable<int> n { get; set; }
or
public static int? n = null;
or
public static int? n
or just
public static int? n { get; set; }
static void Main(string[] args)
{
Console.WriteLine(n == null);
//you also can check using
Console.WriteLine(n.HasValue);
Console.ReadKey();
}
The null keyword is a literal that represents a null reference, one that does not refer to any object.
In programming, nullable types are a feature of the type system of some programming languages which allow the value to be set to the special value NULL instead of the usual possible values of the data type.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null
https://en.wikipedia.org/wiki/Null
No, because int is a value type. int is a Value type like Date, double, etc. So there is no way to assigned a null value.