5

I'm trying to pass an optional argument to a geometry function, called offset, which may or may not be specified, but C# doesn't allow me to do any of the following. Is there a way to accomplish this?

  • Null as default

    Error: A value of type '' cannot be used as a default parameter because there are no standard conversions to type 'System.Drawing.Point'

    public void LayoutRelative(.... Point offset = null) {} 
  • Empty as default

    Error: Default parameter value for 'offset' must be a compile-time constant

    public void LayoutRelative(.... Point offset = Point.Empty) {} 

1 Answer 1

16

If your default value doesn't require any special initialization, you don't need to use a nullable type or create different overloads. You can use the default keyword:

public void LayoutRelative(.... Point offset = default(Point)) {} 

If you want to use a nullable type instead:

public void LayoutRelative(.... Point? offset = null) { if (offset.HasValue) { DoSomethingWith(offset.Value); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.