What is the meaning of the ? operator? [duplicate] - c#

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.

Related

What does the statement "int? i1 = i2" do in c#? [duplicate]

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

Why must I cast to (int?) in C# when variable type is [int?]

Can someone please explain me the logic reason why I must cast null to int?
When the left argument type can have their both types ?
Insted of doing
int? k = (DateTime.Now.Ticks%5 > 3 ? 1 : null);
I must do
int? k = (DateTime.Now.Ticks%5 > 3 ? 1 : (int?) null);
although int? k = null is perfectly valid.
An opposite example :
I didn't have to do it in:
string k = (DateTime.Now.Ticks%5 > 3 ? "lala" : null);
int? k = (DateTime.Now.Ticks%5 > 3 ? 1 : (int?) null);
In this case what we have is 1 is int and null is actually null
Now the confusion is the ternary operator is confused as what is the return type int or well null and since its int it won't accept null
So you would need to cast it to a nullable int
Now in the other case you have a string and null is perfectly acceptable for a string
Further explanation can be found at Type inference - Eric
The second and third operands of the ?: operator control the type of
the conditional expression. Let X and Y be the types of the second and
third operands. Then,
If X and Y are the same type, then this is the type of the conditional expression.
Otherwise, if an implicit conversion exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.
Otherwise, if an implicit conversion exists from Y to X, but not from X to Y, then X is the type of the conditional expression.
Otherwise, no expression type can be determined, and a compile-time error occurs.
Because the compiler doesn't use the type of the variable in the left hand side to determine the type of the expression on the right hand side. First it determines what type the expression is, then it determines if it's possible to put it in the variable.
There is no type close enough that is common between an int and a null value. You have to either make the int value nullable or the null value "intable" for the compiler to find a common ground for the values.
When you have a string and a null value the compiler can simply use one of the types, because a string is already nullable.

Why type "int" is never equal to 'null'?

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.

private int? _City_Id; can any one tell me what "?" means here

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

What is the purpose of a question mark after a value type (for example: int? myVariable)?

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

Categories

Resources