[<DefaultParameterValue>] is ignored in F#-authored code
See original GitHub issueOriginally opened at CodePlex latkin
Reported by Tomas P via fsbugs.
The F# compiler ignores the [<DefaultParameterValue>]
attribute. For example, the following always prints null when called by C# code (calling from F# without specifying message is not supported):
open System
open System.Runtime.InteropServices
type C =
static member Foo([<Optional; DefaultParameterValue("Hello world")>] message) =
printfn "%s" message
Analysis from Don:
This is correct, in F# 3.0 and F# 3.1 DefaultParameterValue is ignored for F#-authored code, both by F# consumers and .NET consumers of F# code.
The relevant code is infos.fs GetParamAttribs, where we look for OptionalArgumentAttribute and not DefaultParameterValueAttribute:
| FSMeth(g,_,vref,_) ->
vref
|> ArgInfosOfMember g
|> List.mapSquared (fun (ty,argInfo) ->
let isParamArrayArg = HasFSharpAttribute g g.attrib_ParamArrayAttribute argInfo.Attribs
let isOutArg = HasFSharpAttribute g g.attrib_OutAttribute argInfo.Attribs && isByrefTy g ty
let isOptArg = HasFSharpAttribute g g.attrib_OptionalArgumentAttribute argInfo.Attribs
// Note: can't specify caller-side default arguments in F#, by design (default is specified on the callee-side)
let optArgInfo = if isOptArg then CalleeSide else NotOptional
(isParamArrayArg,isOutArg,optArgInfo))
Likewise in ilxgen.fs, we never generate a “Default” value in the Abstract IL metadata for an F# assembly. There is even a “TODO” marker there…
let param =
{ Name=nmOpt;
Type= ilArgTy;
Default=None; (* REVIEW: support "default" attributes *)
Marshal=Marshal;
IsIn=inFlag;
IsOut=outFlag;
IsOptional=optionalFlag;
CustomAttrs= mkILCustomAttrs (GenAttrs cenv eenv attribs) }
We should fix this.
Issue Analytics
- State:
- Created 9 years ago
- Comments:17 (11 by maintainers)
Top Results From Across the Web
c# method with default parameter value does not generate ...
Any code that I recompiled was able to compile and execute without any problems, even without the parameter like this:
Read more >Named and Optional Arguments - C# Programming Guide
Named arguments in C# specify arguments by name, not position. Optional arguments can be omitted.
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@dsyme, @cartermp Thanks, and sorry again for off-topic.
Yes, you will need to use F# 4.1. You can use the FSharp.Compiler.Tools package in your current projects, or move to Visual Studio 2017.