Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do optional parameters in C# 4.0 require compile-time constants?

Also is there a way to use run-time values for optional method parameters?

like image 692
Joan Venge Avatar asked Mar 18 '11 00:03

Joan Venge


People also ask

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.

Does C allow optional parameters?

Optional arguments are generally not allowed in C (but they exist in C++ and in Ocaml, etc...). The only exception is variadic functions (like printf ).

What is the use of optional parameters in C#?

Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates. When you use named and optional arguments, the arguments are evaluated in the order in which they appear in the argument list, not the parameter list.

Why are optional parameters added Mcq?

Developers can use the optional parameter to declare parameters in function optional so that the requirement to pass the value to optional parameters gets eliminated.


2 Answers

Optional parameters are required to be constants because they are written out as values of an attribute. Hence they inherit all of the restrictions that an attribute value has.

There is no way to directly encode a runtime value. However you can get close with the following pattern

public void MyApi(SomeType type = null) {
  type = type ?? new SomeType();
  ...
}
like image 163
JaredPar Avatar answered Oct 12 '22 11:10

JaredPar


Optional parameters are compiled into the assembly and as such (just like anything that is designated as const) they must be a compile-time constant.

And no, you cannot use execution-time values as optional parameters.

like image 32
Andrew Hare Avatar answered Oct 12 '22 09:10

Andrew Hare