Link to home
Start Free TrialLog in
Avatar of juarrero
juarreroFlag for Spain

asked on

Convert a null value to null value

Hello:

I want to convert a value of a nullable type to another nullable type, in order to get a simple code avoiding to use an IF/THEN sentence.

I thought I could use the Convert class but I found out that a null is not converted to a null even when both types are nullable and can hold the null value.

In the example code below you can see how null is converted to 0 when using int?, so resulting in missing the null.

How could I achieve this?

Thanks in advance,

Juarrero

class Program
    {
        int? a;
        int? b; 
 
        static void Main(string[] args)
        {
            Program P = new Program();
 
            P.a = null;
 
            // Using Convert
            P.b = Convert.ToInt32(P.a);
            if (P.b == null) { Console.WriteLine("null"); } else { Console.WriteLine(P.b); }
 
            // Without using Convert
            P.b = P.a;
            if (P.b == null) { Console.WriteLine("null"); } else { Console.WriteLine(P.b); }
 
            Console.ReadLine();
        }
    }

Open in new window

SOLUTION
Avatar of johnaryan
johnaryan
Flag of Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of juarrero

ASKER

johnaryan provided the first response and _Gerry_ provided a more complete one.

Thanks you both.

Juarrero