Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continued "Is there an equivalent of C#'s nameof(..) in F#?"

Tags:

f#

nameof

With reference to Is there an equivalent of C#'s nameof(..) in F#?

how can the nameof function used or extended for the following case?

let nameof (q:Expr<_>) = 
    match q with 
    | Patterns.Let(_, _, DerivedPatterns.Lambdas(_, Patterns.Call(_, mi, _))) -> mi.Name
    | Patterns.PropertyGet(_, mi, _) -> mi.Name
    | DerivedPatterns.Lambdas(_, Patterns.Call(_, mi, _)) -> mi.Name
    | _ -> failwith "Unexpected format"

let any<'R> : 'R = failwith "!"

let s = _nameof <@ System.Char.IsControl @> //OK

type A<'a>() = 
    static member MethodWith2Pars(guid:Guid, str:string) = ""
    static member MethodWith2Pars(guid:Guid, ba:byte[]) = ""

let s1 = nameof <@ A<_>.MethodWith2Pars @> //Error  FS0503  A member or object constructor 'MethodWith2Pars' taking 1 arguments is not accessible from this code location. All accessible versions of method 'MethodWith2Pars' take 2 arguments
let s2 = nameof <@ A<_>.MethodWith2Pars : Guid * string -> string @> //Same error

The compiler gives the following error:

Error FS0503 A member or object constructor 'MethodWith2Pars' taking 1 arguments is not accessible from this code location. All accessible versions of method 'MethodWith2Pars' take 2 arguments

like image 861
Franco Tiveron Avatar asked Dec 30 '22 18:12

Franco Tiveron


2 Answers

The answer you linked is a bit outdated. F# 5.0 (released just recently) offers the true nameof feature. See the announcement: https://devblogs.microsoft.com/dotnet/announcing-f-4-7/#nameof

This feature also existed in preview since F# 4.7: https://devblogs.microsoft.com/dotnet/announcing-f-4-7/#nameof

like image 124
Fyodor Soikin Avatar answered Jan 10 '23 07:01

Fyodor Soikin


You can write your code like this:

open System

type A() = 
    static member MethodWith2Pars(guid:Guid, str:string) = ""
    static member MethodWith2Pars(guid:Guid, ba:byte[]) = ""

let s1 = nameof (A.MethodWith2Pars : Guid * byte[] -> string)
let s2 = nameof (A.MethodWith2Pars : Guid * string -> string)

The type annotation is needed due to overloading. Not sure why there is a generic type parameter on the class declaration, but it's not used anywhere so I just removed it.

like image 35
Phillip Carter Avatar answered Jan 10 '23 08:01

Phillip Carter