How to Use the Latest C# Features on Older .NET Frameworks with PolySharp

Shamil Jauffer
Dev Genius
Published in
2 min readJan 16, 2023

--

A developer assigned to work on a legacy .net application may face many challenges. The main challenge is to understand the codebase that lacks modern C# language features. This will definitely make the code hard to maintain. Further, the developer may not be able to apply modern C# language features and best practices to improve the quality and the maintainability of the application. The developer’s familiarity with more efficient and modern ways of solving problems that will no longer be valid while working with the legacy application.

In a nutshell this can make the life of a developer a living hell.

Fret no more. There’s PolySharp!

PolySharp is a tool that generates source-only polyfills for C# language features, allowing developers to use the latest language features in older versions of the .NET framework without the need for binary dependencies. This can help improve the maintainability and compatibility of codebases.

First, install the PolySharp.Core NuGet package in your project.

Then, use the Polyfill attribute on a method that implements the functionality of the latest C# language feature you want to use.

For example, let’s use the C# 9 init property feature, this allows you to assign a value to a property at the time it’s declared.

[Polyfill]
public class Person
{
public string Name { get; init; } = "default name";
}

Then use the init property as you would in C# 9:

var  person = new Person { Name = "Noha" };

That’s it. You can use the command dotnet polysharp to generate the polyfill.

Note: PolySharp is not an official Microsoft product, it is only a community tool. From time to time there can be bugs and its always recommended to test the code generated.

--

--

Tech content creator. An experienced engineer with specialization in Architecture, Cloud, DevOps, .Net, and Angular