6

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?

prathapa reddy
  • 321
  • 1
  • 4
  • 17
  • Possible duplicate of [How to convert C# nullable int to int](http://stackoverflow.com/questions/5995317/how-to-convert-c-sharp-nullable-int-to-int) –  Jul 29 '16 at 02:22

6 Answers6

3

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.

Anonymous Duck
  • 2,942
  • 1
  • 12
  • 35
2

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.

TimS
  • 2,085
  • 20
  • 31
2

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;
Stef Geysels
  • 1,023
  • 11
  • 27
1

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
lucaspompeun
  • 170
  • 1
  • 9
0

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.

Community
  • 1
  • 1
Blue
  • 22,608
  • 7
  • 62
  • 92
0

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); 
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88