Reputation: 331
I've seen this code sample question in a exam and it works perfectly.
namespace Trials_1
{
class Program
{
static void Main(string[] args)
{
int? a = 9;
Console.Write("{0}", a);
}
}
}
But the below code throws an error CS0266.
namespace Trials_1
{
class Program
{
static void Main(string[] args)
{
int? a = 9;
int b = a;
Console.Write("{0},{1}", a, b);
}
}
}
Can somebody explain me in detail?
Upvotes: 7
Views: 16837
Reputation: 308
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
Upvotes: 2
Reputation: 1047
If you want to convert an int? to int, you have to cast it:
int? a = 9;
int b = (int)a;
Or:
int b = a.Value;
B.t.w: this woont give any problem:
int a = 9;
int? b = a;
Upvotes: 2
Reputation: 29016
The variable b
is of type int
and you are trying to assign int?
to an int
. which will be wrong assignment(if a
is null, then you cannot assign it to non-nullable object b
, so compiler will not permit this): alternatively you can use:
int? a = 9;
int b = a == null ? 0 : 1;
Console.Write("{0},{1}", a, b);
Upvotes: 0
Reputation: 2978
This is a C# nullable types
Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)
This line int b = a;
throws an error because you cannot directly assign an int
type into a nullable int
type. In other words, int
datatype cannot accept null
value.
Upvotes: 3
Reputation: 2113
int?
is shorthand for Nullable<int>
and indicates that a value of null
can be assigned to the variable.
In the example given, the type of variable b
is an int
, which cannot accept a value of Nullable<int>
.
Refer to This MSDN article for more information.
Upvotes: 2
Reputation: 22911
Some info on error CS0266
:
Cannot implicitly convert type 'type1' to 'type2'. An explicit conversion exists (are you missing a cast?) This error occurs when your code tries to convert between two types that cannot be implicitly converted, but where an explicit conversion is available.
A nullable int (int?
) cannot be converted simply converted to an int. An int by default cannot be null, so trying to convert something that can be null, to something that can't be null, gives you this error. Because you're trying to make this assumption, the compiler is telling you, you can't.
See this post on how to convert from a nullable int to an int.
Upvotes: 0