views:

354

answers:

6

Is there anyway to have the var be of a nullable type?

This implicitly types i as an int, but what if I want a nullable int?

var i = 0;

Why not support this:

var? i = 0;

+2  A: 

Why support it? If that's what you mean, you should say var i = (int?)0; instead.

(Well, you should probably just say int? i = 0, but for more complicated types, etc.)

mquander
+2  A: 

var is typed implicitly by the expression or constant on the right hand side of the assignment. var in and of itself is not a type so Nullable<var> is not possible.

Andrew Hare
+1  A: 

The problem deals with nullable types.

For instance, you cannot create a nullable string, which in turn prevents you from creating a nullable var, since var could be a string.

JTA
A: 

My answer is kind of along these lines. "var" is implicitly typed. It figures out what type it is by the value supplied on the right-hand side of the assignment. If you tell it that it's nullable it has no idea what type to be. Remember, once it's assigned, that's the type it's going to be forever.

A: 

Try this - is this what you're talking about?

    static void Main(string[] args)
    {
        for (int i=0; i < 10; i++)
        {
            var j = testMethod();
            if (j == null)
            {
                System.Diagnostics.Debug.WriteLine("j is null");
            }
            else
            {
                System.Diagnostics.Debug.WriteLine(j.GetType().ToString());
            }
        }
    }

    static int? testMethod()
    {
        int rem;
        Math.DivRem(Convert.ToInt32(DateTime.Now.Millisecond), 2, out rem);
        if (rem > 0)
        {
            return rem;
        }
        else
        {
            return null;
        }
    }
D. Lambert