Maybe monad implementation with LINQ support for functional programming in C#. Provides type-safe null handling, eliminates null reference exceptions, and enables functional composition. Essential for functional programming patterns and safe value handling.
$ dotnet add package CSharpEssentials.MaybeCSharpEssentials is a comprehensive library that enhances C#'s functional programming capabilities. It provides a robust set of tools and utilities designed to make your C# applications more maintainable, testable, and aligned with functional programming principles.
Maybe<T> - Safe handling of nullable values:
Maybe<string> someValue = Maybe.From("Hello");
Maybe<string> noValue = Maybe.None;
// LINQ support
var result = someValue
.Select(str => str.ToUpper())
.Where(str => str.Length > 5);Result<T> - Functional approach to error handling:
public Result<User> CreateUser(UserDto dto)
{
if (string.IsNullOrEmpty(dto.Email))
return Error.Validation("EMAIL_REQUIRED", "Email is required");
var user = new User(dto);
return Result<User>.Success(user);
}RuleEngine - Complex business rule management:
public class EmailValidationRule : IRule<string>
{
public Result Evaluate(string email, CancellationToken cancellationToken = default)
{
return email.Contains("@")
? Result.Success()
: Error.Validation("INVALID_EMAIL", "Email must contain @");
}
}Error - Structured error handling:
var error = Error.Validation(
code: "USER_INVALID_AGE",
description: "User age must be greater than 18"
);Any<T0,T1,...> - Type-safe union types:
public Any<string, int> ParseOrKeepAsString(string input)
{
return int.TryParse(input, out int number)
? number
: input;
}EntityFrameworkCore - Enhanced EF Core support with functional patterns:
public class Product : SoftDeletableEntityBase<Guid>
{
private Product(string name, decimal price)
{
Id = Guid.NewGuid();
Name = name;
Price = price;
}
public static Product Create(string name, decimal price)
{
var product = new Product(name, price);
product.Raise(new ProductCreatedEvent(product.Id));
return product;
}
}
// Configure in DbContext
public void Configure(EntityTypeBuilder<Product> builder)
{
builder.SoftDeletableEntityBaseGuidIdMap();
builder.OptimisticConcurrencyVersionMap();
}DateTimeProvider - Testable datetime handling:
public class OrderService
{
private readonly IDateTimeProvider _dateTimeProvider;
public Order CreateOrder()
{
return new Order { CreatedAt = _dateTimeProvider.UtcNow };
}
}JSON - Enhanced JSON capabilities:
var options = EnhancedJsonSerializerOptions.DefaultOptions;
string json = myObject.ConvertToJson(options);Extensions - Useful extension methods:
// String transformations
"helloWorld".ToPascalCase(); // => "HelloWorld"
"hello_world".ToCamelCase(); // => "helloWorld"
// Collection operations
var randomItem = list.GetRandomItem();RequestResponseLogging - Comprehensive HTTP traffic monitoring:
public void Configure(IApplicationBuilder app)
{
app.AddRequestResponseLogging(opt =>
{
// Configure logging options
var loggingOptions = LoggingOptions.CreateAllFields();
loggingOptions.HeaderKeys.Add("X-Correlation-Id");
// Use the configured logger
opt.UseLogger(app.Services.GetRequiredService<ILoggerFactory>(), loggingOptions);
});
}AspNetCore - Enhanced ASP.NET Core capabilities:
public void ConfigureServices(IServiceCollection services)
{
services
.AddExceptionHandler<GlobalExceptionHandler>()
.ConfigureModelValidatorResponse()
.ConfigureSystemTextJson()
.AddEnhancedProblemDetails()
.AddAndConfigureApiVersioning()
.AddSwagger<DefaultConfigureSwaggerOptions>(
SecuritySchemes.JwtBearerTokenSecurity,
Assembly.GetExecutingAssembly()
);
}
public void Configure(IApplicationBuilder app)
{
app.UseVersionableSwagger();
app.UseExceptionHandler();
app.UseStatusCodePages();
}GcpSecretManager - Seamless integration with Google Cloud Secret Manager:
// Basic configuration in Program.cs or Startup.cs
builder.Configuration.AddGcpSecretManager();
// Advanced configuration with options
builder.Configuration.AddGcpSecretManager(options =>
{
options.CredentialsPath = "/path/to/credentials.json";
options.AddProject(new ProjectSecretConfiguration
{
ProjectId = "your-gcp-project-id",
Region = "europe-west1",
PrefixFilters = ["app_", "service_"],
SecretIds = ["specific-secret1"],
RawSecretIds = ["config-json"], // Skip JSON parsing for these secrets
RawSecretPrefixes = ["raw_"] // Skip JSON parsing for secrets with these prefixes
});
});
// Configuration in appsettings.json
{
"GoogleSecretManager": {
"Projects": [
{
"ProjectId": "your-gcp-project-id",
"Region": "europe-west1",
"PrefixFilters": ["app_"],
"SecretIds": ["specific-secret1"],
"RawSecretIds": ["config-json"],
"RawSecretPrefixes": ["raw_"]
}
]
}
}Key features:
Choose the packages you need:
dotnet add package CSharpEssentialsdotnet add package CSharpEssentials.Coredotnet add package CSharpEssentials.Maybedotnet add package CSharpEssentials.Resultsdotnet add package CSharpEssentials.Anydotnet add package CSharpEssentials.Errorsdotnet add package CSharpEssentials.Rulesdotnet add package CSharpEssentials.Entitydotnet add package CSharpEssentials.EntityFrameworkCoredotnet add package CSharpEssentials.AspNetCoredotnet add package CSharpEssentials.Jsondotnet add package CSharpEssentials.Timedotnet add package CSharpEssentials.Clonedotnet add package CSharpEssentials.Enumsdotnet add package CSharpEssentials.RequestResponseLoggingdotnet add package CSharpEssentials.GcpSecretManagerYou can also install the packages directly from the NuGet Gallery.
Import the required namespaces based on your needs:
// Core functionality
using CSharpEssentials;
// Entity Framework Core integration
using CSharpEssentials.EntityFrameworkCore;
// ASP.NET Core integration
using CSharpEssentials.AspNetCore;
// Request Response Logging
using CSharpEssentials.RequestResponseLogging;Result<T> for operations that can failMaybe<T> over null values for optional valuesError types for domain errorsResult<T>Error.Validation() for input validation failuresError.NotFound() for resource not found scenariosError.Unauthorized() for authentication/authorization failuresEntityBase for domain entitiesRuleEngine for complex validationsIRule<T> for reusable business rulesAny<T0,T1> for type-safe union typesSoftDeletableEntityBase for soft delete supportDateTimeProvider for time-dependent testsResult<T> for predictable error scenariosThis repository includes an optimized build and publish script that handles all CSharpEssentials packages with proper dependency order management.
Script: build-and-publish-nugets.sh - Cross-platform script for Linux, macOS, and Windows (Git Bash/WSL)
--parallel)# Basic build and package (no publishing)
./build-and-publish-nugets.sh
# Build, package and publish to NuGet.org
./build-and-publish-nugets.sh YOUR_API_KEY
# Use parallel processing for faster builds
./build-and-publish-nugets.sh --parallel YOUR_API_KEY
# Preview what would happen (dry run)
./build-and-publish-nugets.sh --dry-run --verbose YOUR_API_KEY
# Skip build and only package existing builds
./build-and-publish-nugets.sh --skip-build YOUR_API_KEY
# Force package even with warnings (for NU5017 errors)
./build-and-publish-nugets.sh --force-pack YOUR_API_KEY
# Show help
./build-and-publish-nugets.sh --help--parallel: Enable parallel processing for same-level packages--verbose: Enable detailed logging--dry-run: Show what would be executed without doing it--skip-build: Skip build step and only package/publish--force-pack: Force packaging even with NU5017 warnings--help, -h: Show usage information# Clone the repository
git clone https://github.com/senrecep/CSharpEssentials.git
cd CSharpEssentials
# Build all packages
./build-and-publish-nugets.sh
# Run tests (if available)
dotnet test
# Build and publish with API key
./build-and-publish-nugets.sh --parallel YOUR_NUGET_API_KEYWe welcome contributions! Please see our Contributing Guide for details.
This project is licensed under the MIT License - see the LICENSE file for details.
This library was inspired by and builds upon the work of several excellent open-source projects:
Special thanks to all contributors who have helped shape this library and to the maintainers of these inspiring projects.
For support, please open an issue in the GitHub repository or contact the maintainers.
Take a look at senrecep.Aspire, a modern microservices template built with .NET Aspire 9.0. The template provides a robust foundation for building scalable, maintainable, and cloud-ready microservices applications. Check out the GitHub repository for more details.