Argon.Extensions.Types 8.5.0
Argon.Extensions.Types
Utility types to improve .NET development.
📦 Installation
dotnet add package Argon.Extensions.Types
✨ Features
Optional<T>
A type to safely represent optional values, avoiding errors related to null values.
Characteristics:
- Implicit conversion from and to the underlying type
- Full pattern matching support
- Safe handling of missing values
- Type-safe alternative to nullable values
🚀 Usage
Creating an optional value
using Argon.Extensions.Types;
// With a value
Optional<string> name = new Optional<string>("John");
Optional<string> name2 = "John"; // Implicit conversion
// Without a value
Optional<string> empty = new Optional<string>();
Checking and accessing the value
Optional<string> name = "John";
if (name.HasValue)
{
Console.WriteLine($"Name: {name.Value}");
}
// Implicit conversion (throws InvalidOperationException if empty)
string actualName = name;
Practical example
public class UserService
{
public Optional<User> FindUserById(int id)
{
var user = _repository.GetById(id);
if (user == null)
return new Optional<User>(); // Returns an empty Optional
return user; // Implicit conversion
}
}
// Usage
var userOptional = userService.FindUserById(42);
if (userOptional.HasValue)
{
Console.WriteLine($"User found: {userOptional.Value.Name}");
}
else
{
Console.WriteLine("User not found");
}
📝 API Reference
Properties
Value: Gets the encapsulated value. ThrowsInvalidOperationExceptionifHasValueisfalse.HasValue: Indicates whether the instance contains a value.
Constructors
Optional(): Creates an empty instance.Optional(TValue value): Creates an instance with the specified value.
Implicit conversions
TValue→Optional<TValue>: Converts a value to Optional.Optional<TValue>→TValue: Extracts the value (throws an exception if empty).
🔗 Links
No packages depend on Argon.Extensions.Types.
.NET 8.0
- No dependencies.