### Install PolySharp via .NET CLI Source: https://context7.com/sergio0694/polysharp/llms.txt Install the PolySharp NuGet package using the .NET CLI command. ```bash dotnet add package PolySharp ``` -------------------------------- ### Install PolySharp via NuGet Source: https://context7.com/sergio0694/polysharp/llms.txt Add the PolySharp NuGet package to your project using the PackageReference format. ```xml all runtime; build; native; contentfiles; analyzers ``` -------------------------------- ### Install PolySharp via Package Manager Console Source: https://context7.com/sergio0694/polysharp/llms.txt Install the PolySharp NuGet package using the Package Manager Console command. ```powershell Install-Package PolySharp ``` -------------------------------- ### Init-Only Properties Example Source: https://context7.com/sergio0694/polysharp/llms.txt Demonstrates the use of init-only properties, enabled by PolySharp's generated IsExternalInit class. ```csharp // PolySharp generates the IsExternalInit class, enabling init-only properties public class Person { public string FirstName { get; init; } public string LastName { get; init; } public int Age { get; init; } } // Usage var person = new Person { FirstName = "John", LastName = "Doe", Age = 30 }; // Attempting to modify after initialization causes compile error: // person.FirstName = "Jane"; // Error CS8852 ``` -------------------------------- ### Index and Range Types Example Source: https://context7.com/sergio0694/polysharp/llms.txt Illustrates using indices and ranges syntax for collection slicing on older frameworks, provided by PolySharp's System.Index and System.Range types. ```csharp // PolySharp provides System.Index and System.Range types int[] numbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Index from end using ^ operator int lastElement = numbers[^1]; // 9 int secondToLast = numbers[^2]; // 8 // Range slicing using .. operator int[] firstThree = numbers[..3]; // { 0, 1, 2 } int[] lastThree = numbers[^3..]; // { 7, 8, 9 } int[] middle = numbers[3..7]; // { 3, 4, 5, 6 } int[] allButFirstAndLast = numbers[1..^1]; // { 1, 2, 3, 4, 5, 6, 7, 8 } // Works with strings too string text = "Hello, World!"; string world = text[7..^1]; // "World" ``` -------------------------------- ### C# Module Initializer for Assembly Load Source: https://context7.com/sergio0694/polysharp/llms.txt Execute code automatically when an assembly is loaded using the [ModuleInitializer] attribute. This method runs once per module upon its first load, useful for setup tasks like configuring logging or registering services. ```csharp using System.Runtime.CompilerServices; public static class ApplicationBootstrap { private static bool _initialized; // Method runs once when the module (assembly) is first loaded [ModuleInitializer] public static void Initialize() { if (_initialized) return; // Configure logging Console.WriteLine("Module initialized"); // Register default services RegisterServices(); _initialized = true; } private static void RegisterServices() { // Service registration logic } } // No explicit call needed - Initialize() runs automatically on assembly load ``` -------------------------------- ### Custom Interpolated String Handler Source: https://context7.com/sergio0694/polysharp/llms.txt Implement a custom interpolated string handler to control how interpolated strings are processed, enabling efficient string building. This example demonstrates a handler for conditional logging, avoiding expensive operations when logging is disabled. ```csharp using System.Runtime.CompilerServices; using System.Text; [InterpolatedStringHandler] public ref struct LogInterpolatedStringHandler { private readonly StringBuilder _builder; private readonly bool _enabled; public LogInterpolatedStringHandler( int literalLength, int formattedCount, bool isEnabled, out bool handlerIsValid) { _enabled = isEnabled; handlerIsValid = isEnabled; _builder = isEnabled ? new StringBuilder(literalLength) : null!; } public void AppendLiteral(string s) { if (_enabled) _builder.Append(s); } public void AppendFormatted(T value) { if (_enabled) _builder.Append(value); } public void AppendFormatted(T value, string format) { if (_enabled) _builder.AppendFormat($"{{0:{format}}}", value); } internal string GetFormattedText() => _builder?.ToString() ?? string.Empty; } public static class Logger { public static bool IsDebugEnabled { get; set; } = true; // Expensive string formatting only occurs if logging is enabled public static void Debug( [InterpolatedStringHandlerArgument(nameof(isEnabled))] LogInterpolatedStringHandler handler, bool isEnabled = true) { if (isEnabled && IsDebugEnabled) { Console.WriteLine($"[DEBUG] {handler.GetFormattedText()}"); } } } // Usage - expensive ToString() calls are skipped when logging disabled var data = new ExpensiveObject(); Logger.Debug($"Processing {data} with value {CalculateExpensiveValue()}", Logger.IsDebugEnabled); ``` -------------------------------- ### Trimming and AOT Attributes for Libraries Source: https://context7.com/sergio0694/polysharp/llms.txt Annotate code with attributes like `RequiresUnreferencedCode`, `DynamicallyAccessedMembers`, and `RequiresDynamicCode` to guide the .NET trimmer and Ahead-Of-Time (AOT) compilation, ensuring library compatibility. `DynamicDependency` can preserve specific members. ```csharp using System.Diagnostics.CodeAnalysis; public class ReflectionHelper { // Warn that this method uses reflection unsafely for trimming [RequiresUnreferencedCode("Uses reflection to discover types")] public Type[] GetAllTypes(Assembly assembly) { return assembly.GetTypes(); } // Indicate which members are accessed dynamically public object CreateInstance( [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type) { return Activator.CreateInstance(type)!; } // Warn about dynamic code generation [RequiresDynamicCode("Creates types at runtime")] public Type CreateDynamicType() { // Dynamic type generation code throw new NotImplementedException(); } // Preserve specific dependencies during trimming [DynamicDependency(nameof(ToString), typeof(object))] public string GetString(object obj) { return obj.ToString()!; } } ``` -------------------------------- ### Configure Project for Modern C# Source: https://context7.com/sergio0694/polysharp/llms.txt Configure your project's .NET SDK, target framework, and C# language version to enable modern features with PolySharp. ```xml net472 13.0 enable all runtime; build; native; contentfiles; analyzers ``` -------------------------------- ### Platform Support Attributes for Older Frameworks Source: https://context7.com/sergio0694/polysharp/llms.txt Use platform compatibility annotations like `SupportedOSPlatform` and `UnsupportedOSPlatform` to manage feature availability across different operating systems and versions. A `SupportedOSPlatformGuard` can be used for runtime checks. ```csharp using System.Runtime.Versioning; public class PlatformSpecificFeatures { // Method only works on Windows 10+ [SupportedOSPlatform("windows10.0")] public void UseWindowsNotifications() { // Windows-specific notification code } // Method works everywhere except iOS [UnsupportedOSPlatform("ios")] public void UseFileSystem() { // File system operations not supported on iOS sandbox } // Check platform at runtime using guard attribute [SupportedOSPlatformGuard("windows")] public static bool IsWindows => OperatingSystem.IsWindows(); public void DoSomething() { if (IsWindows) { UseWindowsNotifications(); } } } ``` -------------------------------- ### Skip Locals Init for Performance Source: https://context7.com/sergio0694/polysharp/llms.txt Use the [SkipLocalsInit] attribute to prevent the runtime from zero-initializing local variables, potentially improving performance in performance-critical code. This can be applied at the method or module level. Caution: Ensure all local variables are manually initialized before use. ```csharp using System.Runtime.CompilerServices; public class HighPerformanceBuffer { // Skip zero-initialization for entire class methods [SkipLocalsInit] public unsafe void ProcessBuffer(byte* input, int length) { // Local array not zero-initialized (performance gain) // CAUTION: Must initialize manually before reading byte* buffer = stackalloc byte[1024]; for (int i = 0; i < Math.Min(length, 1024); i++) { buffer[i] = input[i]; } ProcessInternal(buffer, Math.Min(length, 1024)); } private unsafe void ProcessInternal(byte* buffer, int length) { // Process buffer... } } // Can also be applied at module level via assembly attribute [module: SkipLocalsInit] ``` -------------------------------- ### Configure PolySharp with MSBuild Properties Source: https://context7.com/sergio0694/polysharp/llms.txt Configure PolySharp's behavior, such as accessibility of generated types, inclusion of runtime-supported attributes, and exclusion/inclusion of specific types, using MSBuild properties in your project file. ```xml net472 13.0 true true System.Index; System.Range; System.Runtime.CompilerServices.CallerArgumentExpressionAttribute System.Runtime.CompilerServices.IsExternalInit; System.Diagnostics.CodeAnalysis.NotNullWhenAttribute true true all runtime; build; native; contentfiles; analyzers ``` -------------------------------- ### C# String Syntax Attribute for IDE Highlighting Source: https://context7.com/sergio0694/polysharp/llms.txt Enable IDE syntax highlighting for string parameters containing specific formats like Regex, JSON, DateTime formats, or URIs using the [StringSyntax] attribute. This improves code readability and reduces errors. ```csharp using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; public static class Validator { // IDE provides regex syntax highlighting and validation public static bool IsMatch( string input, [StringSyntax(StringSyntax.Regex)] string pattern) { return Regex.IsMatch(input, pattern); } // IDE provides JSON syntax highlighting public static void LogJson([StringSyntax(StringSyntax.Json)] string json) { Console.WriteLine(json); } // IDE provides DateTime format syntax highlighting public static string FormatDate( DateTime date, [StringSyntax(StringSyntax.DateTimeFormat)] string format) { return date.ToString(format); } // IDE provides URI syntax highlighting public static Uri CreateUri([StringSyntax(StringSyntax.Uri)] string uri) { return new Uri(uri); } } // Usage with IDE syntax highlighting in string literals bool isEmail = Validator.IsMatch(input, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"); string formatted = Validator.FormatDate(DateTime.Now, "yyyy-MM-dd HH:mm:ss"); Validator.LogJson("{{\"name\": \"John\", \"age\": 30}}"); ``` -------------------------------- ### C# Required Members for Object Initialization Source: https://context7.com/sergio0694/polysharp/llms.txt Use required members to enforce initialization of properties during object creation. Ensure all required members are set either via an object initializer or a constructor that explicitly sets them. ```csharp using System.Diagnostics.CodeAnalysis; public class Configuration { // Required members must be set during object initialization public required string ConnectionString { get; init; } public required string ApplicationName { get; init; } // Optional member with default value public int Timeout { get; init; } = 30; // [SetsRequiredMembers] indicates constructor sets all required members [SetsRequiredMembers] public Configuration(string connectionString, string appName) { ConnectionString = connectionString; ApplicationName = appName; } // Parameterless constructor requires object initializer public Configuration() { } } // Usage - must provide all required members var config1 = new Configuration { ConnectionString = "Server=localhost;Database=mydb", ApplicationName = "MyApp" }; // Using constructor that sets required members var config2 = new Configuration("Server=localhost;Database=mydb", "MyApp"); // Compile error - missing required member: // var invalid = new Configuration { ApplicationName = "MyApp" }; // Error ``` -------------------------------- ### Collection Builder for Custom Collections Source: https://context7.com/sergio0694/polysharp/llms.txt Enable custom collection types to work with collection expressions (C# 12+) by using the [CollectionBuilder] attribute. This allows your custom collections to be initialized using a familiar array-like syntax. ```csharp using System.Runtime.CompilerServices; [CollectionBuilder(typeof(ImmutableListBuilder), nameof(ImmutableListBuilder.Create))] public sealed class ImmutableList { private readonly T[] _items; internal ImmutableList(T[] items) => _items = items; public int Count => _items.Length; public T this[int index] => _items[index]; public IEnumerator GetEnumerator() { foreach (var item in _items) yield return item; } } public static class ImmutableListBuilder { public static ImmutableList Create(ReadOnlySpan items) { return new ImmutableList(items.ToArray()); } } // Usage with collection expressions (C# 12+) ImmutableList numbers = [1, 2, 3, 4, 5]; ImmutableList names = ["Alice", "Bob", "Charlie"]; // Spread operator works too ImmutableList combined = [..numbers, 6, 7, 8]; ``` -------------------------------- ### DoesNotReturn Attribute for Non-Returning Methods Source: https://context7.com/sergio0694/polysharp/llms.txt Use the `DoesNotReturn` attribute to indicate that a method will never return normally, allowing the compiler to understand control flow and potentially avoid nullability warnings. `DoesNotReturnIf` can be used for conditional non-return scenarios. ```csharp using System.Diagnostics.CodeAnalysis; public static class ThrowHelper { // Compiler knows this method never returns [DoesNotReturn] public static void ThrowArgumentNull(string paramName) { throw new ArgumentNullException(paramName); } [DoesNotReturn] public static void ThrowInvalidOperation(string message) { throw new InvalidOperationException(message); } // [DoesNotReturnIf] for conditional non-return public static void ThrowIfNull( [NotNull] object? value, [DoesNotReturnIf(true)] bool shouldThrow = false) { if (value is null || shouldThrow) { throw new ArgumentNullException(); } } } // Usage - compiler understands control flow public string ProcessValue(string? input) { if (input is null) { ThrowHelper.ThrowArgumentNull(nameof(input)); } // Compiler knows 'input' is not null here due to [DoesNotReturn] return input.ToUpper(); } ``` -------------------------------- ### Nullable Reference Types Attributes Source: https://context7.com/sergio0694/polysharp/llms.txt Utilizes nullable annotations for improved null-safety analysis, including attributes like NotNullWhen, MaybeNullWhen, AllowNull, NotNull, and MemberNotNull. ```csharp using System.Diagnostics.CodeAnalysis; public class Repository { private readonly Dictionary _cache = new(); // [NotNullWhen] indicates parameter is not null when method returns true public bool TryGetValue(string key, [NotNullWhen(true)] out object? value) { return _cache.TryGetValue(key, out value); } // [MaybeNullWhen] indicates parameter may be null when method returns specific value public bool TryRemove(string key, [MaybeNullWhen(false)] out object? removed) { if (_cache.ContainsKey(key)) { removed = _cache[key]; _cache.Remove(key); return true; } removed = default; return false; } // [AllowNull] allows null input even if type is non-nullable public void SetDefault([AllowNull] string value) { _cache["default"] = value ?? string.Empty; } // [NotNull] ensures output is never null [return: NotNull] public string GetOrThrow(string key) { if (_cache.TryGetValue(key, out var value) && value is string str) return str; throw new KeyNotFoundException(key); } // [MemberNotNull] guarantees member is not null after method completes [MemberNotNull(nameof(_cache))] private void EnsureCacheInitialized() { // _cache is always initialized, this satisfies the analyzer } } ``` -------------------------------- ### C# Caller Argument Expression Capture Source: https://context7.com/sergio0694/polysharp/llms.txt Capture the expression passed to a method parameter as a string using the [CallerArgumentExpression] attribute. This is useful for validation methods to report the exact argument that failed. ```csharp using System.Runtime.CompilerServices; public static class Guard { // Automatically captures the argument expression as a string public static void NotNull( T? value, [CallerArgumentExpression(nameof(value))] string? expression = null) where T : class { if (value is null) { throw new ArgumentNullException(expression); } } public static void IsPositive( int value, [CallerArgumentExpression(nameof(value))] string? expression = null) { if (value <= 0) { throw new ArgumentOutOfRangeException( expression, value, $"Value '{expression}' must be positive, but was {value}"); } } } // Usage public void ProcessOrder(Order? order, int quantity) { Guard.NotNull(order); Guard.IsPositive(quantity); // Process order... } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.