Use null to simulate optional parameters in C#


This example shows how you can use null to simulate optional parameters in older versions of C#.

The example Use overloaded methods to simulate optional parameters in C# shows 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 pen, Brush 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 (brush != null) gr.FillPolygon(brush, points);

    // Draw the diamond.
    if (pen != null) gr.DrawPolygon(pen, points);

The method creates the points it needs to draw the diamond and then checks its parameters. If the brush isn’t null, the code fills the diamond. If the pen isn’t null, the code draws the diamond’s outline.

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 those data types. In contrast, an int is a value type, so a parameter with type int cannot take the value null. In my next post, I’ll explain how to use nullable types to work around this restriction. (Although it may be easier to upgrade to a newer version of C# or to use overloaded methods as described in the previous entry).

Download Example   Follow me on Twitter   RSS feed

This entry was posted in OOP, syntax and tagged , , , , , , , , , , . Bookmark the permalink.

1 Response to Use null to simulate optional parameters in C#

  1. Pingback: Use nullable parameters in C# -

Comments are closed.