2023
Introducing the Source Generator Toolkit
Source Generators made easier!
Sharing a common method across classes
Leverage interfaces and extension methods and to share a common method
Daily Drop wrap-up
A wrap-up on a year's worth of Daily Drop posts
EF queries on unmapped types
Introducing the ability to execute raw queries on unmapped types
ArrayPool for frequent array creation
Using ArrayPool for performant memory reuse when creating array frequently
Expression-body constructor
How to write a constructor body as an expression
Calling an async method in a constructor
Using lazy initialization to call an async method from a constructor
Case-less Dictionary keys
How to ignore the case of Dictionary keys when performing operations
LINQ lambda vs method group
Comparing lambda and method groups when using LINQ
Task.Delay accuracy
Learning about the accuracy of Task.Delay with small time frames
LINQ Any/All over Count
Use the Any or All methods instead of the Count method
Eliding await keyword
How and why the await keyword should be elided
Accurate string length
String.Length for inaccurate string length and how to get the correct length
Non-generic to generic method call
How to call into a generic method from a non-generic method
Cancelling a collection iteration
Using a CancellationToken to exit a collection iteration
Naming minimal endpoints
Naming minimal endpoints for easier link generation
Request binding with IParseable
Using IParseable to bind primitive types to more complex entities
SQL: IS DISTINCT FROM
Comparing two expressions with NULL support in SQL
Caching MVC responses
How to cache the response from an MVC controller to increase service performance
Database creation on startup
Using dependency injection to create an EF database on startup
LINQ DistinctBy
Using DistinctBy to get a unique collection of items
Efficient Stopwatch usage
New .NET 7 feature to make StopWatch usage more efficient
Combining multiple attributes
Combining multiple attributes into a single line
Converting values with EF
Converting properties when reading and writing to a database using Entity Framework
.NET 8 Exception helpers
Throwing exceptions is becoming much easier in .NET 8
2022
Entity Framework conventions
Customizing Entity Framework through the use of conventions
Holiday Break 2022
Taking a break until 2023
.NET8 Frozen collection
New Frozen collection (potentially) being introduced with .NET8
New HTTP methods
How to handle new or custom HTTP methods
EF tags and interceptors
Modifying EF generated SQL with tags and interceptors
Enum iteration
Using Enum.GetValues to iteration through enum values
Fast, potentially unsafe iteration
Using CollectionsMarshal, MemoryMarshal and Unsafe for fast looping
EF7 GroupBy support
Entity Framework 7 adds supports for GroupBy as the final operator
Unreachable code and UnreachableException
UnreachableException - the new exception which should never be thrown
Determining bytes of memory allocated
Using GetAllocatedBytesForCurrentThread to get the allocated bytes in a thread
Parse a string to anything
Parsing a string to any object type with the IParseable interface
Compiler Warning CS8981
Discovering the new C#11 compiler warning CS8981
Custom feature filters
Defining custom feature filters to selectively enable functionality
Short and arithmetic operations
How arithmetic operators convert short values when performing operations
Dynamic LINQ with System.Linq.Dynamic.Core
How System.Linq.Dynamic.Core can be used to parse strings in LINQ dynamically
Null-coalescing operator and associativity
Chaining the null-coalescing operators together
Opting into experimental functionality
Using the RequiresPreviewFeatures attribute to create preview functionality
Distributed caching int ASP.NET Core
ASP.NET Core has build in distributed caching functionality with multiple providers
Supporting 13 months
.NET has support for 13 months
Efficient EF deletion
Exploring a more efficient method to perform deletes in Entity Framework
List ConvertAll
Converting list data types with ConvertAll
Succinct initialization pattern
Succinct lazy initialization patterns with newer C# features
Local functions and attributes
Since C#9, local functions are permitted to be decorated with attributes
Builder pattern implicit conversions
Leveraging implicit conversions to make using the builder pattern easier
Foreach loops and indexes
Using a tuple to keep track of an item index in a foreach loop
String comparison with StringComparer
Using StringComparer.OrdinalIgnoreCase.Equals to compare strings instead of ToLower
List AddRange performance
Comparing the performance of the List AddRange and Add methods
Awaiting anything with GetAwaiter
Using a GetAwaiter extension method to await any type
Adding localization with dependency injection
Adding localization support to ASP.NET Core with dependency injection support
Target-type new expressions
Omitting the target-type when .NET can infer the type
List capacity and performance
How setting a Lists capacity explicitly can improve performance
Switch expression and string interpolation
Switch expressions inside string interpolation expression with C#11
Primitive obsession and Value Records
Leveraging records to assist overcoming primitive obsession
Platform specific path separator
The Path class contains platform specific characters
Generic List property wrapping
Putting a generic List property behind a class to created cleaner code
Jagged array in C#
Learning about jagged arrays in C#
SQL COALESCE uses
Having a look at a few uses of SQL COALESCE
LINQ's ToLookup method
Discovering LINQ has a ToLookup method for grouping collection items
OpenAPI documentation from XML documentation comments
How XML documentation comments can be used to populate a swagger document
File access modifier
Discovering the file access modifier in C#11
Protecting sensitive data with data protection api
Exploring the built-in C# data protection api
Using math functions on numeric types
With .NET 7 the static Math class is no longer required for math functions
Built in HTTP header properties
ASP.NET Core has built-in properties for commonly used HTTP headers
Binding query string values to an array
Automatically binding a query string value to an array
Performant deserialization with Utf8JsonReader
Using Utf8JsonReader to deserialize a JSON string (to get a specific value)
Access cache stats with MemoryCacheStatistics
Using MemoryCacheStatistics to better understand MemoryCache usage in an application
Deserializing incompatible types using JsonConverter
How to deserialize incompatible types using Newtonsoft.Json and JsonConverter
ObjectPool for resource management
Using the ObjectPool class to keep objects in memory for reuse
Primitive collection performance
Having a look at .NET 7 Linq sort updates and collection sorting performance
ReadOnlyList and runtime errors
Compile vs runtime error occurs with readonly lists
Automatic redirect on http status code
Using UseStatusCodePagesWithRedirects to automatically redirect to an error endpoint
Performant LINQ type checks
Comparing the performance of type checking items using LINQ
Culture specific strings with String.Create
Evaluating interpolated strings to a specific culture using String.Create
Manually passing parameters to a middleware component
Using manually supplied parameters in conjunction with injected parameters
Map all urls with IApplicationBuilder.Run
Leveraging the IApplicationBuilder.Run method to map all URLs to an endpoint delegate
Obtaining a list of app URLs
Using IServerAddressesFeature to get a list of URLs your app is responding to
Minimal api's and cancellation tokens
How to cancel aborted api calls with cancellation tokens
Native AOT compilation with .NET 7
Using ahead-of-time compilation for improved application startup performance and memory usage
Strongly typed middleware with IMiddleware
Using IMiddleware to ensure correctly configured middleware
dynamic, ExpandoObject and INotifyPropertyChanged
Adding a property changed event handler to a ExpandoObject object
Delaying injected dependency instantiation
Using Lazy to delay the instantiation of injected dependencies
Bulk update (and delete) in EF7
New bulk update and delete functionality coming with Entity Framework 7
Extend the middleware pipeline with IStartupFilter
Automatically extend the start or end of the middleware pipeline with IStartupFilter
Simplifying command line argument with switch mappings
Exploring switch mappings to simplify (and alias) command line arguments
Representing an external operation with TaskCompletionSource
Using TaskCompletionSource to cancel an external asynchronous operation
UTF8 string literals in C#11
How string literals are easily translated into bytes with C#11
Application lifetime events with IHostApplicationLifetime
Using IHostApplicationLifetime call back events to handle post-startup and graceful shutdown tasks
Streaming responses from a minimal api
How to use IAsyncEnumerable amd yield in a minimal api
Auto-default struct property values
Struct properties auto defaulting coming in C# 11
Correlation using the Activity class
Using the Activity class to correlate requests across distributed systems
Constructors with default values
Constructors with default values and dependency injection behavior
Delay SQL execution with WAITFOR
Using the SQL WAITFOR command to delay the execution of a SQL statement
Formatting interpolated strings
How interpolated strings can be formatted without using the ToString method
.NET 7 API output caching
An introduction into output caching coming with .NET 7
Dynamic EF operations with EF.Property
Using EF.Property to dynamically reference entity properties using a string
Performing a ping programmatically
C# has a Ping class which enables Ping operations programmatically
nameof enhancement in C# 11
A look into C# 11 enhancement to the nameof expression
Dispose vs Exception handling
Exploring the sequence of event when using a disposable class inside a try-catch block
.NET 7 Rate limiting
An introduction into rate limiting coming with .NET 7
Entity Framework: IQueryable vs IEnumerable
How different collection types impact Entity Framework queries
Namespace-less types
Reference types without a namespace and handling naming conflicts
Constructor out parameters
A constructor can contain out and ref parameters
Delimit an array with ArraySegment
Using ArraySegment to represent only a portion of a larger array
Route handler filters in .NET 7
Learning about minimal api route handler filters coming in .NET 7
Override vs New behavior
A look into polymorphism with override and new and their differing behavior
Unsafe cast for performance
Performing unsafe casts for performance improvements
Filter IEnumerable with OfType
LINQ has a built in method to automatically filter a collection by a specific Type
Combining enum values
Using bit flags to combine enum values to simplify code
Parallel processing with ParallelEnumerable
Built in Linq parallel processing with ParallelEnumerable
Pub/Sub with Redis
Redis has pub/sub functionality in addition to being a key/value database
Complex Pattern Matching
Pattern matching can contain IS, NOT, AND and OR keywords for more complex statements
Modifying configuration on load
How configuration can be modified on load but still leverage the Options pattern
OS information via Runtime.InteropServices
Levering Runtime.InteropServices to execute OS specific functionality
An intro to SQL SELECT-OVER
How the SQL SELECT-OVER clause can be used to simplify t-sql statements
HashiCorp Vault with C#
A step by step guide to integrating into HashiCorp vault with C#
Accurate, regular scheduling with PeriodicTimer
Using PeriodicTimer to build an accurate, reliable background service
String null or empty using pattern matching
Leveraging pattern matching instead of string.IsNullOrEmpty - with performance benchmarks!
Windows services with .NET Core
Configuring a background service to run as a Windows Service
Dynamically changing minimal api return type
Changing minimal api return content types dynamically (including to xml)
String interpolation with alignment
String interpolation provides a mechanism to align (and pad) interpolated values
ActivatorUtilities to create instances
The ActivatorUtilities class can be used to create instances of classes, in conjunction with DI
Readonly parameters with the in modifier
C# has a lesser used in parameter modifier which prevents parameter value modification
Deconstructing a class instance into multiple variables
Investigating how a class instance can be easily deconstructed into multiple variables
Multiple applications - one host
How multiple applications can be run in a single ASPNET Core host with minimal api
Null forgiving operator
Suppressing compiler null reference warnings with the null forgiving operator
IEnumerable's lazy evaluation
Defer execution of IEnumerable returning methods until iteration
Environment specific startup Configure methods
How environment specific named Configure methods can be used during startup
Exploring the new required properties
Learning about the new required keyword potentially coming with C#11
Configuration from memory with AddJsonStream
Using AddJsonStream to load configuration in a unit test
SQL wildcard characters
Diving into the SQL wildcard characters (beyond %)
nameof usage for better code quality
How the nameof operator can be leveraged to produce cleaner, less error prone code
Tuples for class value equality
Using a tuple to check the equality of two class instances
Unit testing a protected method
How to unit test a protected method on a class
Entity Framework DbContext Pooling
Using DbContext pooling to improve the performance of aan application
Visual Studio Schema Compare
Comparing two database schemas using Visual Studio Schema Compare feature
MaybeNullWhen attribute usage
How the MaybeNullWhen attribute can be used to give more information to the compiler about your code
Expanding on an property initializer
Adding additional values to a Dictionary property initializer
For loop lowering in C#
Discovering how C# lowers for a loop to a while loop
Type conversion with the implicit operator
How the implicit operator can be used to convert one type to another easily
T-SQL enhancements in SQL Server 2022
Exploring some of the more useful T-SQL enhancement coming with SQL Server 2022
View config values with GetDebugView
Use GetDebugView to view all configuration values
EF Find vs First performance
Comparing the performance of Entity Framework's Find and First methods
Keyset Pagination (vs Offset pagination)
Exploring keyset pagination in SQL Server
Multiple statements in a for loop
A for loop can contain multiple statements in the iterator section
CSS property: all
Using the CSS all property to reset all element properties
Destructing a Dictionary record into a Tuple
A Dictionary key-value pair can be destructed into a Tuple
Lambda vs local function performance
Exploring the performance of a lambda function vs a local function
Method currying basics in C#
A simple introduction to method currying in C#
Visual Studio layouts
Customizing and switching between Visual Studio layouts
Converting ExpandObject
How ExpandObject can be converted to IEnumerable and a Dictionary
TryAddEnumerable to configure dependency injection
How TryAddEnumerable operates differently to the other DI methods
Binary and hexadecimal conversion
Using the Convert class to convert a integer to binary or hexadecimal
Sortable Guids using NewId
How sortable, but unique, Guids can be generated using the NewId library
The cost of Nullable variables
Nullable variables are a useful feature, but come with a performance cost
Creating objects without calling the constructor
Using GetUninitializedObject to create objects without calling the object constructor
Indexers with multiple arguments
Writing custom indexers which accept multiple arguments
Lambda chaining in C#
Lambda Action's can be changed together in a single handle
Using XML documentation comments to enrich code
How XML documentation features can use to enhance the usability of code
Binding a query parameter to an object
Exploring binding a query parameter to an endpoint object parameter
Viewing collections with IEnumerable Visualizer
How to easily view .NET collections with IEnumerable Debugger Visualizer
AllowNull and DisallowNull attributes
Exploring the usage of the AllowNull and DisallowNull attributes
IEnumerable performance cost
Exploring the cost of virtualization with IEnumerable
Optional parameters in minimal apis
How to to send optional query string parameters to a minimal api
EF Core INSERT vs MERGE
Entity Framework Core will use MERGE instead of INSERT under certain conditions
Listing all ASP.NET Core routes
How to display access and display all routes in an ASP.NET application
Generic attributes with C#11
Starting with C# 11 attributes can now contain generic parameters
LINQ First and Single performance
Investigating LINQ performance when retrieving a single item from a enumeration
Raw string literals in .NET7
Exploring the useful .NET7 raw string literal feature
IEnumerable count without enumeration
How to (possibility) get an IEnumerable count with TryGetNonEnumeratedCount
Introduction to the SQL MERGE
An introduction to the SQL MERGE statement
Value type default values
Understanding the default value for a value type
Flags attribute for enums
Using the Flags attribute to treat an enum as a set of flags
Visual Studio Code snippets
Having a look at some of the code snippets shipped with Visual Studio
Creating temporary files in .NET
Exploring the built-in temporary file creator
Anonymous type property name inference
How anonymous types can infer property names from variable names
Static constructors in C#
Exploring the behavior of static constructors in C#
Catering for big numbers with BigInteger
How to work with integer values great than int.MaxValue with BigInteger
Controller FromServices change in .NET 7
How the FromServices requirement for controllers is changing in.NET 7
Rectangle text selection in Visual Studio
How and why the rectangular text selection is useful
checked and unchecked keywords
Using the checked and unchecked keywords to control overflow checking
Creating a deterministic guid
How to create a deterministic guid from a string
Error and warning preprocessor directives
Generate user-defined compiler error and warnings with preprocessor directives
Multi-statement line breakpoints
How to create breakpoints on part of a multi-statement line
Capture exception state
Using ExceptionDispatchInfo to capture exception state
Environment.FailFast
How FailFast can be used to skip the finally block
Index initializer behavior
How different collection initialization styles behavior differs
Attributes on lambda methods
Applying method attributes to lambda methods
Sealed class performance
Improve performance by making classes sealed
Using throw expressions in C#
What are throw expression, and how and when can they be used?
Separating pinned documents
Pinned documents in Visual Studio can be separated for better organization
Soft deletes with EF global filters
How EF Core global filters can be used to simplify soft deletes
Goto and switch statements
Using goto statements with switch statements
String interning in C#
How interning reuses memory for strings of same value
Line breaks in string interpolation
Line breaks allowed in interpolation expressions with C#11
Creating a task in a task
Exploring what happens when creating a task from within a task
Chaining null-coalescing operator
Looking into how the null-coalescing operator can be chained together
Executing code before Main
Exploring the ways code can be execute before the Main method is called
Accessing private variables
In certain scenarios private variables can be accessed externally
Using Partitioner to improve parallel processing
How chunking parallel tasks with Partitioner can improve performance
Creating scopes with braces
Creating scopes with braces without any statements
ConcurrentDictionary AddOrUpdate method
ConcurrentDictionary (unlike Dictionary) has a useful AddOrUpdate method
Exploring the new list pattern
Exploring the new list and slice pattern coming with C# 11
Setting readonly variable using init
Readonly variable can be set using an init only setter
Managing multi-thread access with ReaderWriterLockSlim
Using ReaderWriterLockSlim to allow concurrent reading but exclusive writing
Interlocked vs using the lock keyword
How InterLocked can simplify the lock process in certain cases
Linked Lists in C#
Having a look at C#'s built in link list implementation
Cancel a task with OperationCanceledException
Why the OperationCanceledException should be used over a soft cancellation
Anonymous types and with keyword
Using the with keyword to support non-destructive mutations on anonymous types
Conditional attribute to exclude method execution
The Conditional attribute can be used to conditionally execute a method
Using underscore as a digit separator
Underscores can be used a digit separator on numeric literals for ease of reading
StringSyntaxAttribute for syntax highlighting
Leverage the new StringSyntaxAttribute to enhance the developer experience
Null checking with the is keyword
Why you should do null checking with is keyword instead of ==
Indices and ranges
Using indices and ranges for succinct syntax when working with sequences
Using Func<> as an intermediary
How Func or Action can be used as an intermediary when calling methods
ArgumentNullException improvements
How its becoming easier to throw argument null exceptions
Covariance and Contravariance in C#
Covariance and Contravariance in C# explained with examples
Using SQL Server's OFFSET and FETCH
Using SQL Server's built in functionality to limit the number of rows returned
Closures explained
What is a closure, and how does it work?
Private variables prefixed with underscore?
Why is the convention that private variables should start with an underscore?
Enum validity with IsDefined
Check the validity of an enum with with the IsDefined method
Evolution of multi case switch statements
Various ways of handling multiple case switch expressions in C#
Duck typing in C#
What is duck typing and how does it work in C#?
Lazy loading objects with Lazy<>
Defer the loading of large objects until require with Lazy<>
Customize debugger class display
Customize how classes are displayed when debugger
Dependency Injection with Func and delegates
Injecting a Func or Delegate using dependency injection
Incremental source generators
Generate code, to be used in code, to generate additional code
Enumeration on a custom class
How to make a custom class enumerable (work with foreach)
Optional method parameters
Use the Optional attribute to make parameters optional
System.Text.Json notifications
Exploring the new .NET6 Json notifications
EF Core 6 column order
Manually order columns in EF Core 6
LINQ improvements - FirstOrDefault defaults
Exploring the FirstOfDefault improvements introduced in .NET6
Entity Framework Core interceptors
Query interception with Entity Framework Core interceptors
Indexers - access a class as an array
How to extend a class so that it can be accessed as an array
Customize source generator output location
How to emit source generated files to be included in source control
EF Core 6 EntityTypeConfiguration Attribute
Discover the new EntityTypeConfiguration attribute added in EF Core 6
Garbage collection configuration
The .NET garbage collector can be configured at runtime
Using with IDisposable
Use using by implementing a single interface
Task.WaitAsync in .NET6
Exploring the new WaitAsync method introduced in .NET6
Aliases with global using directives
Create an alias with C#10 global usings
Filtering try-catch statement
Apply filtering to catch statements with a when clause
Extract calling method metadata with C#
Extract useful information from a calling method
C# Channels - Produce & Consume data
A thread-safe feature for producing and consumer data
Performant logging with LoggerMessageAttribute
How to leverage LoggerMessageAttribute for a highly performant logging solution
Scheduling with GitHub Actions
How to schedule a GitHub Action
C# ValueTuple
Exploring the C# ValueTuple type
EF Core 6: GroupBy enhancements
Improvements made to the Entity Framework Core 6 GroupBy functionality
Use IOptions<> for application configuration
Use IOptions for configuration and leverage the additional available interfaces
C# Records - the rundown
Not sure what records are? Here's the quick rundown
Use the ILogger IsEnabled method
More effective memory usage using ILogger.IsEnabled
Structured logging - an introduction
An introduction to what, why and how of structured logging using Serilog
Git workflows - explained
Git Flow? GitHub Flow? Flows? This post explains and compares various Git workflows
Azure Devops Symbol Server - a how to guide
A guide to using an Azure Devops Symbol Server
2021
Dynamic Context (for Entity Framework Core)
A guide to returning projected, anonymous and simple type values dynamically
Roslyn Analyzer - tips and tricks (Part 5)
A collection of tips and tricks for writing analyzers
Roslyn Analyzer - testing an analyzer and code fix (Part 4)
A step by step guide to testing an analyzer and code fix
Roslyn Analyzer - writing the code fix (Part 3)
A step by step guide to writing an analyzer code fix
Roslyn Analyzer - writing the analyzer (Part 2)
A step by step guide to writing an analyzer
Roslyn Analyzer - explained (Part 1)
An introduction to Roslyn Analyzers, what they are and how they are useful
Multiple implementations of same interface - the options
Different methods of registering the same interface with multiple implementations using .NET dependency injection
Useful Visual Studio keyboard shortcuts
Be up to 20% more productive!
C# String vs string
Which to use? Does it matter?