'Is there any alternative to C#'s public member initializer for F#?
in C#, public members can be assigned in place of constructor call:
options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = "preferred_username" }
To achieve the same effect, I wrote the following F# code:
options.TokenValidationParameters <- (new TokenValidationParameters()) |> fun it -> (it.NameClaimType <- "preferred_username"; it)
However it doesn't look nice at all.
Is there any better way to do this? An ideal solution may be a function like apply in kotlin?
Any help is appreciated.
Solution 1:[1]
As mentioned in the comments, you can specify parameters using an object initialization syntax:
options.TokenValidationParameters <-
new TokenValidationParameters( NameClaimType = "preferred_username")
The above is definitely the best way to do this. But even if you needed more complex logic, it is not necessary to construct objects on one line using an awkward piping and fun construct. There is nothing wrong with just defining a local variable:
let tokParams = new TokenValidationParameters()
tokParams.NameClaimType <- "preferred_username"
options.TokenValidationParameters <- tokParams
If you wanted to limit the scope of the tokParams variable, you could do something like this:
options.TokenValidationParameters <-
let tokParams = new TokenValidationParameters()
tokParams.NameClaimType <- "preferred_username"
tokParams
This also works, because an F# block is treated as an expression. You do not need to do this in this particular case, but it may be good to know - and it lets you avoid awkward piping.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
