Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can CodeDom create optional arguments when generating a c# method?

Tags:

c#

.net

codedom

Can CodeDom create optional arguments when generating a c# method and provide a default value?

For example:

public void ExampleMethod(int required
                          , string optionalstr = "default string"
                          , int optionalint = 10)

Solution I've found a simple workaround for this, you can just put the default value in as part of the argument name:

CodeParameterDeclarationExpression(typeof(int), "optionalint = 5");

This works for me b/c I'm only using the CodeDom to produce C# code. It won't work if you need to support multiple languages.

like image 230
NotDan Avatar asked Jan 19 '11 21:01

NotDan


People also ask

Does C# support optional parameters?

Use optional parameters in C#Optional parameters in the C# programming language allow you to specify arguments in a method signature that the caller of the method is free to omit. In other words, while you must specify values for required parameters, you might choose not to specify values for optional parameters.


1 Answers

Yes.

Add the [Optional] attribute.
To specify the default value, add the [[DefaultParameterValue(...)] attribute. (If the default value is 0 or null, this attribute can be omitted.

I wrote a more detailed explanation on my blog.

like image 83
SLaks Avatar answered Sep 28 '22 07:09

SLaks