Why isn’t there a protected access modifier in F#?

The protected modifier can be quite problematic in F#, because you often need to call members from a lambda expression. However, when you do that, you no longer access the method from within the class. This also causes confusion when using protected members declared in C# (see for example this SO question). If you could declare a protected member, the following code could be surprising:

type Base() = 
  protected member x.Test(a) = a > 10

type Inherited() = 
  inherit Base()
  member x.Filter(list) =
    list |> List.filter (fun a -> x.Test(a))

This code wouldn’t work, because you’re calling Test from a lambda function (which is a different object than the current instance of Test), so the code wouldn’t work. I think this is tha main reason for not supporting the protected modifier in F#.

In F# you typically use implementation inheritance (that is, inheriting from a base class) much less frequently than in C#, so you shouldn’t need protected as often. Instead, it is usually preferred to use interfaces (in the object-oriented F# code) and higher-order functions (in the functional code). However, it is difficult to say how to avoid the need for protected in general (other than by avoiding implementation inheritance). Do you have some specific example which motivated your question?

Leave a Comment