Before you start
- Check which version of
DotNextthe project references (.csprojorDirectory.Packages.props). This skill describes 6.x. For older versions, verify each member you use against the XML docs/IntelliSense of the referenced version. - The types below are in several namespaces. Each type is given with its namespace
(e.g.
DotNext.Diagnostics.Timestamp). Add theusingfor that namespace and use the short type name in code. - If this skill doesn't cover what you need (API details, more examples), find the relevant article in the documentation index: https://dotnet.github.io/dotNext/llms.txt
Use Cases
Monadic Types
- Consider
DotNext.Optional<T>monad to express value absence in a unified way for both reference and value types.- This type is compatible with
System.Text.Jsonserialization viaDotNext.Text.Json.OptionalConverterFactoryconverter. UseDotNext.Text.Json.OptionalConverter<T>explicitly for AOT and self-contained deployment. - To omit the field from JSON when the value is undefined (equivalent to undefined in JavaScript, useful for PATCH DTOs), the property needs both attributes. The default value of
Optional<T>is undefined, soWhenWritingDefaultdrops it. WithoutJsonIgnore, the converter throwsInvalidOperationExceptionfor undefined value.[JsonConverter(typeof(OptionalConverterFactory))] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public Optional<int> IntegerValue { get; set; } - Optional with null value (
IsNull) is not undefined. It is written as JSONnull. AsyncEnumerable.FlattenandCollection.FlatteninDotNext.Collections.Genericextension methods can be used to filter out the empty values in a sequence.
- This type is compatible with
- Consider
DotNext.Result<T>monad to express error or successful result as a return type in synchronous methods- Avoid
Task<Result<T>>orResult<Task<T>>wrapping.Task<T>in asynchronous code provides the same semantics: it can represent error or task result on success
- Avoid
Diagnostics
- Consider
DotNext.Diagnostics.Timestampvalue type for time measurements instead ofSystem.Diagnostics.Stopwatchclass or rawlongvalues returned byStopwatch.GetTimestamp().- It can be stored in a field and passed around:
Elapsed,ElapsedMillisecondsandElapsedTicksgive the time passed since the timestamp was taken. - It supports comparison operators, and
timestamp + timeoutproduces a deadline that can be checked withIsPastorIsFuture. - The constructor and elapsed time methods (
GetElapsedTime,GetElapsedTicks,GetElapsedMilliseconds) have overloads that acceptSystem.TimeProvider, so the code can be tested with a fake time provider.Elapsed*,IsPastandIsFutureproperties always use the system clock.
- It can be stored in a field and passed around:
Reflection
- Consider
DotNext.Reflection.EnumTypeextensions to obtain a custom attribute for the enum field. This approach is AOT compatible.
Console Application
- If the app doesn't use the generic host (
Microsoft.Extensions.Hosting),DotNext.Hosting.ConsoleLifetimeTokenSourcecan be used to get cancellation token associated with the console application lifetime. It gets canceled onSIGINT(Ctrl+C),SIGQUITorSIGTERMsignal (SIGTERMis sent bydocker stopand Kubernetes).- Not supported on Android, iOS, tvOS and browser. Check
ConsoleLifetimeTokenSource.IsSupportedin cross-platform code. - Declare it with
using.Disposeremoves the signal handlers.
- Not supported on Android, iOS, tvOS and browser. Check
Collections
- Consider
DotNext.Collections.Specialized.TypeMap<TValue>orDotNext.Collections.Specialized.ConcurrentTypeMap<TValue>classes to replaceSystem.Collections.Generic.Dictionary<System.Type, TValue>when keys are known at compile time. These specialized maps provide O(1) lookup.- The key is a generic type argument, e.g.
map.Set<string>(value),map.TryGetValue<string>(out var value). ASystem.Typeinstance obtained at runtime cannot be used as a key. TypeMap<TValue>is not thread-safe. UseConcurrentTypeMap<TValue>for concurrent access.
- The key is a generic type argument, e.g.
Misc
- Use
DotNext.LocalReference<T>orDotNext.ReadOnlyLocalReference<T>if you need a ref field pointing to a ref struct (C# doesn't allow ref fields of ref struct type), or you need to represent managed pointer in generic context. - Use
DotNext.BasicExtensions.UserDataextension property to attach arbitrary values to the objects instead of maintainingSystem.Runtime.CompilerServices.ConditionalWeakTable<TKey, TValue>manually.