You are previewing Programming F#.

Programming F#

Cover of Programming F# by Chris Smith Published by O'Reilly Media, Inc.
O'Reilly logo

Understanding System.Object

.NET offers a rich type system that can check the identity of objects and guarantee type safety at runtime. By keeping track of the type of an object, the .NET runtime can ensure that square pegs aren’t put into round holes.

To achieve this notion of object identity, everything from integers to strings to discriminated unions are instances of System.Object, abbreviated in F# by obj. An instance of System.Object isn’t useful on its own because it doesn’t have any customizations. However, it is important to know the methods available on System.Object because they are available on every object you encounter in .NET.

Common Methods

Each instance of System.Object comes with several methods that can be overwritten or customized. For custom F# types (discriminated unions and records), some of these methods are overwritten by the F# compiler.


ToString produces a human-readable string representation of the object. In F# this is the value the printf format specifier %A or %O displays to the console. No formal guidelines exist for what this should return, though the result from ToString should be adequate to differentiate the object from others, as well as an aid in debugging. The default value is the full name of the class itself.

The following example defines a type PunctionMark and provides an implementation of its ToString method. Without overriding ToString, the default message would look something like FSI_0002+PunctuationMark:

> // Overriding ToString type ...

The best content for your career. Discover unlimited learning on demand for around $1/day.