Use null to simulate optional parameters in C#

The example Use overloaded methods to simulate optional parameters in C# explains how you can use overloaded methods to simulate optional parameters. Another approach is to pass null into a method if you want to use a default value for that parameter. The method can then check the parameter and set it to a default value if it is null.

The following code shows a DrawDiamond method that can take a null Pen or Brush parameter.

// Draw a diamond, optionally filling it.
private void DrawDiamond(Graphics gr, RectangleF bounds, Pen diamond_pen, Brush diamond_brush)
{
// Make the diamond's points.
PointF[] points = new PointF[4];
float xmid = (bounds.Left + bounds.Right) / 2;
float ymid = (bounds.Top + bounds.Bottom) / 2;
points[0] = new PointF(xmid, bounds.Top);
points[1] = new PointF(bounds.Right, ymid);
points[2] = new PointF(xmid, bounds.Bottom);
points[3] = new PointF(bounds.Left, ymid);

// Fill the diamond.
if (diamond_brush != null) gr.FillPolygon(diamond_brush, points);

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

The method creates the points needed to draw the diamond and then checks these parameters. It only fills the diamond if the Brush is not null. If the Pen is null, it sets the Pen parameter to the stock black pen and before it draws the diamond.

Note that this technique only works for data types that can be null. For example, Pen and Brush are both classes so null represents a valid value for parameters with those data types. In contrast, an int is a value type so a parameter with type int cannot take the value null. In tomorrow's entry I'll explain how to use nullable types to work around this restriction, although in many cases it may be easier to use overloaded methods as described in the previous entry.

   

 

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.