Is it possible to define a static class that contains overloadable members in F#? let
module bindings cannot be overloaded, even though they are compiled into static static members in static classes.
type
declerations can contain static members, but I don't know if the type itself can be made static.
My current solution is to define a type
with a private constructor and just use that. I'm wondering if there is a way I can define a static type as I want.
A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.
What is a static method? Static methods in Python are extremely similar to python class level methods, the difference being that a static method is bound to a class rather than the objects for that class. This means that a static method can be called without an object for that class.
A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields. For example, in the . NET Class Library, the static System.
As Robert Jeppeson pointed out, a "static class" in C# is just short-hand for making a class that cannot be instantiated or inherited from, and has only static members. Here's how you can accomplish exactly that in F#:
[<AbstractClass; Sealed>] type MyStaticClass private () = static member SomeStaticMethod(a, b, c) = (a + b + c) static member SomeStaticMethod(a, b, c, d) = (a + b + c + d)
This might be a little bit of overkill, as both the AbstractClass
and the private constructor will prevent you from creating an instance of the class, however, this is what C# static classes do - they are compiled to an abstract class with a private constructor. The Sealed
attribute prevents you from inheriting from this class.
This technique won't cause a compiler error if you add instance methods the way it would in C#, but from a caller's point of view there is no difference.
This is explained in The F# Component Design Guidelines.
[<AbstractClass; Sealed>] type Demo = static member World = "World" static member Hello() = Demo.Hello(Demo.World) static member Hello(name: string) = sprintf "Hello %s!" name let s1 = Demo.Hello() let s2 = Demo.Hello("F#")
It is still possible to define instance methods, but you can't instantiate the class when there is no constructor available.
edit Jan 2021 : See the comment from Abel, and the linked issue. Joel Mueller's answer seems to be the best advice so far, but things will perhaps change in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With