Yemi Bedu
Yemi Bedu

Reputation: 312

System.String extension member in F# for Chars

I have gone through the documentation and source code for System.String. I can see that the default indexer is defined with this[int index] and that the alias "Chars" is used. I want to extend it by writing the below code.

type System.String with
    member self.Chars (boolean:bool) = if boolean then self.[0] else self.[1]

printfn "%c" ("abc".[false])
printfn "%c" ("abc".Chars(false))

The reason why is because I have seen other articles and code snippets pointing to the idea that I would have this ability. I am now trying to test it out. I also noticed that System.String is defined as Sealed.

[<Sealed>]

I have been doing many searches and looking at sites like fssnip.net and Tomas P's articles and here on Stackoverflow. What am I missing?

Upvotes: 2

Views: 120

Answers (1)

Yemi Bedu
Yemi Bedu

Reputation: 312

The reason why this is not working is because Chars is an alias to a property and not a method itself. Extension methods seem to not be possible on properties.

Even though it is a get with a parameter, there would had to of been a generic version created and that would likely need to point to a method that I could create my constrained version from. @Ringil led me in the right direction. Thank you. Good day.

Upvotes: 2

Related Questions