Overview
Similarities
Modules and namespaces allow you to:
Organize code into zones of related functionality
Avoid name collisions
Differences
.NET equivalent
namespace
static class
Type
Top-level
Top-level or local
Contains
Modules, Types
Idem + Values, Functions
Annotable
ā No
ā Yes
Scope: Namespaces > Files > Modules
Use a module or a namespace
Either qualify the elements individually
Or import everything with the
open
keywordplaced anywhere before the usage, at the top recommended
open Name.Space
ā” CāÆusing Name.Space
open My.Module
ā” CāÆusing static My.Module
Imports order
ā ļø Warning: the order of the imports is taken into account, from top to bottom.
This allows shadowing (see below).
As a result, reordering imports in an existing file may cause compilation to fail!
So, although it's advisable to have imports sorted alphabetically, this isn't always possible. It is therefore advisable to indicate this in the code by means of a comment.
Shadowing at import
Imports are done without name conflicts but need disambiguation:
Modules and static classes are merged ā
Types and functions are shadowed ā - Last-imported-wins mode: see example below - Import order matters
ā Recommendation
Shadowing is more likely to happen with common names such as add
in the previous example, or map
, filter
... from the List
, Seq
... modules.
Qualification is recommended in this case, and it can be made mandatory by decorating the module with [<RequireQualifiedAccess>]
š
Keyword global
global
Because of Shadowing, we may come across cases where we can't import the right namespace. For example, having done open FsCheck
and referenced the FsCheck.Xunit
library, when you do open Xunit
, we don't import the Xunit
namespace from the Xunit
library but the FsCheck.Xunit
namespace!
š” We resolve fix issue by doing open global.Xunit
.
Last updated
Was this helpful?