I use null to denote that an optional parameter A? a of a function should assume a non-null default value, computed in the function. After entering the function, I check whether the passed-in argument a is null, and if so, assign a a non-null value. From that point on, it can safely be assumed that a is non-null. The problem: the compiler is not aware of this, and now I have to refer to a.Value for the rest of the function, instead of the straightforward a.
Is there a way to tell the compiler that a is actually non-null from some point on? If not, what is the clearest way to deal with such optional parameters?
Example code:
using System;
namespace test
{
public struct A { public int x; };
class Program
{
static void f(A? a = null)
{
// Assign the default value.
if (a == null) a = new A { x = 3 };
// Now 'a' is non-null for the rest of the function.
// What I do now:
Console.WriteLine(a.Value.x);
// What I'd like to do:
// * Mark 'a' as non-null somehow.
// Now can refer to 'a' directly:
// Console.WriteLine(a.x);
}
static void Main(string[] args)
{
f();
}
}
}