### Standard ILogger usage Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS065-LoggerMessageAttribute.md Example of a standard logging call that triggers the SS065 analyzer. ```cs public class MyService { private readonly ILogger _logger; public MyService(ILogger logger) { _logger = logger; } public void DoWork(string userId) { _logger.LogInformation("User {UserId} started work", userId); } } ``` -------------------------------- ### No Violation Example Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS046-UnboundedStackalloc.md Illustrates a safe implementation where a heap allocation fallback is used for stackalloc. ```cs byte[] bytes = new byte[64]; Span result = bytes.Length > 16 ? new char[bytes.Length * 2] : stackalloc char[bytes.Length * 2]; ``` -------------------------------- ### Violation of SS050 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS050-ParameterAssignedInConstructor.md Example of a constructor parameter being incorrectly assigned. ```cs class Test { int Count { get; set; } Test(int count) { count = Count; } } ``` -------------------------------- ### Fix for SS067 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS067-RedisResponseNotHandled.md Example of code that correctly captures and validates the Elasticsearch client response. ```csharp using System.Threading.Tasks; using Elastic.Clients.Elasticsearch; class Test { async Task Method() { var client = new ElasticsearchClient(); var response = await client.IndexAsync(new MyDocument()); if (!response.IsValidResponse) { // Handle error } } } ``` -------------------------------- ### Install SharpSource via Package Manager Source: https://github.com/vannevelj/sharpsource/blob/master/README.md Use these methods to add the SharpSource analyzer package to your project. ```powershell Install-Package SharpSource ``` ```xml ``` -------------------------------- ### Install SharpSource via NuGet Source: https://context7.com/vannevelj/sharpsource/llms.txt Add the SharpSource analyzer package to your project using MSBuild or PowerShell. ```xml ``` ```powershell Install-Package SharpSource ``` -------------------------------- ### Avoid Default Guid Constructor Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS010-NewGuid.md The default Guid constructor creates an empty GUID, which is rarely intended. Use Guid.NewGuid() to generate a valid, non-empty GUID. ```cs var g = new Guid(); ``` ```cs var g = Guid.NewGuid(); ``` -------------------------------- ### SS010: NewGuid Source: https://context7.com/vannevelj/sharpsource/llms.txt Use Guid.NewGuid() to generate unique identifiers instead of the default constructor which creates an empty GUID. ```csharp // Violation: creates empty GUID (all zeros) var g = new Guid(); // Fix: generate a unique identifier var g = Guid.NewGuid(); ``` -------------------------------- ### Identify integer division violation Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS003-DivideIntegerByInteger.md Shows an example of integer division that results in implicit rounding. ```cs int result = 5 / 6; ``` -------------------------------- ### Violation of SS015 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md Example of a string.Format() call where placeholders are provided in an incorrect, non-ascending index order. ```cs string s = string.Format("Hello {1}, my name is {0}. Yes you heard that right, {0}.", "Mr. Test", "Mr. Tester"); ``` -------------------------------- ### Identify PointlessCollectionToString violation Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS053-PointlessCollectionToString.md This example demonstrates the code pattern that triggers the SS053 warning. ```cs using System; using System.Collections.Generic; var collection = new List(); Console.Write(collection.ToString()); ``` -------------------------------- ### Violation of SS059 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS059-DisposeAsyncDisposable.md Example of using a standard using statement for an object that implements IAsyncDisposable. ```cs using System.IO; using System.Threading.Tasks; async Task Method() { using var stream = new FileStream("", FileMode.Create); } ``` -------------------------------- ### Violation of SS043 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS043-MultipleFromBodyParameters.md Example of a controller method incorrectly using multiple [FromBody] attributes. ```cs using Microsoft.AspNetCore.Mvc; class MyController { void DoThing([FromBody] string first, [FromBody] string second) { } } ``` -------------------------------- ### Violation of NewtonsoftMixedWithSystemTextJson Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS054-NewtonsoftMixedWithSystemTextJson.md Example showing an object using System.Text.Json attributes while being serialized with Newtonsoft.Json. ```cs var data = Newtonsoft.Json.JsonConvert.SerializeObject(new MyData()); class MyData { [System.Text.Json.Serialization.JsonPropertyName("prop")] public int MyProp { get; set; } } ``` -------------------------------- ### Configure .editorconfig for Analyzer Severity Source: https://context7.com/vannevelj/sharpsource/llms.txt Analyzer severity can be adjusted using the .editorconfig file. This example shows how to disable specific rules or set them to a suggestion level. ```ini # .editorconfig - disable specific rules [*.cs] dotnet_diagnostic.SS002.severity = none dotnet_diagnostic.SS036.severity = suggestion ``` -------------------------------- ### Violation of SS023 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS023-ExceptionThrownFromPropertyGetter.md Example of a property getter throwing an ArgumentException, which triggers the SS023 warning. ```cs public class MyClass { public int MyProp { get { throw new ArgumentException(); } set { } } } ``` -------------------------------- ### Violation of SS039 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS039-EnumWithoutDefaultValue.md Example of an enum definition that lacks a default value of 0. ```cs enum Test { A } ``` -------------------------------- ### Ensure Activity is Stopped or Disposed in C# Source: https://context7.com/vannevelj/sharpsource/llms.txt Activities started with `ActivitySource.StartActivity()` must be stopped or disposed to ensure telemetry data is recorded. Use a `using` statement for automatic disposal. ```csharp // Violation: activity never stopped void ProcessRequest() { var activity = Source.StartActivity("ProcessRequest"); DoWork(); } // Activity data lost // Fix: use using statement void ProcessRequest() { using var activity = Source.StartActivity("ProcessRequest"); DoWork(); } // Activity automatically stopped ``` -------------------------------- ### Violation of SS024 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS024-ExceptionThrownFromStaticConstructor.md Example of a class throwing an exception within a static constructor, which triggers the SS024 warning. ```cs public class MyClass { static MyClass() { throw new ArgumentException(); } } ``` -------------------------------- ### Violation of SS022 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS022-ExceptionThrownFromImplicitOperator.md Example of an implicit operator throwing an ArgumentException, which triggers the SS022 warning. ```cs public class MyClass { public static implicit operator MyClass(double d) { throw new ArgumentException(); } } ``` -------------------------------- ### Violation of SS026 in C# Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS026-ExceptionThrownFromEqualityOperator.md Example of an equality operator throwing an ArgumentException, which triggers the SS026 violation. ```cs public class MyClass { public static bool operator ==(double d, MyClass mc) { return false; } public static bool operator !=(double d, MyClass mc) { throw new ArgumentException(); } } ``` -------------------------------- ### Violation of SS067 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS067-RedisResponseNotHandled.md Example of code where the Elasticsearch client response is discarded without inspection. ```csharp using System.Threading.Tasks; using Elastic.Clients.Elasticsearch; class Test { async Task Method() { var client = new ElasticsearchClient(); await client.IndexAsync(new MyDocument()); } } ``` -------------------------------- ### Use DateTime.UtcNow instead of DateTime.Now Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS002-DateTimeNow.md Use `DateTime.UtcNow` to get a locale-independent value. `DateTime.Now` uses the system's local timezone which often means unexpected behaviour when working with global teams/deployments. ```cs var date = DateTime.Now; ``` ```cs var date = DateTime.UtcNow; ``` -------------------------------- ### Violation: Activity Not Stopped Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS062-ActivityWasNotStopped.md This code starts an activity but does not stop or dispose of it, which can lead to resource leaks. Ensure activities are always ended. ```cs using System.Diagnostics; class Test { private static readonly ActivitySource Source = new("Test"); void Method() { var activity = Source.StartActivity("test"); // Activity is never stopped } } ``` -------------------------------- ### Violation of SS008 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS008-GetHashCodeRefersToMutableMember.md Example of a class where GetHashCode relies on a mutable field, triggering the SS008 warning. ```cs public class Foo { private char _boo = '1'; public override int GetHashCode() { return _boo.GetHashCode(); } } ``` -------------------------------- ### Violation of SS029 in C# Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS029-ExceptionThrownFromGetHashCode.md Example of a class that violates the rule by throwing an ArgumentException from its GetHashCode override. ```cs public class MyClass { public override int GetHashCode() { throw new ArgumentException(); } } ``` -------------------------------- ### Violation of SS058 in C# Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS058-StringConcatenatedInLoop.md Example of string concatenation inside a foreach loop that triggers the SS058 warning. ```cs using System.Collections.Generic; void Method(List items) { var result = ""; foreach (var item in items) { result += item; } } ``` -------------------------------- ### Violation of Collection Traversal Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS057-CollectionManipulatedDuringTraversal.md This example demonstrates an InvalidOperationException caused by removing items from a list while iterating over it. ```cs using System.Collections.Generic; void Method(List items) { foreach (var item in items) { items.Remove(0); } } ``` -------------------------------- ### Violation of SS030 in C# Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS030-ExceptionThrownFromEquals.md Example of a class that violates the rule by throwing an ArgumentException within an overridden Equals method. ```cs class MyClass { public override bool Equals(object o) { throw new ArgumentException(); } } ``` -------------------------------- ### Unnecessary Enumerable Materialization Violation Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md Example of code that triggers the SS041 warning by materializing an IEnumerable before calling Take. ```cs using System.Linq; using System.Collections.Generic; IEnumerable values = new [] { "test" }; values.ToList().Take(1); ``` -------------------------------- ### Recursive Operator Overload Violation Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS012-RecursiveOperatorOverload.md This example demonstrates a class where the equality and inequality operators call themselves, causing infinite recursion. ```cs public class A { public static A operator ==(A a1, A a2) { return a1 == a2; } public static A operator !=(A a1, A a2) { return a1 != a2; } } ``` -------------------------------- ### Violation of SS007 in C# Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS007-FlagsEnumValuesAreNotPowersOfTwo.md Example of an enum violating the rule where 'Buz' is set to 3, which is not a power of two. ```cs using System; [Flags] enum Foo { Bar = 0, Biz = 1, Baz = 2, Buz = 3, Boz = 4 } ``` -------------------------------- ### Violation of SS056 in ASP.NET Core Controller Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS056-FormReadSynchronously.md This example demonstrates the synchronous access of HttpRequest.Form within a controller action, which triggers the SS056 warning. ```cs using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; class MyController : Controller { public IActionResult Post() { var form = HttpContext.Request.Form; return Ok(); } } ``` -------------------------------- ### Violation of HttpClient instantiation Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS037-HttpClientInstantiatedDirectly.md Directly creating an HttpClient instance, which is discouraged due to potential resource exhaustion. ```cs using System.Net.Http; var client = new HttpClient(); ``` -------------------------------- ### Implement Equals() and GetHashCode() Together Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md This is the corrected version where both Equals() and GetHashCode() are implemented. This ensures consistent behavior for object comparisons and hash-based collections. ```cs class MyClass { public override bool Equals(object obj) { throw new System.NotImplementedException(); } public override int GetHashCode() { throw new System.NotImplementedException(); } } ``` -------------------------------- ### Fix: Creating ImmutableArray with Create() Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS061-ImmutableCollectionCreatedIncorrectly.md Use the ImmutableArray.Create() factory method for proper initialization of ImmutableArray to avoid runtime exceptions. ```csharp var array = ImmutableArray.Create(); ``` -------------------------------- ### SS033: AsyncOverloadsAvailable Source: https://context7.com/vannevelj/sharpsource/llms.txt Prefer async overloads in async contexts to avoid blocking threads and improve scalability. ```csharp // Violation: synchronous I/O in async method async Task WriteDataAsync(Stream stream) { using var writer = new StreamWriter(stream); writer.Write("data"); // Blocks thread } // Fix: use async overload async Task WriteDataAsync(Stream stream) { await using var writer = new StreamWriter(stream); await writer.WriteAsync("data"); } ``` -------------------------------- ### Avoid Direct HttpClient Instantiation Source: https://context7.com/vannevelj/sharpsource/llms.txt Use IHttpClientFactory to create HttpClient instances to prevent socket exhaustion and DNS caching issues. Direct instantiation is not recommended for long-running applications. ```csharp // Violation: direct instantiation causes socket exhaustion public async Task GetDataAsync() { var client = new HttpClient(); // Don't do this return await client.GetStringAsync("https://api.example.com/data"); } ``` ```csharp // Fix: inject IHttpClientFactory public class MyService { private readonly IHttpClientFactory _httpClientFactory; public MyService(IHttpClientFactory httpClientFactory) { _httpClientFactory = httpClientFactory; } public async Task GetDataAsync() { var client = _httpClientFactory.CreateClient(); return await client.GetStringAsync("https://api.example.com/data"); } } ``` -------------------------------- ### Violation and Fix for SS034 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS034-AccessingTaskResultWithoutAwait.md Demonstrates the incorrect usage of .Result and the recommended fix using the await keyword. ```cs class MyClass { async Task MyMethod() { var number = Other().Result; } async Task Other() => 5; } ``` ```cs class MyClass { async Task MyMethod() { var number = await Other(); } async Task Other() => 5; } ``` -------------------------------- ### Fix for SS059 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS059-DisposeAsyncDisposable.md Correct implementation using await using to asynchronously dispose of the object. ```cs using System.IO; using System.Threading.Tasks; async Task Method() { await using var stream = new FileStream("", FileMode.Create); } ``` -------------------------------- ### Fix for SS015 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS015-StringPlaceholdersInWrongOrder.md Corrected version of the string.Format() call with placeholders and arguments reordered to follow ascending index order. ```cs string s = string.Format("Hello {0}, my name is {1}. Yes you heard that right, {1}.", "Mr. Tester", "Mr. Test"); ``` -------------------------------- ### Violation of SS009 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS009-LoopedRandomInstantiation.md Shows the incorrect pattern of instantiating System.Random inside a loop. ```cs while (true) { var rand = new Random(); } ``` -------------------------------- ### Fix: Use using Statement for Activity Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS062-ActivityWasNotStopped.md This code demonstrates the recommended fix using a `using` statement to automatically dispose of the activity when it goes out of scope. This ensures the activity is always stopped. ```cs using System.Diagnostics; class Test { private static readonly ActivitySource Source = new("Test"); void Method() { using var activity = Source.StartActivity("test"); // Activity is automatically disposed at end of scope } } ``` -------------------------------- ### Use Async Overload for StringWriter Write Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS033-AsyncOverloadsAvailable.md Prefer using `WriteAsync` over `Write` when available for `StringWriter` to leverage non-blocking IO operations. Ensure the method is marked as `async` and uses `await`. ```cs using System.IO; async void MyMethod() { new StringWriter().Write(""); } ``` ```cs using System.IO; async void MyMethod() { await new StringWriter().WriteAsync(""); } ``` -------------------------------- ### Fix for SS055 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS055-MultipleOrderByCalls.md Demonstrates the correct usage using ThenBy to maintain multiple sort orders. ```cs record Data(int X, int Y); var data = new Data[] { new(1, 3), new(1, 4), new Data(2, 3), new(2, 1), new(1, 1) }; var ordered = data.OrderBy(obj => obj.X).ThenBy(obj => obj.Y); ``` -------------------------------- ### Fix for ConcurrentDictionary emptiness check Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md Demonstrates the recommended approach using the .IsEmpty property to avoid unnecessary locking. ```cs using System.Collections.Concurrent; var dic = new ConcurrentDictionary(); var empty = dic.IsEmpty; ``` -------------------------------- ### Use StringComparison for Case-Insensitive String Comparisons Source: https://context7.com/vannevelj/sharpsource/llms.txt Use StringComparison for case-insensitive comparisons instead of allocating new strings with ToLower() or ToUpper(). This avoids unnecessary memory allocations. ```csharp // Violation: allocates new strings bool match = s1.ToLower() == s2.ToLower(); // Fix: use StringComparison (no allocations) bool match = string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase); ``` -------------------------------- ### SS002: DateTimeNow Source: https://context7.com/vannevelj/sharpsource/llms.txt Use DateTime.UtcNow instead of DateTime.Now to avoid locale-dependent timestamp issues in global deployments. ```csharp // Violation: timezone-dependent timestamp var date = DateTime.Now; // Fix: use UTC for consistency across timezones var date = DateTime.UtcNow; ``` -------------------------------- ### Use Consistent JSON Serialization Attributes Source: https://context7.com/vannevelj/sharpsource/llms.txt Do not mix Newtonsoft.Json and System.Text.Json attributes on the same types, as attributes from one library are ignored by the other. Use attributes consistent with your chosen serializer. ```csharp // Violation: mixed serialization attributes var json = JsonConvert.SerializeObject(new MyData()); // Newtonsoft class MyData { [System.Text.Json.Serialization.JsonPropertyName("prop")] // Ignored! public int MyProp { get; set; } } // Fix: use consistent attributes var json = JsonConvert.SerializeObject(new MyData()); class MyData { [Newtonsoft.Json.JsonProperty("prop")] // Matches serializer public int MyProp { get; set; } } ``` -------------------------------- ### TimeSpan constructor violation and fix Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS068-TimeSpanConstructedWithTicks.md Demonstrates the incorrect use of the TimeSpan constructor with ticks and the recommended fix using factory methods. ```cs var timeout = new TimeSpan(30); ``` ```cs var timeout = TimeSpan.FromSeconds(30); ``` -------------------------------- ### Use LoggerMessage Attribute for High-Performance Logging in C# Source: https://context7.com/vannevelj/sharpsource/llms.txt Employ `[LoggerMessage]` source generation for efficient logging, avoiding the overhead of `ILogger` extension methods, boxing, and runtime parsing. ```csharp // Violation: runtime overhead public void ProcessOrder(int orderId) { _logger.LogInformation("Processing order {OrderId}", orderId); } // Fix: compile-time generated logging public partial class OrderService { [LoggerMessage(Level = LogLevel.Information, Message = "Processing order {OrderId}")] private partial void LogProcessingOrder(int orderId); public void ProcessOrder(int orderId) { LogProcessingOrder(orderId); } } ``` -------------------------------- ### Fix for UnboundedStackalloc Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS046-UnboundedStackalloc.md Shows the recommended fix using a ternary operator to provide a heap allocation fallback. ```cs var len = new Random().Next(); Span values = len < 1024 ? stackalloc int[len] : new int[len]; ``` -------------------------------- ### Async method return type violation and fix Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS001-AsyncMethodWithVoidReturnType.md Demonstrates the incorrect use of async void and the corrected version returning Task. ```cs async void WriteFile() { await File.WriteAllTextAsync("c:/temp", "content") } ``` ```cs async Task WriteFile() { await File.WriteAllTextAsync("c:/temp", "content") } ``` -------------------------------- ### SS013: RethrowExceptionWithoutLosingStacktrace Source: https://context7.com/vannevelj/sharpsource/llms.txt Use throw; instead of throw ex; to preserve the original stack trace when rethrowing exceptions. ```csharp // Violation: loses original stack trace try { await ProcessDataAsync(); } catch (Exception ex) { LogError(ex); throw ex; // Stack trace now starts here } // Fix: preserve stack trace with empty throw try { await ProcessDataAsync(); } catch (Exception ex) { LogError(ex); throw; // Original stack trace preserved } ``` -------------------------------- ### Avoid Multiple ValueTask Awaits Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS063-ValueTaskAwaitedMultipleTimes.md A ValueTask instance may only be awaited once. Awaiting it more than once can lead to undefined behavior. Ensure each ValueTask is consumed only once. ```cs async Task Method() { ValueTask GetValueTask() => ValueTask.CompletedTask; var task = GetValueTask(); await task; await task; // Second await on the same ValueTask } ``` -------------------------------- ### Properly Dispose IAsyncDisposable with await using in C# Source: https://context7.com/vannevelj/sharpsource/llms.txt In async contexts, use `await using` for types implementing `IAsyncDisposable` to ensure asynchronous disposal. Synchronous `using` calls `Dispose()` instead of `DisposeAsync()`. ```csharp // Violation: synchronous dispose in async method async Task ProcessFileAsync() { using var stream = new FileStream("file.txt", FileMode.Open); await ReadDataAsync(stream); } // Calls Dispose() synchronously // Fix: use await using async Task ProcessFileAsync() { await using var stream = new FileStream("file.txt", FileMode.Open); await ReadDataAsync(stream); } // Calls DisposeAsync() asynchronously ``` -------------------------------- ### Create Immutable Collections Correctly in C# Source: https://context7.com/vannevelj/sharpsource/llms.txt Use factory methods like `ImmutableArray.Create()` instead of constructors for immutable collections. `new ImmutableArray()` creates an uninitialized struct that can lead to exceptions. ```csharp // Violation: creates uninitialized struct var array = new ImmutableArray(); var count = array.Length; // Throws NullReferenceException! // Fix: use factory method var array = ImmutableArray.Create(); var count = array.Length; // Works correctly: 0 ``` -------------------------------- ### Violation and Fix for SS013 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS013-RethrowExceptionWithoutLosingStacktrace.md The violation shows the incorrect use of 'throw e', while the fix demonstrates the correct 'throw;' syntax to maintain the stack trace. ```cs try { } catch(Exception e) { throw e; } ``` ```cs try { } catch(Exception e) { throw; } ``` -------------------------------- ### Violation of UnboundedStackalloc Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS046-UnboundedStackalloc.md Demonstrates an unbounded stack allocation that triggers the SS046 warning. ```cs var len = new Random().Next(); Span values = stackalloc int[len];"; ``` -------------------------------- ### Fix for SS017 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md A struct that correctly overrides Equals, GetHashCode, and ToString. ```cs struct X { public override bool Equals(object obj) { throw new System.NotImplementedException(); } public override int GetHashCode() { throw new System.NotImplementedException(); } public override string ToString() { throw new System.NotImplementedException(); } } ``` -------------------------------- ### Use TimeSpan Factory Methods Source: https://context7.com/vannevelj/sharpsource/llms.txt The TimeSpan constructor accepting a single integer parameter interprets the value as ticks (100 nanosecond units), not seconds. Use factory methods like TimeSpan.FromSeconds for clarity and correctness. ```csharp // Violation: creates 30 ticks = 3 microseconds, not 30 seconds var timeout = new TimeSpan(30); ``` ```csharp // Fix: use explicit factory method var timeout = TimeSpan.FromSeconds(30); ``` -------------------------------- ### Use StringBuilder for String Concatenation in Loops (C#) Source: https://context7.com/vannevelj/sharpsource/llms.txt String concatenation within loops leads to O(n^2) memory usage due to repeated string allocations. Use `StringBuilder` for efficient O(n) performance. ```csharp // Violation: O(n^2) allocations var result = ""; foreach (var item in items) { result += item.ToString(); // New string each iteration } // Fix: use StringBuilder for O(n) performance var sb = new StringBuilder(); foreach (var item in items) { sb.Append(item); } var result = sb.ToString(); ``` -------------------------------- ### SS035: SynchronousTaskWait Source: https://context7.com/vannevelj/sharpsource/llms.txt Avoid using .Wait() or .Result on tasks; use await to prevent deadlocks in UI and ASP.NET environments. ```csharp // Violation: blocks thread waiting for task async Task MyMethod() { Task.Delay(1000).Wait(); } // Fix: await asynchronously async Task MyMethod() { await Task.Delay(1000); } ``` -------------------------------- ### Identify string.Format argument mismatch Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS014-StringDotFormatWithDifferentAmountOfArguments.md This violation occurs when the number of arguments provided to string.Format is insufficient for the placeholders defined in the format string. ```cs string s = string.Format("abc {0}, def {1}", 1); ``` -------------------------------- ### Handle Elasticsearch/OpenSearch Response Errors Source: https://context7.com/vannevelj/sharpsource/llms.txt Elasticsearch and OpenSearch .NET clients require explicit checking of response objects for errors. Failure to do so can hide critical issues. ```csharp // Violation: error response discarded async Task IndexDocumentAsync() { var client = new ElasticsearchClient(); await client.IndexAsync(new MyDocument()); // Errors ignored! } ``` ```csharp // Fix: check response for errors async Task IndexDocumentAsync() { var client = new ElasticsearchClient(); var response = await client.IndexAsync(new MyDocument()); if (!response.IsValidResponse) { throw new Exception($"Indexing failed: {response.DebugInformation}"); } } ``` -------------------------------- ### Fixing Case-Insensitive String Comparison Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md This code snippet shows the recommended fix for case-insensitive string comparisons. It uses `string.Equals` with `StringComparison.OrdinalIgnoreCase` to avoid unnecessary string allocations and improve performance. ```cs using System; string s1 = string.Empty; string s2 = string.Empty; bool result = string.Equals(s1, s2, StringComparison.OrdinalIgnoreCase); ``` -------------------------------- ### Fix: Explicitly Stop Activity in Finally Block Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS062-ActivityWasNotStopped.md This code shows how to explicitly stop an activity using a `try-finally` block. The `Stop()` method is called in the `finally` block to guarantee it executes even if exceptions occur. ```cs using System.Diagnostics; class Test { private static readonly ActivitySource Source = new("Test"); void Method() { var activity = Source.StartActivity("test"); try { // Do work } finally { activity?.Stop(); } } } ``` -------------------------------- ### Violation: ThreadStatic field with initializer Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS052-ThreadStaticWithInitializer.md A field marked with [ThreadStatic] cannot contain an initializer. The initializer is only executed for the first thread. This code violates that rule. ```cs using System; using System.Threading; class MyClass { [ThreadStatic] static Random _random = new Random(); } ``` -------------------------------- ### Avoid blocking async tasks with .Wait() Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS035-SynchronousTaskWait.md Use 'await' to properly handle asynchronous operations. Blocking with .Wait() can cause deadlocks in async methods. ```cs async Task MyMethod() { Task.Delay(1).Wait(); } ``` ```cs async Task MyMethod() { await Task.Delay(1); } ``` -------------------------------- ### SS034: AccessingTaskResultWithoutAwait Source: https://context7.com/vannevelj/sharpsource/llms.txt Use await to retrieve task results to prevent potential deadlocks in synchronization contexts. ```csharp // Violation: synchronous blocking on async result async Task ProcessAsync() { var data = FetchDataAsync().Result; // Can deadlock } // Fix: await the task async Task ProcessAsync() { var data = await FetchDataAsync(); } ``` -------------------------------- ### Violation of SS017 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS017-StructWithoutElementaryMethodsOverridden.md A struct that fails to override the required elementary methods. ```cs struct X { } ``` -------------------------------- ### Fix for SS050 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS050-ParameterAssignedInConstructor.md Corrected implementation where the class property is assigned the value of the constructor parameter. ```cs class Test { int Count { get; set; } Test(int count) { Count = count; } } ``` -------------------------------- ### Violation: Creating ImmutableArray with 'new' Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS061-ImmutableCollectionCreatedIncorrectly.md Using 'new ImmutableArray()' creates an uninitialized struct, which can cause runtime exceptions. Always use factory methods like ImmutableArray.Create(). ```csharp var array = new ImmutableArray(); ``` -------------------------------- ### SS032: ThreadSleepInAsyncMethod Source: https://context7.com/vannevelj/sharpsource/llms.txt Use await Task.Delay() instead of Thread.Sleep() in async methods to prevent blocking the thread. ```csharp // Violation: blocks thread in async context async Task MyMethod() { Thread.Sleep(5000); } // Fix: use async delay async Task MyMethod() { await Task.Delay(5000); } ``` -------------------------------- ### SS001: AsyncMethodWithVoidReturnType Source: https://context7.com/vannevelj/sharpsource/llms.txt Async methods should return Task instead of void to ensure proper exception handling and awaitability. ```csharp // Violation: async void prevents awaiting and loses exceptions async void WriteFile() { await File.WriteAllTextAsync("c:/temp/file.txt", "content"); } // Fix: return Task to enable proper async patterns async Task WriteFile() { await File.WriteAllTextAsync("c:/temp/file.txt", "content"); } ``` -------------------------------- ### Violation of SS048 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS048-LockingOnDiscouragedObject.md Demonstrates the use of discouraged types like Type, string, and 'this' within a lock statement. ```cs class Test { private Type _badLock1 = default; private string _badLock2 = default; void Method() { lock (_badLock1) { } lock (_badLock2) { } lock (this) { } } } ``` -------------------------------- ### Violation of SS055 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS055-MultipleOrderByCalls.md Demonstrates the incorrect usage where the first OrderBy call is overridden by the second. ```cs record Data(int X, int Y); var data = new Data[] { new(1, 3), new(1, 4), new Data(2, 3), new(2, 1), new(1, 1) }; var ordered = data.OrderBy(obj => obj.X).OrderBy(obj => obj.Y); ``` -------------------------------- ### Implement Equals() without GetHashCode() Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS005-EqualsAndGetHashcodeNotImplementedTogether.md This violation occurs when Equals() is overridden but GetHashCode() is not. Implement both to ensure consistent behavior. ```cs class MyClass { public override bool Equals(object obj) { throw new System.NotImplementedException(); } } ``` -------------------------------- ### Avoid Awaiting ValueTask Multiple Times in C# Source: https://context7.com/vannevelj/sharpsource/llms.txt A `ValueTask` can only be awaited once. Awaiting it multiple times leads to undefined behavior. Store the result or convert to `Task` if multiple accesses are needed. ```csharp // Violation: awaiting ValueTask twice async Task ProcessAsync() { var task = GetValueTaskAsync(); await task; await task; // Undefined behavior! } // Fix: store result or convert to Task async Task ProcessAsync() { var task = GetValueTaskAsync(); var result = await task; // Use result multiple times, not the task } ``` -------------------------------- ### Source-generated logging fix Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS065-LoggerMessageAttribute.md Refactored code using the LoggerMessage attribute to implement high-performance logging. ```cs public partial class MyService { private readonly ILogger _logger; public MyService(ILogger logger) { _logger = logger; } public void DoWork(string userId) { LogUserStartedWork(userId); } [LoggerMessage(Level = LogLevel.Information, Message = "User {UserId} started work")] private partial void LogUserStartedWork(string userId); } ``` -------------------------------- ### Unnecessary Enumerable Materialization Fix Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS041-UnnecessaryEnumerableMaterialization.md Corrected version of the code that removes the unnecessary ToList() call to allow deferred execution. ```cs using System.Linq; using System.Collections.Generic; IEnumerable values = new [] { "test" }; values.Take(1); ``` -------------------------------- ### Attribute definition violation and fix Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS044-AttributeMustSpecifyAttributeUsage.md Shows the violation of a missing AttributeUsage and the corrected implementation. ```cs class MyAttribute : Attribute { } ``` ```cs [AttributeUsage(AttributeTargets.All, AllowMultiple = false)] class MyAttribute : Attribute { } ``` -------------------------------- ### Violation: Exception Thrown From Dispose Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS027-ExceptionThrownFromDispose.md This code demonstrates a violation where an ArgumentException is thrown from the Dispose method of an IDisposable object. This can disrupt the normal flow of resource cleanup. ```cs public class MyClass : IDisposable { public void Dispose() { throw new ArgumentException(); } } ``` -------------------------------- ### Apply Filters Before Traversal in LINQ Source: https://context7.com/vannevelj/sharpsource/llms.txt Apply Where filters before expensive traversal operations like OrderBy or Select to process fewer items. This optimization improves query performance by reducing the dataset early. ```csharp // Violation: sorts all items before filtering var result = users .OrderBy(u => u.Name) // Sorts 1000 users .Where(u => u.IsActive); // Then filters to 10 // Fix: filter first to reduce work var result = users .Where(u => u.IsActive) // Filters to 10 users .OrderBy(u => u.Name); // Sorts only 10 ``` -------------------------------- ### Violation: Static Field Accessed Before Initialization in C# Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS045-StaticInitializerAccessedBeforeInitialization.md This C# code demonstrates a violation where 'FirstField' attempts to access 'SecondField' before 'SecondField' is initialized. Static fields are initialized in order of appearance. ```csharp class Test { public static int FirstField = SecondField; private static int SecondField = 5; } ``` -------------------------------- ### Use ThenBy for Secondary Sorting Criteria Source: https://context7.com/vannevelj/sharpsource/llms.txt Successive OrderBy() calls override previous sorting. Use ThenBy() for secondary sort criteria to achieve multi-level sorting. ```csharp // Violation: second OrderBy replaces first var sorted = data .OrderBy(x => x.LastName) .OrderBy(x => x.FirstName); // Only sorts by FirstName! // Fix: use ThenBy for secondary sort var sorted = data .OrderBy(x => x.LastName) .ThenBy(x => x.FirstName); // Sorts by LastName, then FirstName ``` -------------------------------- ### Use Wrapper Type for Multiple FromBody Parameters Source: https://context7.com/vannevelj/sharpsource/llms.txt Web API actions can only deserialize one [FromBody] parameter. Use a wrapper type to combine multiple parameters into a single [FromBody] object to avoid runtime binding failures. ```csharp // Violation: only one FromBody allowed [HttpPost] public IActionResult Create([FromBody] User user, [FromBody] Settings settings) { return Ok(); } // Fix: use a wrapper type public record CreateRequest(User User, Settings Settings); [HttpPost] public IActionResult Create([FromBody] CreateRequest request) { return Ok(); } ``` -------------------------------- ### Violation of ConcurrentDictionary emptiness check Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS060-ConcurrentDictionaryEmptyCheck.md Demonstrates the inefficient use of .Count == 0, which causes a global lock on the dictionary. ```cs using System.Collections.Concurrent; var dic = new ConcurrentDictionary(); var empty = dic.Count == 0; ``` -------------------------------- ### Switch Statement with Default Label (Fix) Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md This C# code shows the corrected version of the switch statement, now including a 'default' label. This ensures that any unhandled cases, including future enum additions, are explicitly managed, here by throwing an exception. ```csharp var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; default: throw new ArgumentException("Unsupported value"); } enum MyEnum { Fizz, Buzz, FizzBuzz } ``` -------------------------------- ### Violation and Fix for SS051 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS051-LockingOnMutableReference.md Shows the problematic mutable lock field and the corrected readonly version. ```cs class Test { private object _lock = new object(); } ``` ```cs class Test { private readonly object _lock = new object(); } ``` -------------------------------- ### Identify ThrowNull violation in C# Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS006-ThrowNull.md This snippet demonstrates a violation where null is explicitly thrown, leading to a runtime exception. ```cs void Method() { throw null; } ``` -------------------------------- ### C# Exception in Finalizer Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS028-ExceptionThrownFromFinalizer.md Avoid throwing exceptions from finalizer methods. This violation demonstrates throwing an `ArgumentException` in a finalizer. ```csharp public class MyClass { ~MyClass() { throw new ArgumentException(); } } ``` -------------------------------- ### Use IsEmpty for ConcurrentDictionary Check in C# Source: https://context7.com/vannevelj/sharpsource/llms.txt Prefer `IsEmpty` over `Count == 0` for checking if a `ConcurrentDictionary` is empty. `Count` acquires internal locks, while `IsEmpty` is a lock-free operation. ```csharp // Violation: acquires all internal locks var dict = new ConcurrentDictionary(); if (dict.Count == 0) { } // Fix: lock-free check if (dict.IsEmpty) { } ``` -------------------------------- ### Identify and Fix Unnecessary ToString on Span Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS064-UnnecessaryToStringOnSpan.md Demonstrates the violation of calling ToString() on a span and the corrected version using the span-accepting overload. ```cs ReadOnlySpan span = "hello world".AsSpan(); Console.WriteLine(span.ToString()); ``` ```cs ReadOnlySpan span = "hello world".AsSpan(); Console.WriteLine(span); ``` -------------------------------- ### Defer Enumerable Materialization Source: https://context7.com/vannevelj/sharpsource/llms.txt Avoid unnecessary materialization of enumerables using ToList() or ToArray() when the result is immediately enumerated by deferred LINQ operations. Defer execution to improve performance. ```csharp // Violation: unnecessary allocation IEnumerable users = GetUsers(); var activeUsers = users.ToList().Where(u => u.IsActive).Take(10); // Fix: defer execution IEnumerable users = GetUsers(); var activeUsers = users.Where(u => u.IsActive).Take(10); ``` -------------------------------- ### Fix: OnPropertyChanged with nameof() Operator Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS011-OnPropertyChangedWithoutNameofOperator.md This code demonstrates the fix for SS011 by using the nameof(IsEnabled) operator. This ensures that the correct property name is passed to OnPropertyChanged, preventing divergence. ```csharp class MyClass : INotifyPropertyChanged { private bool _isEnabled; public bool IsEnabled { get { return _isEnabled; } set { _isEnabled = value; OnPropertyChanged(nameof(IsEnabled)); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if(handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } ``` -------------------------------- ### Violation: [ThreadStatic] on Instance Field Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS042-InstanceFieldWithThreadStatic.md This code demonstrates the incorrect usage of the [ThreadStatic] attribute on an instance field. The attribute will have no effect, and thread-specific behavior will not be achieved. ```csharp class MyClass { [ThreadStatic] int _field; } ``` -------------------------------- ### Avoid Modifying Collections During Traversal in C# Source: https://context7.com/vannevelj/sharpsource/llms.txt Modifying a collection while iterating over it using `foreach` throws `InvalidOperationException`. Use `RemoveAll` or iterate backward with a `for` loop to avoid this. ```csharp // Violation: modifying during foreach foreach (var item in items) { if (item.ShouldRemove) items.Remove(item); // Throws InvalidOperationException } // Fix: iterate over a copy or use RemoveAll items.RemoveAll(item => item.ShouldRemove); // Or iterate backwards with for loop for (int i = items.Count - 1; i >= 0; i--) { if (items[i].ShouldRemove) items.RemoveAt(i); } ``` -------------------------------- ### C# Method Missing Test Attribute Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS021-TestMethodWithoutTestAttribute.md A method within a `[TestClass]` is missing a test attribute (e.g., `[TestMethod]`). Ensure all testable methods are decorated with the correct attribute to be included in test runs. ```csharp using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] class MyClass { public void MyMethod() { } } ``` -------------------------------- ### Switch Statement Missing Default Label (Violation) Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS019-SwitchIsMissingDefaultLabel.md This C# code demonstrates a switch statement where the 'default' label is missing. This can lead to unhandled cases if the enum 'MyEnum' is extended or if an unexpected value is assigned. ```csharp var e = MyEnum.Fizz; switch (e) { case MyEnum.Fizz: case MyEnum.Buzz: break; } enum MyEnum { Fizz, Buzz, FizzBuzz } ``` -------------------------------- ### Violating Case-Insensitive String Comparison Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS049-ComparingStringsWithoutStringComparison.md This code snippet demonstrates a violation by using `ToLower()` on strings before comparison, which allocates new string objects. This approach is less efficient than using `string.Equals` with `StringComparison.OrdinalIgnoreCase`. ```cs using System; string s1 = string.Empty; string s2 = string.Empty; bool result = s1.ToLower() == s2.ToLower(); ``` -------------------------------- ### Fix for SS007 in C# Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS007-FlagsEnumValuesAreNotPowersOfTwo.md Corrected version of the enum where 'Buz' is defined as a bitwise OR expression of existing members. ```cs using System; [Flags] enum Foo { Bar = 0, Biz = 1, Baz = 2, Buz = Biz | Baz, Boz = 4 } ``` -------------------------------- ### Violation: Missing Equals and GetHashcode in Collection Item Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS004-ElementaryMethodsOfTypeInCollectionNotOverridden.md This code demonstrates a violation where a custom type 'MyCollectionItem' is used in a List without overriding Equals() and GetHashcode(). Consequently, 'list.Contains(default)' will perform a reference equality check, potentially failing to find the item if it's not the exact same instance. ```cs class MyCollectionItem { } var list = new List(); var s = list.Contains(default); ``` -------------------------------- ### Violation: Test method without public modifier Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS020-TestMethodWithoutPublicModifier.md This code demonstrates a test method with an 'internal' modifier, which may not be discoverable by all test frameworks. Ensure test methods are public for broader compatibility. ```csharp using NUnit.Framework; [TestFixture] public class MyClass { [Test] internal void Method() { } } ``` -------------------------------- ### Inefficient LINQ Query: Traversal Before Filter Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS047-LinqTraversalBeforeFilter.md Use this pattern when you have an IEnumerable collection and want to filter it. Ensure the Where clause is applied before traversal methods like OrderBy to optimize performance. ```cs var users = GetUsers(); users.OrderBy(x => x.Age).Where(x => x.IsEnabled); ``` -------------------------------- ### Fix: Test method with public modifier Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS020-TestMethodWithoutPublicModifier.md This code shows the corrected version where the test method has the 'public' modifier, ensuring it is discoverable by xUnit, NUnit, and MSTest. ```csharp using NUnit.Framework; [TestFixture] public class MyClass { [Test] public void Method() { } } ``` -------------------------------- ### Suppress SharpSource Analyzers with Attribute Source: https://context7.com/vannevelj/sharpsource/llms.txt Analyzer suppressions can be applied at the method or class level using the System.Diagnostics.CodeAnalysis.SuppressMessage attribute. ```csharp // Suppress with attribute [System.Diagnostics.CodeAnalysis.SuppressMessage("SharpSource", "SS037")] public HttpClient CreateClient() => new HttpClient(); ``` -------------------------------- ### Dispose Owned Disposable Fields in C# Source: https://context7.com/vannevelj/sharpsource/llms.txt Ensure that disposable fields owned by a type are properly disposed within the type's `Dispose` method to prevent resource leaks. Implement `IDisposable` and call `Dispose()` on owned resources. ```csharp // Violation: owned disposable not disposed class DataProcessor : IDisposable { private readonly MemoryStream _stream = new(); public void Dispose() { } // _stream leaked! } // Fix: dispose owned resources class DataProcessor : IDisposable { private readonly MemoryStream _stream = new(); public void Dispose() { _stream.Dispose(); } } ``` -------------------------------- ### Suppress SharpSource Analyzers Inline Source: https://context7.com/vannevelj/sharpsource/llms.txt Individual code lines or blocks can suppress specific SharpSource analyzer warnings using the #pragma warning directive. Ensure to restore the warning state afterwards. ```csharp // Suppress inline #pragma warning disable SS037 var client = new HttpClient(); #pragma warning restore SS037 ``` -------------------------------- ### Fix for SS018 Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS018-SwitchDoesNotHandleAllEnumOptions.md The corrected switch statement explicitly handling the missing enum member. ```cs var e = MyEnum.Fizz; switch (e) { case MyEnum.FizzBuzz: throw new System.NotImplementedException(); case MyEnum.Fizz: case MyEnum.Buzz: break; } enum MyEnum { Fizz, Buzz, FizzBuzz } ``` -------------------------------- ### Fix: Dispose Disposable Field Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS066-DisposableFieldIsNotDisposed.md This code shows the corrected version where the MemoryStream field is properly disposed of within the Dispose method. ```cs using System; using System.IO; class Test : IDisposable { private readonly MemoryStream _stream = new(); public void Dispose() { _stream.Dispose(); } } ``` -------------------------------- ### Avoid Storing HttpContext in Fields Source: https://context7.com/vannevelj/sharpsource/llms.txt Do not store HttpContext in fields as it is request-scoped. Use IHttpContextAccessor to access the current HttpContext safely, preventing stale context issues. ```csharp // Violation: storing request-scoped context class MyService { private HttpContext _context; // Will be invalid after request ends public void SetContext(HttpContext context) => _context = context; } ``` ```csharp // Fix: use IHttpContextAccessor class MyService { private readonly IHttpContextAccessor _contextAccessor; public MyService(IHttpContextAccessor contextAccessor) { _contextAccessor = contextAccessor; } public HttpContext Context => _contextAccessor.HttpContext; } ``` -------------------------------- ### C# - Unused result of string operation Source: https://github.com/vannevelj/sharpsource/blob/master/docs/SS040-UnusedResultOnImmutableObject.md Avoid calling methods on immutable objects like strings if the result is not used, as it may indicate a missed operation. ```csharp void Method() { "test ".Trim(); } ```