C# Nullabalicious!

Something I’ve started using lately, and quite like… is C#’s ‘?’ property. This allows you to flag a parameter in a method’s constructor as ‘nullable’. In other words, when someone interfaces with your method, certain arguments can be left blank or set to null. This save’s creating overloaded methods. An example of such a method looks like:

public void PrintString(String text, int? numberOfTimes)
{
     int number = 1;
     if(numberOfTimes.HasValue)
          number = numberOfTimes.value;

     for(int i = 0; i < number + 1; i++)
     {
          DisplayString(text);
     }
}

Hope this helps or makes things easier in some cases :) .

  1. No comments yet.

  1. No trackbacks yet.