ananoid 1.1.0

Edit this page

How-To: Create a Default NanoId

A simple example

The most common use-case for this library is to generate an new identifier, based on sensible defaults (21 random characters from a URL-safe alphabet consisting of: letters, numbers, underscore, or hyphen). A struct representing such an identifier can be generated as follows:

F#
let nanoId = NanoId.ofDefaults ()

printfn $"%s{nameof nanoId}, as string: %s{string nanoId}"
printfn $"%s{nameof nanoId}, length: %i{nanoId.Length}"
VB
Dim nanoId = NanoId.NewId()

WriteLine($"{NameOf(nanoId)}, as string: {nanoId.ToString()})"
WriteLine($"{NameOf(nanoId)}, length: {nanoId.Length})"
C#
var nanoId = NanoId.NewId();

WriteLine($"{nameof(nanoId)}, as string: {nanoId.ToString()})";
WriteLine($"{nameof(nanoId)}, length: {nanoId.Length})";
OUT
> dotnet fsi ~/scratches/nanoiddefault.fsx

nano identifier as string: 6aWPM2MNoB_xnAt9ZCyL0
nano identifier length: 21

The zeroed instance

NanoId is actually a value type. As such is has a "zero" representation -- the empty identifier. This is a single, special instance of a NanoId that has a length of zero (0) and produces an empty string (when cast). The following example shows different ways of creating and working with empty identifiers:

F#
let zeroedId = NanoId()
// ⮝⮝⮝ Identical! ⮟⮟⮟
let emptyId = NanoId.Empty

printfn $"%s{nameof zeroedId}, length: %i{NanoId.length zeroedId}"
printfn $"%s{nameof emptyId}, length: %i{NanoId.length emptyId}"
VB
Dim zeroedId As New NanoId()
' ⮝⮝⮝ Identical! ⮟⮟⮟
Dim emptyId = NanoId.Empty

WriteLine($"{NameOf(zeroedId)}, length: {zeroedId.Length}")
WriteLine($"{NameOf(emptyId)}, length: {emptyId.Length}")
C#
NanoId zeroedId = new ();
// ⮝⮝⮝ Identical! ⮟⮟⮟
var emptyId = NanoId.Empty;

WriteLine($"{nameof(zeroedId)}, length: {zeroedId.Length}");
WriteLine($"{nameof(emptyId)}, length: {emptyId.Length}");
OUT
> dotnet fsi ~/scratches/nanoiddefault.fsx

zeroedId, length: 0
emptyId, length: 0

Further Reading

Copyright

The library is available under the Mozilla Public License, Version 2.0. For more information see the project's License file.

val nanoId: obj
val printfn: format: Printf.TextWriterFormat<'T> -> 'T
val nameof: 'T -> string