Thursday, March 26, 2009
Nullable Parameters in Public Interfaces
As discussed in previous posts, C# now has the concept of nullable value types via the
Conside, for example, a class with the following public method that uses a paremeter of type
Rather than exposing that method for use by others, it could instead be made
That code is pretty straight forward. The only trick is to cast the parameter as a
? operator. When used correctly, they can be very useful and solve some problems. But, quite honestly, I feel that they're kind of "hackish" to use them in public methods and interfaces. In many cases, you can simply make a few quick overloads to cleanup things up a bit.Conside, for example, a class with the following public method that uses a paremeter of type
int?.
public void MyMethod(int? myParameter)
{
...
}
Rather than exposing that method for use by others, it could instead be made
private and we could define a couple of public overloads.
public void MyMethod()
{
MyMethod();
}
public void MyMethod(int myParameter)
{
MyMethod(myParameter as int?);
}
private void MyMethod(int? myParameter)
{
...
}
That code is pretty straight forward. The only trick is to cast the parameter as a
int? before calling the private overload that does all the work. If you do not do that, then you will very quickly encounter a stack overflow.Subscribe to Posts [Atom]