private int? _City_Id;
Without knowing your target language to respond with, in C# 2.0 the ? denotes nullable value types.
Nullable value types (denoted by a question mark, e.g. int? i = null;) which add null to the set of allowed values for any value type.
Which, as Calum points out (all credit to him), means that the variable can be assigned null. Normally primitives like int and double can't be null,
int? x = 10;
double? d = 4.108
Related
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.
I would like to check if the decimal number is NULL or it has some value, since the value is assigned from database in class object:
public decimal myDecimal{ get; set; }
and then I have
myDecimal = Convert.ToDecimal(rdrSelect[23].ToString());
I am trying:
if (rdrSelect[23] != DBNull.Value)
{
myDecimal = Convert.ToDecimal(rdrSelect[23].ToString());
}
But I am getting this:
the result of the expression is always 'true' since a value of type
'decimal' is never equal to null
How can I check if that decimal number has some value?
A decimal will always have some default value. If you need to have a nullable type decimal, you can use decimal?. Then you can do myDecimal.HasValue
you can use this code
if (DecimalVariable.Equals(null))
{
//something statements
}
decimal is a value type in .NET. And value types can't be null. But if you use nullable type for your decimal, then you can check your decimal is null or not. Like myDecimal?
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.
if (myDecimal.HasValue)
But I think in your database, if this column contains nullable values, then it shouldn't be type of decimal.
I've ran across this problem recently while trying to retrieve a null decimal from a DataTable object from db and I haven't seen this answer here. I find this easier and shorter:
var value = rdrSelect.Field<decimal?>("ColumnName") ?? 0;
This was useful in my case since i didn't have a nullable decimal in the model, but needed a quick check against one. If the db value happens to be null, it'll just assign the default value.
Assuming you are reading from a data row, what you want is:
if ( !rdrSelect.IsNull(23) )
{
//handle parsing
}
Decimal is a value type, so if you wish to check whether it has a value other than the value it was initialised with (zero) you can use the condition myDecimal != default(decimal).
Otherwise you should possibly consider the use of a nullable (decimal?) type and the use a condition such as myNullableDecimal.HasValue
If you're pulling this value directly from a SQL Database and the value is null in there, it will actually be the DBNull object rather than null. Either place a check prior to your conversion & use a default value in the event of DBNull, or replace your null check afterwards with a check on rdrSelect[23] for DBNull.
You can also create a handy utility functions to handle values from DB in cases like these.
Ex. Below is the function which gives you Nullable Decimal from object type.
public static decimal? ToNullableDecimal(object val)
{
if (val is DBNull ||
val == null)
{
return null;
}
if (val is string &&
((string)val).Length == 0)
{
return null;
}
return Convert.ToDecimal(val);
}
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.
I am going over some code written by another developer and am not sure what long? means:
protected string AccountToLogin(long? id)
{
string loginName = "";
if (id.HasValue)
{
try
{....
long is the same as Int64
long data type
The ? means it is nullable
A nullable type can represent the
normal range of values for its
underlying value type, plus an
additional null value
Nullable Types
Nullable example:
int? num = null;
if (num.HasValue == true)
{
System.Console.WriteLine("num = " + num.Value);
}
else
{
System.Console.WriteLine("num = Null");
}
This allows you to actually check for a null value instead of trying to assign an arbitrary value to something to check to see if something failed.
I actually wrote a blog post about this here.
long is an Int64, the ? makes it nullable.
"long?" is a nullable 64-bit signed integer. It's equivalent to Nullable<Int64>.
long? is a 64-bit, nullable integer.
To clarify, nullable means it can be null or an integer number ( 0, 1, etc.).
long? is a nullable type. This means that the id parameter can have a long value or be set to null. Have a look at the HasValue and Value properties of this parameter.
It's a nullable type declaration.
Typically the main use of the question mark is for the conditional, x ? "yes" : "no".
But I have seen another use for it but can't find an explanation of this use of the ? operator, for example.
public int? myProperty
{
get;
set;
}
It means that the value type in question is a nullable type
Nullable types are instances of the System.Nullable struct. A
nullable type can represent the correct range of values for its
underlying value type, plus an additional null value. For example, a
Nullable<Int32>, pronounced "Nullable of Int32," can be assigned any
value from -2147483648 to 2147483647, or it can be assigned the null
value. A Nullable<bool> can be assigned the values true, false, or
null. The ability to assign null to numeric and Boolean types is
especially useful when you are dealing with databases and other data
types that contain elements that may not be assigned a value. For
example, a Boolean field in a database can store the values true or
false, or it may be undefined.
class NullableExample
{
static void Main()
{
int? num = null;
// Is the HasValue property true?
if (num.HasValue)
{
System.Console.WriteLine("num = " + num.Value);
}
else
{
System.Console.WriteLine("num = Null");
}
// y is set to zero
int y = num.GetValueOrDefault();
// num.Value throws an InvalidOperationException if num.HasValue is false
try
{
y = num.Value;
}
catch (System.InvalidOperationException e)
{
System.Console.WriteLine(e.Message);
}
}
}
It is a shorthand for Nullable<int>. Nullable<T> is used to allow a value type to be set to null. Value types usually cannot be null.
In
x ? "yes" : "no"
the ? declares an if sentence. Here: x represents the boolean condition; The part before the : is the then sentence and the part after is the else sentence.
In, for example,
int?
the ? declares a nullable type, and means that the type before it may have a null value.
it declares that the type is nullable.
practical usage:
public string someFunctionThatMayBeCalledWithNullAndReturnsString(int? value)
{
if (value == null)
{
return "bad value";
}
return someFunctionThatHandlesIntAndReturnsString(value);
}
int? is shorthand for Nullable<int>. The two forms are interchangeable.
Nullable<T> is an operator that you can use with a value type T to make it accept null.
In case you don't know it: value types are types that accepts values as int, bool, char etc...
They can't accept references to values: they would generate a compile-time error if you assign them a null, as opposed to reference types, which can obviously accept it.
Why would you need that?
Because sometimes your value type variables could receive null references returned by something that didn't work very well, like a missing or undefined variable returned from a database.
I suggest you to read the Microsoft Documentation because it covers the subject quite well.
Means that the variable declared with (int?) is nullable
int i1=1; //ok
int i2=null; //not ok
int? i3=1; //ok
int? i4=null; //ok
To add on to the answers above, here is a code sample
struct Test
{
int something;
}
struct NullableTest
{
int something;
}
class Example
{
public void Demo()
{
Test t = new Test();
t = null;
NullableTest? t2 = new NullableTest();
t2 = null;
}
}
This would give a compilation error:
Error 12 Cannot convert null to 'Test' because it is a non-nullable
value type
Notice that there is no compilation error for NullableTest. (note the ? in the declaration of t2)
To add on to the other answers:
Starting in C# 8.0, Nullable<> and ? are NOT always interchangeable. Nullable<> only works with Value types, whereas ? works with both Reference and Value types.
These can be seen here in the documentation
"A nullable reference type is noted using the same syntax as nullable
value types: a ? is appended to the type of the variable."
And here
public struct Nullable<T> where T : struct