Does C# 8 support the .NET Framework? - c#

In Visual Studio 2019 Advanced Build settings, C# 8 does not appear to be available for a .NET Framework project, only (as in the picture below) for a .NET Core 3.0 project:
Does C# 8 support the .NET Framework?

Yes, C# 8 can be used with the .NET Framework and other targets older than .NET Core 3.0/.NET Standard 2.1 in Visual Studio 2019 (or older versions of Visual Studio if you install a NuGet package).
The only thing required is to set language version to 8.0 in the csproj file. You can also do this in Directory.Build.props to apply it to all projects in your solution. Read below for how to do this in Visual Studio 2019, version 16.3 and newer.
Most - but not all - features are available whichever framework is targeted.
Features that work
The following features are syntax changes only; they work regardless of framework:
Static local functions
Using declarations
Null-coalescing assignment
Readonly members
Disposable ref structs
Positional patterns
Tuple patterns
Switch expressions
Nullable reference types are also supported, but the new nullable attributes required to design the more complex nullable use cases are not. I cover this in more detail further down in the "gory details" section.
Features that can be made to work
These require new types which are not in the .NET Framework. They can only be used in conjunction with "polyfill" NuGet packages or code files:
Asynchronous streams - Microsoft.Bcl.AsyncInterfaces
Indices and ranges
Default interface members - do not, cannot, and never will work
Default interface members won't compile under .NET Framework and will never work because they require runtime changes in the CLR. The .NET CLR is now frozen as .NET Core is now the way forward.
For more information on what does and doesn't work, and on possible polyfills, see Stuart Lang's article, C# 8.0 and .NET Standard 2.0 - Doing Unsupported Things.
Code
The following C# project targetting .NET Framework 4.8 and using C# 8 nullable reference types compiles in Visual Studio 16.2.0. I created it by choosing the .NET Standard Class Library template and then editing it to target .NET Framework instead:
.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net48</TargetFrameworks>
<LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
.cs:
namespace ClassLibrary1
{
public class Class1
{
public string? NullableString { get; set; }
}
}
I then tried a .NET Framework 4.5.2 WinForms project, using a legacy .csproj format, and added the same nullable reference type property. I changed the language type in the Visual Studio Advanced Build settings dialog (disabled in 16.3) to latest and saved the project. Of course as this point it doesn't build. I opened the project file in a text editor and changed latest to preview in the build configuration PropertyGroup:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<LangVersion>preview</LangVersion>
I then enabled support for nullable reference types by adding <Nullable>enable</Nullable> to the main PropertyGroup:
<PropertyGroup>
<Nullable>enable</Nullable>
I reloaded the project, and it builds.
Visual Studio 2019
There has been a major change in the RTM version of Visual Studio 2019 version 16.3, the launch version for C# 8.0: the language selection dropdown has been disabled:
Microsoft's rationale for this is:
Moving forward, ... each version of each framework will have a single
supported and default version, and we won't support arbitrary
versions. To reflect this change in support, this commit permanently
disables the language version combo box and adds a link to a document
explaining the change.
The document which opens is C# language versioning. This lists C# 8.0 as the default language for .NET Core 3.x ONLY. It also confirms that each version of each framework will, going forward, have a single supported and default version and that the framework-agnosticism of the language can no longer be relied on.
The language version can still be forced to 8 for .NET Framework projects by editing the .csproj file.
The gory details
When this answer was first written, C# 8 was in preview and a lot of detective work was involved. I leave that information here for posterity. Feel free to skip it if you don't need to know all the gory details.
The C# language has historically been mostly framework neutral - i.e. able to compile older versions of the Framework - although some features have required new types or CLR support.
Most C# enthusiasts will have read the blog entry Building C# 8.0 by Mads Torgersen, which explains that certain features of C# 8 have platform dependencies:
Async streams, indexers and ranges all rely on new framework types
that will be part of .NET Standard 2.1... .NET Core 3.0 as well as
Xamarin, Unity and Mono will all implement .NET Standard 2.1, but .NET
Framework 4.8 will not. This means that the types required to use
these features won’t be available on .NET Framework 4.8.
This looks a bit like Value Tuples which were introduced in C# 7. That feature required new types - the ValueTuple structures - which were not available in NET Framework versions below 4.7 or .NET Standard older than 2.0. However, C# 7 could still be used in older versions of .NET, either without value tuples or with them by installing the System.ValueTuple Nuget package. Visual Studio understood this, and all was fine with the world.
However, Mads also wrote:
For this reason, using C# 8.0 is only supported on platforms that implement .NET Standard 2.1.
...which if true would have ruled out using C# 8 with any version of the .NET Framework, and indeed even in .NET Standard 2.0 libraries which only recently we were encouraged to use as a baseline target for library code. You wouldn't even be able to use it with .NET Core versions older than 3.0 as they too only support .NET Standard 2.0.
The investigation was on! -
Jon Skeet has an alpha version of Noda-Time using C# 8 ready to go which targets .NET Standard 2.0 only. He is clearly expecting C# 8/.NET Standard 2.0 to support all frameworks in the .NET family. (See also Jon's blog post "First steps with nullable reference types").
Microsoft employees have been discussing the Visual Studio UI for C# 8 nullable reference types on GitHub, and it is stated that they intend to support the legacy csproj (pre-.NET Core SDK format csproj). This is a very strong indication that C# 8 will be usable with the .NET Framework. [I suspect they will backtrack on this now that the Visual Studio 2019 language version dropdown has been disabled and .NET has been tied to C# 7.3]
Shortly after the famous blog post, a GitHub thread discussed cross-platform support. An important point which emerged was that .NET Standard 2.1 will include a marker that denotes that default implementations of interfaces is supported - the feature requires a CLR change that will never be available to the .NET Framework. Here's the important bit, from Immo Landwerth, Program Manager on the .NET team at Microsoft:
Compilers (such as C#) are expected to use the presence of this field to decide whether or not to allow default interface implementations. If the field is present, the runtime is expected to be able to load & execute the resulting code.
This all pointed to "C# 8.0 is only supported on platforms that implement .NET Standard 2.1" being an oversimplification, and that C# 8 will support the .NET Framework but, as there is so much uncertainty, I asked on GitHub and HaloFour answered:
IIRC, the only feature that definitely won't appear on .NET Framework is DIM (default interface methods) as that requires runtime changes. The other features are driven by the shape of classes that might never be added to the .NET Framework but can be polyfilled through your own code or NuGet (ranges, indexes, async iterators, async disposal).
Victor Derks commented that "The new nullable attributes required to design the more complex nullable use cases are only available in System.Runtime.dll that ships with .NET Core 3.0 and .NET Standard 2.1... [and] incompatible with .NET Framework 4.8"
However, Immo Landwerth commented that "The vast majority of our APIs didn't need any custom attributes as the types are either fully generic or not-null" under the article Try out Nullable Reference Types
Ben Hall raised the issue Availability of nullable attributes outside of Core 3.0 on GitHub, with the following comments from Microsoft employees being of note:
C# 8 will be fully supported on .net core 3.0 and .net standard 2.1 only.
If you manually edit the project file to use C# 8 with .net core 2.1,
you are in unsupported territory. Some C# 8 features will happen to
work well, some C# 8 features will work not too well (e.g. poor
performance), some C# 8 features will work with extra hacks, and some
C# 8 features will not work at all. Very complex to explain. We do not
actively block it so the expert users who can navigate through it can
do so. I would not recommend this unsupported mix&match to be used
broadly.
(Jan Kotas)
People like you who are willing understand -- and work around them --
are free to use C# 8. The point is, not all language features will work
on down-level targets.
(Immo Landwerth)
Caveat emptor
The C# 8/.NET Framework combination is not officially supported by Microsoft. It is, they say, for experts only.

According to this blog entry the language is indeed tied to the framework:
This means that the types required to use these features won’t be available on .NET Framework 4.8. Likewise, default interface member implementations rely on new runtime enhancements, and we will not make those in the .NET Runtime 4.8 either.
For this reason, using C# 8.0 is only supported on platforms that implement .NET Standard 2.1. The need to keep the runtime stable has prevented us from implementing new language features in it for more than a decade. With the side-by-side and open-source nature of the modern runtimes, we feel that we can responsibly evolve them again, and do language design with that in mind. Scott explained in his Update on .NET Core 3.0 and .NET Framework 4.8 that .NET Framework is going to see less innovation in the future, instead focusing on stability and reliability. Given that, we think it is better for it to miss out on some language features than for nobody to get them.

Related

How do I change the C# version in Visual Studio 2019

I'm currently writing a project in C# 7.3 but I need to change it to C# 10.0
When I go to my project's properties' advanced build settings, the option to change the language version is disabled. I'm not sure why it's grayed out, but I don't know how to manually change the C# version. If someone could help, that would be great, thanks!
Screenshot of the advanced build settings
Taken directly from the documentation
The compiler determines a default based on these rules:
Target framework
version
C# language version default
.NET
7.x
C# 11
.NET
6.x
C# 10
.NET
5.x
C# 9.0
.NET Core
3.x
C# 8.0
.NET Core
2.x
C# 7.3
.NET Standard
2.1
C# 8.0
.NET Standard
2.0
C# 7.3
.NET Standard
1.x
C# 7.3
.NET Framework
all
C# 7.3
C# 10 is supported only on .NET 6 and newer
You haven't provided the target framework for your project. But you likely need to retarget your project to a framework that supports C#10
You can try to edit the .csproj file by adding something like this:
<PropertyGroup>
<LangVersion>10.0</LangVersion>
</PropertyGroup>
C#10 is already the default language version if your target framework is .NET 6, provided you're not overriding it with the LangVersion entry as mentioned in other answers. If you're not targeting .NET 6 or compiling with VS/Build Tools 2022, you'll need to upgrade those first in order to have proper C#10 support.
If you are attempting to set the C# language version manually, keep in mind the default can be overridden in two locations (or programmatically): the project file (aka ProjectName.csproj), or a Directory.Build.props file (for explicitly overriding multiple projects at once). If the aforementioned props file exists, check it as well as your project file to ensure you don't have conflicting entries.
In your case, there's really no reason to manually specify the language version; just upgrade your compiler and use the default. If at that point you still find the project targeting anything < C#10, be aware that the culprit isn't necessarily confined to being the project file.

In Visual Studio, is it possible to target a .NET 4.x CLR but a 2.0 class library API?

When you select the target framework of a C# project in Visual Studio, you actually select three different things at once (as far as I understand).
Selecting .NET 4.7.2 will select:
the language version (e.g. C# 7.2)
the CRL (common language runtime) version (e.g. 4.5)
and the BCL (base class library) version (e.g. 4.7.2)
Now, is it possible to somehow configure these things independently? I understand there are dependencies, but targeting a lower BCL API should work, right?
The reason is this: my project is a C# class library that is used inside a Unity3D application. Unity has a 4.x (compatible) CLR, but let's you chose between a .NET Standard 2.0 API and a 4.x. It generally makes sense to target 2.0 because it is smaller and 4.x does not work on all platforms that Unity supports.
It would be great if I could replicate this configuration in Visual Studio. Otherwise I might accidentally make an invalid (i.e. > 2.0) API call in my dll code and will only find out when the code crashes with a 'class/function not found' in Unity.
The language version can be set completely independently via <LangVersion> in the csproj, i.e.
<LangVersion>8.0</LangVersion>
The CLR and BCL versions are ... complex. You're really targeting a TFM here. It sounds like you want (again, in the csproj)
<TargetFramework>netstandard2.0</TargetFramework>
The actual CLR (runtime) is determined by whatever runs it, not the library. But you can multi-target, if that becomes useful, i.e.
<TargetFrameworks>netstandard2.0;net472</TargetFrameworks>
and configure different dependencies and #if etc for different platforms, to make the most of each. Whether unity can properly consume a multi-targeted package is another question, that I can't answer.
You can edit the csproj at any point; you aren't tied to what is generated from the template.

Is there a way to generate multilingual documentation in .NET Core / .NET Standard?

When I create a .NET Framework project, prompts for standard types appear in the same language as Visual Studio. With .NET Core / .NET Standard projects this is no longer the case. I've tried ways suggested on Stack Overflow (putting an additional <summary lang="..."> comment) but couldn't get the described effect either on .NET Framework or on .NET Core.
Is this possibility available now? Is it available for any assembly or, perhaps, only for standard assemblies?

Are C# and .NET versions dependent on each other?

I'm just starting to learn C# and its relationship to .NET. If say I wanted to take advantage of the latest C# language conventions, but wanted to target, say a .NET 2.0 framework, could I do that? Or does using the latest C# mean I have to use the latest .NET?
C# as a language is not dependent on .net framework.
For example: Extension methods is a feature released with C# 3.0 which came along with .Net 2.0.
Extension methods depends on ExtensionAttribute which lives in "mscorlib.dll" which was added in .Net 3.5. But you can use Extension methods in .Net 2.0 given that you provide your own ExtensionAttribute in your library itself. It doesn't needs to be in mscorlib. Refer this question for more info.
As we know async-await is new in C# 5.0 which was released with .Net 4.5, but we can use async-await in .Net 4.0 itself.
Sameway, most of the dependencies of language features can be defined in your own assembly to make it work. So it doesn't need the particular .Net framework version.
you can use features of lastest visual studio editions (2013, 2015), but the code must be according to 2.0 specifications to allow a .NET 2.0 compilation (older versions)
Yes, C# and .Net versions are dependent. According to my understanding C# is a programming language which works using .Net Technology.
Learning C# means learning the basic syntax, which is almost the same in all .Net versions. So for learn c#, it doesn't matter which .Net version you must target. Different .Net versions adds up certain new features or functionality. Any way its better to understand latest .Net version which will help you in projects.
You can use C# features from earlier versions with later versions of .Net, for example, you can use any C# 2.0 feature with .Net 3.5, this does not work the other way arround, so you cannot use .Net 3.5 features with the c# 2.0 compiler.
For more details see: https://msdn.microsoft.com/en-us/library/ff602939(v=vs.110).aspx
C# 6.0 is available in .NET 5.0.
It depends on the CLR. C# 4, 4.5 and 4.5.1 are using the CLR Version 4.
Yes C# is dependent on .net versions. The dependence between the both is on features and technologies provided. Refer following link:
https://msdn.microsoft.com/en-us/library/bb822049%28v=vs.110%29.aspx

Reference a .net framework 4.5.1 assembly in a 4.0 project

How can i make a 4.0 project have a 4.5 reference. In the unit tests, i cant build the solution and it's giving me this warning.
Warning 2 The primary reference "PR.Wallet" could not be resolved
because it was built against the ".NETFramework,Version=v4.5.1"
framework. This is a higher version than the currently targeted
framework ".NETFramework,Version=v4.0". PR.Wallet.Tests
.Net frameworks (v2.0 or higher) are not forward compatible. . You can't reference a .Net 4.5 assembly in .Net 4.0 project.
See: Version Compatibility in the .NET Framework
You may also see: Version Compatibility
The degree of .NET Framework support for backward and forward
compatibility is version-specific. The .NET Framework supports both
backward and forward compatibility for applications created using
version 1.1 only. It does not support forward compatibility in
applications created using version 2.0. In the context of the .NET
Framework, backward compatibility means that an application created
using an early version of the .NET Framework will run on a later
version. Conversely, forward compatibility means that an application
created using a later version of the .NET Framework will run on an
earlier version.
The .NET Framework provides a high degree of support
for backward compatibility. For example, most applications created
using version 1.0 will run on version 1.1 and applications using
version 1.1 will run on version 2.0. The .NET Framework also supports
forward compatibility for version 1.1 only. However, for forward
compatibility you might need to modify an application so that the
application runs as expected. Applications created with version 2.0
will not run on earlier versions of the .NET Framework. For both
backward and forward compatibility, a change to the .NET Framework
that helps improve security, correctness, or functionality might also
raise compatibility issues.
Sounds like you need to change the framework of the library. And since it is only a unit tests project, I don't see why you wouldn't.
In Visual Studio:
Right-click on your project
Select Properties
Select the Application tab
Change the Target Framework to the desired framework
If you are not seeing .NET Framework 4.5.1 as an option there, ensure you have it installed.
You aren't able to reference a 4.5.1 assembly in a project that targets 4.0 .
But ... you can call the method of a 4.5.1 assembly in a project that targets 4.0 by calling it dynamically, assuming 4.5.1 is installed:
var assembly= Assembly.LoadFrom(...);
var type = assembly.GetType(...);
var method = type.GetMethod(...);
var res = method.Invoke(null, args);
Note that there may be limitations to this approach, but I found it useful for calling Roslyn routines while still using VS2010.
There may be exceptions. Based on my own experience, for example, some libraries like TagLib-Sharp 2.2.0 (which you can download from NuGet) perfectly allowed me to reference its .NET 4.5 DLL just fine from .NET 4.0 (Client of Full Profile) project running on Visual Studio 2010.
Additionally, calling some method from aforementioned referenced .NET 4.5 DLL did not emit any warning or error, build process went fine though, including at runtime. However, some methods/functions have failed, so it's a hit and miss but remember that referencing .NET 4.5 DLL was succeeded. So the answers and general rules above about "forward compatability" context clearly have some exceptions like TagLib-Sharp under particular circumstances.

Categories

Resources