Use nullable parameters in C#

The example Use null to simulate optional parameters in C# explains how you can pass null to a method to simulate optional parameters but that only works for reference types. Value types such as int and bool cannot take the value null so you cannot pass null for parameters of those types.

To work around this restriction, you can use nullable types. Using a special syntax, you can create a type from a value type that can be null. To do this, add a question mark after the parameter's type as in the following declaration.

int? num_points;

To see if a nullable variable contains a value, use its HasValue property. If the variable has a value, use its Value property to get that value.

The following DrawStar method draws a star. The num_points, star_pen, and star_brush parameters can all be null. The star_pen and star_brush parameters can be null because they are object references and those can always be null. The num_points parameter is a nullable integer.

// Draw a star.
private void DrawStar(Graphics gr, int? num_points, RectangleF bounds, Pen star_pen, Brush star_brush)
{
// See if num_points is null.
int number_of_points;
if (num_points.HasValue)
{
number_of_points = num_points.Value;
}
else
{
number_of_points = 5;
}

// Make room for the points.
PointF[] points = new PointF[2 * number_of_points];

double rx1 = bounds.Width / 2;
double ry1 = bounds.Height / 2;
double rx2 = rx1 * 0.5;
double ry2 = ry1 * 0.5;
double cx = bounds.X + rx1;
double cy = bounds.Y + ry1;

// Start at the top.
double theta = -Math.PI / 2;
double dtheta = Math.PI / number_of_points;
for (int i = 0; i < 2 * number_of_points; i += 2)
{
points[i] = new PointF(
(float)(cx + rx1 * Math.Cos(theta)),
(float)(cy + ry1 * Math.Sin(theta)));
theta += dtheta;

points[i + 1] = new PointF(
(float)(cx + rx2 * Math.Cos(theta)),
(float)(cy + ry2 * Math.Sin(theta)));
theta += dtheta;
}

// Fill the star.
if (star_brush != null) gr.FillPolygon(star_brush, points);

// Draw the star.
if (star_pen == null) star_pen = Pens.Black;
gr.DrawPolygon(star_pen, points);
}

The method checks whether num_points has a value and sets the value number_of_points to either that value if it exists or the default value of 5 otherwise. The code then creates an array of points representing the star's corners. (For details, see Draw a non-intersecting star in C#.)

Next the code checks the star_brush parameter and fills the star if the brush isn't null.

It then checks the star_pen parameter. If star_pen is null, the program sets it to the stock black pen. Finally the code draws the star using the pen.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.