Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't Point and Rectangle be used as optional parameters?

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) {}
    
like image 952
Robin Rodricks Avatar asked Sep 02 '12 11:09

Robin Rodricks


People also ask

Can parameters be optional?

The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition.

How do you set a parameter as optional?

We can implement optional parameters by assigning a default value for the parameters. This is the easiest and simple way to make the methods parameter optional. In this way, we just need to define the optional parameter with its default values when we create our methods.

Why are optional parameters are added?

Optional Parameters are parameters that can be specified, but are not required. This allows for functions that are more customizable, without requiring parameters that many users will not need.

What is known as optional parameter from the given?

An optional parameter in Java, as the name implies, refers simply to a parameter that may be optional for a method invocation! It describes the possibility to call a method without specifying some of the arguments used in its definition! Parameters are variables that you can pass to a method or a function!


1 Answers

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);
    }
}
like image 95
Adam Avatar answered Sep 20 '22 10:09

Adam