### Allocate Pooled Memory with MemoryOwner Source: https://context7.com/communitytoolkit/dotnet/llms.txt Use MemoryOwner.Allocate to get a pooled memory buffer. Access it as a Span for efficient operations or as Memory for async operations. ```csharp using CommunityToolkit.HighPerformance.Buffers; public class BufferExamples { public void ProcessLargeData() { // Allocate from shared pool using var buffer = MemoryOwner.Allocate(1024); // Access as Span for fast operations Span span = buffer.Span; span.Fill(0xFF); // Access as Memory for async operations Memory memory = buffer.Memory; Console.WriteLine($"Buffer length: {buffer.Length}"); } public void ProcessWithClearedBuffer() { // Allocate with cleared memory using var buffer = MemoryOwner.Allocate(100, AllocationMode.Clear); // All values are zero Console.WriteLine($"First value: {buffer.Span[0]}"); // 0 } public byte[] ProcessAndSlice(int dataSize) { using var buffer = MemoryOwner.Allocate(dataSize * 2); // Fill with data buffer.Span.Fill(42); // Slice creates new owner (disposes original) using var sliced = buffer.Slice(0, dataSize); return sliced.Span.ToArray(); } public async Task ProcessAsyncData(Stream stream) { using var buffer = MemoryOwner.Allocate(4096); int bytesRead = await stream.ReadAsync(buffer.Memory); // Process the data ProcessBytes(buffer.Span.Slice(0, bytesRead)); } private void ProcessBytes(ReadOnlySpan data) { Console.WriteLine($"Processing {data.Length} bytes"); } } ``` -------------------------------- ### StringPool: Caching and Retrieving Strings Source: https://context7.com/communitytoolkit/dotnet/llms.txt Demonstrates how to use StringPool to cache and retrieve string instances, minimizing allocations. Use the shared instance for general purposes or create a custom-sized pool. Strings are cached based on their character content. ```csharp using CommunityToolkit.HighPerformance.Buffers; using System.Text; public class StringPoolExamples { public void DemonstrateStringPooling() { // Use the shared instance var pool = StringPool.Shared; // Or create a custom-sized pool var customPool = new StringPool(minimumSize: 256); // Cache a string pool.Add("frequently_used_key"); // Get or add - returns cached instance if exists ReadOnlySpan chars = "hello_world".AsSpan(); string cached1 = pool.GetOrAdd(chars); string cached2 = pool.GetOrAdd(chars); Console.WriteLine($"Same reference: {ReferenceEquals(cached1, cached2)}"); // true // From existing string string original = "test_string"; string fromPool = pool.GetOrAdd(original); // Try to get without adding if (pool.TryGet("frequently_used_key".AsSpan(), out string? found)) { Console.WriteLine($"Found: {found}"); } // Reset the pool customPool.Reset(); } public void ParseCsvWithPooling(string csvData) { var pool = StringPool.Shared; var lines = csvData.Split(' '); foreach (var line in lines) { var fields = line.Split(','); foreach (var field in fields) { // Reuse string instances for repeated values string pooled = pool.GetOrAdd(field.AsSpan().Trim()); ProcessField(pooled); } } } public string GetOrAddFromBytes(ReadOnlySpan utf8Bytes) { // Create string from encoded bytes with pooling return StringPool.Shared.GetOrAdd(utf8Bytes, Encoding.UTF8); } private void ProcessField(string field) { Console.WriteLine($"Field: {field}"); } } ``` -------------------------------- ### ArrayPoolBufferWriter: Building Byte Arrays Source: https://context7.com/communitytoolkit/dotnet/llms.txt Demonstrates using ArrayPoolBufferWriter to efficiently build a byte array by writing header, separator, and payload. The writer reuses underlying arrays from the pool, reducing allocations. ```csharp using CommunityToolkit.HighPerformance.Buffers; public class BufferWriterExamples { public byte[] BuildMessage(string header, byte[] payload) { using var writer = new ArrayPoolBufferWriter(); // Write header bytes var headerBytes = System.Text.Encoding.UTF8.GetBytes(header); writer.Write(headerBytes); // Write separator writer.GetSpan(1)[0] = (byte)':'; writer.Advance(1); // Write payload writer.Write(payload); // Get the result return writer.WrittenSpan.ToArray(); } public void StreamProcessing() { using var writer = new ArrayPoolBufferWriter(); // Add items incrementally for (int i = 0; i < 100; i++) { var span = writer.GetSpan(1); span[0] = i * 2; writer.Advance(1); } Console.WriteLine($"Written count: {writer.WrittenCount}"); // Access written data ReadOnlySpan data = writer.WrittenSpan; foreach (var item in data) { Console.Write($"{item} "); } } } ``` -------------------------------- ### RelayCommand for ICommand Implementation Source: https://context7.com/communitytoolkit/dotnet/llms.txt Implement ICommand using RelayCommand for simple delegate commands. It supports parameterless and generic versions, and includes a CanExecute delegate for conditional execution. ```csharp using CommunityToolkit.Mvvm.Input; public class CalculatorViewModel { private int total; public IRelayCommand IncrementCommand { get; } public IRelayCommand AddCommand { get; } public IRelayCommand ResetCommand { get; } public CalculatorViewModel() { // Simple command IncrementCommand = new RelayCommand(() => total++); // Command with parameter AddCommand = new RelayCommand(value => total += value); // Command with CanExecute ResetCommand = new RelayCommand( execute: () => total = 0, canExecute: () => total > 0 ); } } // Usage var vm = new CalculatorViewModel(); vm.IncrementCommand.Execute(null); // total = 1 vm.AddCommand.Execute(5); // total = 6 vm.ResetCommand.NotifyCanExecuteChanged(); // Update UI binding state ``` -------------------------------- ### AsyncRelayCommand for Async Operations with Task Tracking Source: https://context7.com/communitytoolkit/dotnet/llms.txt AsyncRelayCommand supports asynchronous operations with built-in execution tracking, cancellation, and configurable exception handling. Use it for operations that return a Task. ```csharp using CommunityToolkit.Mvvm.Input; public class DataViewModel : ObservableObject { public IAsyncRelayCommand LoadDataCommand { get; } public IAsyncRelayCommand FetchPageCommand { get; } public DataViewModel() { // Basic async command LoadDataCommand = new AsyncRelayCommand(LoadDataAsync); // Cancelable async command with options FetchPageCommand = new AsyncRelayCommand( FetchPageAsync, AsyncRelayCommandOptions.AllowConcurrentExecutions ); } private async Task LoadDataAsync() { await Task.Delay(1000); Console.WriteLine("Data loaded!"); } private async Task FetchPageAsync(int pageNumber, CancellationToken token) { await Task.Delay(500, token); Console.WriteLine($"Page {pageNumber} fetched"); } } // Usage with task tracking var vm = new DataViewModel(); await vm.LoadDataCommand.ExecuteAsync(null); Console.WriteLine($"Is running: {vm.LoadDataCommand.IsRunning}"); // false (completed) Console.WriteLine($"Execution task: {vm.LoadDataCommand.ExecutionTask}"); // Task reference // Cancel ongoing operation vm.FetchPageCommand.Execute(1); vm.FetchPageCommand.Cancel(); Console.WriteLine($"Cancellation requested: {vm.FetchPageCommand.IsCancellationRequested}"); ``` -------------------------------- ### Efficient Exception Throwing with ThrowHelper Source: https://context7.com/communitytoolkit/dotnet/llms.txt Use ThrowHelper to throw exceptions without impacting JIT optimization. It provides methods for common exception types like ArgumentOutOfRangeException, ObjectDisposedException, and ArgumentNullException. ```csharp using CommunityToolkit.Diagnostics; public class DataProcessor { private bool isDisposed; private readonly byte[] buffer; public DataProcessor(int bufferSize) { if (bufferSize <= 0) { ThrowHelper.ThrowArgumentOutOfRangeException(nameof(bufferSize), "Buffer size must be positive"); } buffer = new byte[bufferSize]; } public void Process(string data) { if (isDisposed) { ThrowHelper.ThrowObjectDisposedException(nameof(DataProcessor)); } if (string.IsNullOrEmpty(data)) { ThrowHelper.ThrowArgumentNullException(nameof(data)); } // Process data... } public void ValidateState() { if (buffer.Length == 0) { ThrowHelper.ThrowInvalidOperationException("Buffer is empty"); } } // Various exception types available public void DemonstrateThrowHelpers() { // ThrowHelper.ThrowArgumentException(nameof(param), "Invalid argument"); // ThrowHelper.ThrowArgumentNullException(nameof(param)); // ThrowHelper.ThrowArgumentOutOfRangeException(nameof(index)); // ThrowHelper.ThrowInvalidOperationException("Operation not allowed"); // ThrowHelper.ThrowNotSupportedException("Feature not supported"); // ThrowHelper.ThrowObjectDisposedException(nameof(DataProcessor)); // ThrowHelper.ThrowFormatException("Invalid format"); // ThrowHelper.ThrowTimeoutException("Operation timed out"); // ThrowHelper.ThrowOperationCanceledException(cancellationToken); } } ``` -------------------------------- ### Validate User Input with StringExtensions Source: https://context7.com/communitytoolkit/dotnet/llms.txt Use extension methods like IsEmail, IsPhoneNumber, IsNumeric, IsDecimal, and IsCharacterString for robust input validation. Ensure the input string conforms to the expected format before processing. ```csharp using CommunityToolkit.Common; public class StringUtilityExamples { public void ValidateUserInput(string email, string phone, string age, string name) { // Email validation (RFC 5322) bool isValidEmail = email.IsEmail(); Console.WriteLine($"Valid email: {isValidEmail}"); // Phone number validation bool isValidPhone = phone.IsPhoneNumber(); Console.WriteLine($"Valid phone: {isValidPhone}"); // Numeric validation bool isInteger = age.IsNumeric(); bool isDecimal = "123.45".IsDecimal(); Console.WriteLine($"Is integer: {isInteger}, Is decimal: {isDecimal}"); // Character-only validation bool isAlphaOnly = name.IsCharacterString(); Console.WriteLine($"Alpha only: {isAlphaOnly}"); } public void ProcessHtmlContent(string htmlContent) { // Remove HTML tags, scripts, styles, and comments string plainText = htmlContent.DecodeHtml(); Console.WriteLine($"Plain text: {plainText}"); // Fix HTML (remove scripts, styles, comments but keep tags) string cleanedHtml = htmlContent.FixHtml(); Console.WriteLine($"Cleaned HTML: {cleanedHtml}"); } public void TruncateStrings() { string longText = "This is a very long string that needs to be truncated"; // Simple truncation string truncated = longText.Truncate(20); Console.WriteLine(truncated); // "This is a very long " // Truncation with ellipsis string withEllipsis = longText.Truncate(20, ellipsis: true); Console.WriteLine(withEllipsis); // "This is a very long..." // Null-safe truncation string? nullString = null; string safe = nullString.Truncate(10); // Returns empty string } } // Example outputs var examples = new StringUtilityExamples(); examples.ValidateUserInput( email: "user@example.com", // true phone: "+1-555-123-4567", // true age: "25", // true name: "John" // true ); ``` -------------------------------- ### Generate ICommand Properties with RelayCommand Attribute Source: https://context7.com/communitytoolkit/dotnet/llms.txt Use the [RelayCommand] attribute to automatically generate ICommand properties from methods. Supports synchronous, asynchronous operations, and cancellation. ```csharp using CommunityToolkit.Mvvm.Input; public partial class FileViewModel { private string status; // Generates: public IRelayCommand SaveCommand { get; } [RelayCommand] private void Save() { status = "Saved!"; } // Generates: public IRelayCommand OpenFileCommand { get; } [RelayCommand] private void OpenFile(string path) { status = $"Opened: {path}"; } // Generates: public IAsyncRelayCommand DownloadCommand { get; } [RelayCommand] private async Task DownloadAsync(CancellationToken token) { status = "Downloading..."; await Task.Delay(1000, token); status = "Downloaded!"; } // With CanExecute and cancel command [RelayCommand(CanExecute = nameof(CanUpload), IncludeCancelCommand = true)] private async Task UploadAsync(CancellationToken token) { await Task.Delay(2000, token); } private bool CanUpload() => !string.IsNullOrEmpty(status); } ``` -------------------------------- ### Guard for Argument Validation Source: https://context7.com/communitytoolkit/dotnet/llms.txt Utilize the Guard class for comprehensive argument validation in methods. It provides static methods for null checks, string validations, numeric ranges, collection sizes, and type checks, throwing specific exceptions upon failure. ```csharp using CommunityToolkit.Diagnostics; public class UserService { public void CreateUser(string username, string email, int age, IList roles) { // Null checks Guard.IsNotNull(username); Guard.IsNotNull(email); Guard.IsNotNull(roles); // String validations Guard.IsNotNullOrEmpty(username); Guard.IsNotNullOrWhiteSpace(email); Guard.HasSizeGreaterThanOrEqualTo(username, 3); Guard.HasSizeLessThanOrEqualTo(username, 50); // Numeric validations Guard.IsGreaterThanOrEqualTo(age, 0); Guard.IsLessThan(age, 150); Guard.IsInRange(age, 0, 150); // Collection validations Guard.IsNotEmpty(roles); Guard.HasSizeGreaterThan(roles, 0); // Type checks Guard.IsOfType(username); Guard.IsAssignableToType>(roles); Console.WriteLine($"User {username} created with {roles.Count} roles"); } public void ProcessData(byte[] buffer, int offset, int count) { Guard.IsNotNull(buffer); Guard.IsInRangeFor(offset, buffer); Guard.IsLessThanOrEqualTo(offset + count, buffer.Length); // Process buffer... } } // Usage - valid call var service = new UserService(); service.CreateUser("john_doe", "john@example.com", 25, new List { "admin" }); // Usage - throws ArgumentException try { service.CreateUser("", "john@example.com", 25, new List()); } catch (ArgumentException ex) { Console.WriteLine($"Validation failed: {ex.Message}"); } ``` -------------------------------- ### ObservableObject Base Class for Observable Properties Source: https://context7.com/communitytoolkit/dotnet/llms.txt Use ObservableObject as a base class for properties that need to notify changes. It implements INotifyPropertyChanged and INotifyPropertyChanging, providing the SetProperty method for efficient notifications. ```csharp using CommunityToolkit.Mvvm.ComponentModel; public class PersonViewModel : ObservableObject { private string name; private int age; public string Name { get => name; set => SetProperty(ref name, value); // Raises PropertyChanging and PropertyChanged } public int Age { get => age; set => SetProperty(ref age, value); } } // Usage var person = new PersonViewModel(); person.PropertyChanged += (s, e) => Console.WriteLine($"Property {e.PropertyName} changed"); person.Name = "John"; // Output: Property Name changed person.Age = 30; // Output: Property Age changed ``` -------------------------------- ### Guard for Boolean and Reference Validation Source: https://context7.com/communitytoolkit/dotnet/llms.txt Extend argument validation with Guard methods for boolean conditions, reference equality checks, and default value assertions. These are useful for ensuring specific states or object identities before proceeding. ```csharp using CommunityToolkit.Diagnostics; public class ValidationExamples { public void ProcessOrder(Order order, Order previousOrder, bool isEnabled) { // Boolean checks Guard.IsTrue(isEnabled); Guard.IsFalse(order.IsCancelled); // Reference equality Guard.IsReferenceNotEqualTo(order, previousOrder); // Default value checks Guard.IsNotDefault(order.Id); // For value types Console.WriteLine("Order validation passed"); } public void CompareItems(T item1, T item2) where T : class { Guard.IsNotNull(item1); Guard.IsNotNull(item2); Guard.IsReferenceNotEqualTo(item1, item2); // For same instance check // Guard.IsReferenceEqualTo(item1, expectedItem); } } public record Order(Guid Id, bool IsCancelled); ``` -------------------------------- ### WeakReferenceMessenger for Loosely Coupled Messaging Source: https://context7.com/communitytoolkit/dotnet/llms.txt Implement loosely coupled communication using WeakReferenceMessenger. It automatically cleans up message subscriptions when recipients are garbage collected. Define custom messages by inheriting from ValueChangedMessage or using plain classes. ```csharp using CommunityToolkit.Mvvm.Messaging; using CommunityToolkit.Mvvm.Messaging.Messages; // Define messages public class UserLoggedInMessage : ValueChangedMessage { public UserLoggedInMessage(string username) : base(username) { } } public class NotificationMessage { public string Title { get; init; } public string Body { get; init; } } // Recipient using interface public class DashboardViewModel : IRecipient { public string WelcomeText { get; private set; } public DashboardViewModel() { WeakReferenceMessenger.Default.Register(this); } public void Receive(UserLoggedInMessage message) { WelcomeText = $"Welcome, {message.Value}!"; } } // Recipient using delegate public class NotificationService { public NotificationService() { WeakReferenceMessenger.Default.Register(this, (r, m) => { Console.WriteLine($"Notification: {m.Title} - {m.Body}"); }); } } // Sending messages WeakReferenceMessenger.Default.Send(new UserLoggedInMessage("Alice")); WeakReferenceMessenger.Default.Send(new NotificationMessage { Title = "New Order", Body = "Order #123 received" }); // Unregister when done WeakReferenceMessenger.Default.UnregisterAll(this); ``` -------------------------------- ### [ObservableProperty] Attribute for Source-Generated Properties Source: https://context7.com/communitytoolkit/dotnet/llms.txt Employ the [ObservableProperty] attribute to automatically generate observable properties, reducing boilerplate code. This attribute supports both partial properties (C# 14+ preview) and fields. ```csharp using CommunityToolkit.Mvvm.ComponentModel; // Using partial properties (C# 14+ / preview) public partial class UserViewModel : ObservableObject { [ObservableProperty] public partial string FirstName { get; set; } [ObservableProperty] public partial string LastName { get; set; } [ObservableProperty] public partial bool IsActive { get; set; } } // Using fields (legacy approach) public partial class LegacyUserViewModel : ObservableObject { [ObservableProperty] private string firstName; [ObservableProperty] private string lastName; } // Generated code provides full INotifyPropertyChanged support var user = new UserViewModel(); user.PropertyChanged += (s, e) => Console.WriteLine($"{e.PropertyName} = {typeof(UserViewModel).GetProperty(e.PropertyName)?.GetValue(s)}"); user.FirstName = "Jane"; // Output: FirstName = Jane user.IsActive = true; // Output: IsActive = True ``` -------------------------------- ### ObservableValidator for MVVM Validation Source: https://context7.com/communitytoolkit/dotnet/llms.txt Use ObservableValidator as a base class for MVVM view models to integrate data annotation validation with ObservableObject. Properties decorated with validation attributes will be automatically validated when their values change if `validate: true` is passed to `SetProperty`. ```csharp using System.ComponentModel.DataAnnotations; using CommunityToolkit.Mvvm.ComponentModel; public partial class RegistrationViewModel : ObservableValidator { private string email; private string password; private int age; [Required(ErrorMessage = "Email is required")] [EmailAddress(ErrorMessage = "Invalid email format")] public string Email { get => email; set => SetProperty(ref email, value, validate: true); } [Required] [MinLength(8, ErrorMessage = "Password must be at least 8 characters")] public string Password { get => password; set => SetProperty(ref password, value, validate: true); } [Range(18, 120, ErrorMessage = "Age must be between 18 and 120")] public int Age { get => age; set => SetProperty(ref age, value, validate: true); } public void Submit() { ValidateAllProperties(); if (!HasErrors) { Console.WriteLine("Form submitted successfully!"); } else { foreach (var error in GetErrors()) { Console.WriteLine($"Error: {error.ErrorMessage}"); } } } } // Usage var vm = new RegistrationViewModel(); vm.ErrorsChanged += (s, e) => Console.WriteLine($"Errors changed for: {e.PropertyName}"); vim.Email = "invalid"; // Triggers validation error vim.Password = "short"; // Triggers validation error vim.Age = 10; // Triggers validation error Console.WriteLine($"Has errors: {vm.HasErrors}"); // true vim.ClearErrors(); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.