C# 11: "field" keyword not supported in VS 2022 - c#

I have a .NET 7.0 WinForms project which claims, in its properties, to have the Language version set to 11.0 (and I've played in the .csproj to make it "latest" and "preview", etc.).
ReSharper's inspections suggest that I can use the field keyword in a number of places, but when I do so, VS hates the refactored result and I get compile errors ("The name 'field' does not exist in the current context", etc.).
I am completely at a loss as to why my VS (I've even tried the preview -- I'm on Professional 2022 version 17.5.0 preview 6.0) doesn't want to like C# 11.
Here's what I have for installed SDKs, in case that plays into things...
C:\>dotnet --list-sdks
7.0.103 [C:\Program Files\dotnet\sdk]
7.0.200-preview.22628.1 [C:\Program Files\dotnet\sdk]
7.0.200 [C:\Program Files\dotnet\sdk]
Here is one of the areas of code that is producing the error.
BEFORE
private int _updateDepth; // this is "grayed" by R# with hint to address
private int UpdateDepth
{
get => _updateDepth;
set
{
_updateDepth = value;
if (!SkipHandlers && !SkipCallbacks && UpdateDepth is 0)
RunGameDataChangedCallback();
}
}
AFTER
private int UpdateDepth
{
get;
set
{
field = value;
if (!SkipHandlers && !SkipCallbacks && UpdateDepth is 0)
RunGameDataChangedCallback();
}
}
I have also tried (because in reading about the field keyword, it seems to say that the property must be initialized) to add = 0; after the final closing curly-bracket, but that doesn't help.
COMPILER ERRORS
CS0501 'GameControl.UpdateDepth.get' must declare a body because it is not marked abstract, extern, or partial
CS0103 The name 'field' does not exist in the current context
Any ideas?

According to this comment from the C# GitHub repository, there have been issues with the implementation of the field keyword and so it didn't make it into C# 11. It may (or may not) come in C# 12.

It seems that this is R# bug (so I suggest reporting it or try checking if there are updates present). ATM there is no field keyword present in C# (keywords list) and such feature is not listed among released with C# 11 and .NET 7 (docs) because it was removed from the release (github discussion).

Consensus (and Microsoft) seems to say that despite pages saying so, and despite JetBrains ReSharper thinking so, the field keyword is not supported in C# 11 after all.
I have submitted a bug report to JetBrains telling them that they might want to not give bad advice. Anyone interested in this can follow the request at https://resharper-support.jetbrains.com/hc/en-us/requests/4782760
Thanks to all!

Related

How to use type reference nullable or how to enable it on preview in .NET Core

My problem is that i keep having the error CS8652
"C# The feature is currently in Preview and unsupported. To use Preview features, use the language version."
By using "?" after the type to authorize the property to be null during a deserialization (i use JsonConvert if it helps, maybe there is a parameter that authorize some property to be null, but i don't really think so)
class Data
{
String? PropertyCanBeNull { get; set; }
}
I've tried almost all i've found to resolve this error including the following :
- Install Visual Studio 2019 Preview
- Install .NET SDK for preview (and checking in CMD that it worked)
- Modified my project property so that it use the .NET Core 3.0+ version
I also tried to change the language version for my project, but it seems it's useless in my case.
"When your project targets a preview framework that has a corresponding preview language version, the language version used is the preview language version."
Source : https://learn.microsoft.com/fr-fr/dotnet/csharp/language-reference/configure-language-version
Answered by Dirk in comments :
I also remember using the "?" after the type some time ago, but i'm not really sure, did they do any change to it so that it is supported only in "preview" or something ?
Nullable value types (like int?) have been in C# for a very long time. Nullable reference types (like string?) however were introduced with C# 8.
A string is Always nullable in C#.
And while C# 8 will introduce the nullable reference types like public string? this is also a problem NewtonSoft's JSON Converter has had solved for some time:
string ignored = JsonConvert.SerializeObject(movie,
Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
Edit
I made it back to the machine with Visual Studio, fully updated to Visual Studio 2019 (16.2):
If you edit the project solution
Open the solution folder
Right-click the solution and edit
and add the following two settings to the PropertyGroup the warning will go away:
<Nullable>enable</Nullable>
<LangVersion>8.0</LangVersion>

error CS1644: Feature `null propagating operator' cannot be used because it is not part of the C# 4.0 language specification

I have Unity 2018.1.9f2 and I downloaded the Unity ml agents and added the folder to my unity project. But When I try to run the '3DBall' scene I get this error in the console:
Assets/ml-agents-master/UnitySDK/Assets/ML-Agents/Scripts/Brain.cs(79,25): error CS1644: Feature null propagating operator' cannot be used because it is not part of the C# 4.0 language specification. When I double click it then it opens the VS and brainBatcher?.SendBrainInfo(name, agentInfos); is underlined.
and when I hover over the code it says Feature 'null propagating operator' is not available in C# 4. Please use language version 6 or greater.
I tried to follow the answer from anther similar question: Unity Visual Studio C# version synchronization. So I used unity-c-5.0-and-6.0-integration and that error was not displayed but I got 150+ other errors.
Any help will be much appreciated.
Make sure your Player Settings / Scripting Runtime Version is set to .NET 4.x not .NET 3.5
Why not just remove the ?
In my case, the following change fixes the build even using .net 3.5 framework
Action<DeleteObjectsResponse, string> result;
// Change:
//result?.Invoke(null, responseObj.Exception.ToString());
// To:
if (result != null)
result.Invoke(null, responseObj.Exception.ToString());

Object of type 'System.Int32' cannot be converted to type 'System.Web.Security.Cryptography.Purpose'

I am getting this error now whenever I try to build. I just installed Visual Studio 2012 and .Net 4.5, but this project is still on 2010.
Here is the line of code I am having issues with:
private static MethodInfo _encode;
public static string Encode(CookieProtection cookieProtection, byte[] buf, int count)
{
return (string)_encode.Invoke(null, new object[] { cookieProtection, buf, count });
}
I receive an ArgumentException was unhandled by user code error saying, "Object of type 'System.Int32' cannot be converted to type 'System.Web.Security.Cryptography.Purpose'" Nothing has changed in my dev environment and my co-workers are not having the same problem, but they also do not have VS2012.
I found an article about Sitecore having this error, but this is the only place I have seen it pop up.
There they say, "This is because in .NET 4.5 there are some new namespaces in System.Web "
Their solution is to:
Uninstall VS11 if you have it installed
Uninstall .NET 4.5
Reinstall .NET 4
This seem like a ridiculous solution that 4.5 and 4 cant be on the same machine.
Does anyone know what may be causing this and any better solutions before I try to un-install and re-install a bunch of stuff?
A comment also says to try: </setting name="login.rememberlastloggedinusername" value="false" > but I don't want to do that either.
As #hvd alluded to, this code is using reflection to call internal methods which Microsoft changed in .NET 4.5.
Fortunately .NET 4.0 introduced the System.Web.Security.MachineKey class with public Encode() and Decode() methods which accomplish basically the same thing as the internal methods in the CookieProtectionHelper. Note that cookies that were encrypted with CookieProtectionHelper.Encode() will not be able to be decrypted with MachineKey.Decode().
Also note that in .NET 4.5, these methods are deprecated in favor of Protect() and Unprotect().
Change value to false in web.config:
<setting name=”Login.RememberLastLoggedInUserName” value=”false” />
(from: http://truncatedcodr.wordpress.com/2012/06/20/fix-sitecore-and-net-framework-4-5/)
Did you get that from here?
_encode = cookieProtectionHelper.GetMethod(
"Encode", BindingFlags.NonPublic | BindingFlags.Static);
This relies on internal implementation details of the .NET Framework that MS never promised would remain unchanged. So yes, an in-place upgrade of the .NET Framework could very well make such code stop working. That's not a bug in .NET 4.5. That's a bug in your -- that -- code for relying on things you cannot rely upon.
And to solve it, stop using that method. If there is a public API that does what you want, use that. If there isn't, implement it yourself.
If you see this error whilst using the CMS software Ektron, the following is in their 8.7 release notes-
71233—If you installed an 8.6.1 site and enabled cookie encryption in
web.config (),
then installed Microsoft .NET Framework 4.5, you saw this error:
Server Error in '/' Application.
Object of type 'System.Int32' cannot be converted to type System.Web.Security.Cryptography.Purpose'. This
is fixed.
As mentioned in the other answers, one solution is to rollback to .Net framework 4.0. The other answers in this particular case with Ektron are to disable cookie encryption, or upgrade to 8.7.

"Missing compiler required member" error being thrown multiple times with almost no changes to code

Today after deploying some changes to a C# MVC site that I run, I went back to make some more modifications and came across this error:
Missing compiler required member System.Runtime.CompilerServices.ExtensionAttribute..ctor
The error is a bit vague (other than it's description, obviously) as it doesn't give me a file, line, or column to reference, only the project. Also, it throws the error a total of 20 times. I only made three changes to the code between the time I deployed (it was completely functional at that time) and now. I reverted my changes and it is still throwing the same error which makes no sense to me.
I haven't found a lot of information on this error on SO or Google, other than this guys solution and a couple references to some Mono project errors (I'm not using Mono). The solution the guy above gives requires adding a class definition that will allow the compiler to resolve the reference. I don't particularly want to do this because I haven't needed to do it up until this point and it will just muddy my code.
Just curious if anyone has run across this before.
In my case it was because the project was not referencing Microsoft.CSharp. Once I added a reference to that assembly, it compiled just fine.
I don't know if anyone else has experienced this, but I suddenly ran into this error after adding some code utilizing dynamic types and incorporating WebAPI into a project that originated as a TypeScript application in VS2013. Simply adding a reference to Microsoft.CSharp resolved my issue.
Hope this helps someone else.
This error usually means either your project is compiling against .NET 2.0 or you aren't referencing the correct version of System.Core.dll
For a near duplicate question, see Error when using extension methods in C#
I ran into this situation as well today. In my case I was referencing the Newton.Json.Net dll v3.5 in my .NET 4.0 application. I realized that I wasnt even using this library, thus once I removed it from my references, it no longer gave me the compiler error.
Problem solved!!!
The actual error comes from the fact that your 2.0 assembly that causes the error contains this code:
namespace System.Runtime.CompilerServices
{
public class ExtensionAttribute : Attribute { }
}
The Code Above allows the .NET 2.0 Assembly to use extension methods (see Using extension methods in .NET 2.0?). While it confuses the compiler if you target .NET 4.0 and reference a 2.0 Assembly (containing above code) as the mscorlib.dll(4.0) contains the same class in the same namespace.
I fixed this
by compiling the original 2.0 assembly again without the attribute targeting 4.0
by removing the assembly (obviously)
by adding a third Extension Attribute in the target you compile (it seems to overrule the referenced definitions)
Writing this code somewhere in your project may solve your problem. It works for me
namespace System.Runtime.CompilerServices
{
public class ExtensionAttribute : Attribute { }
}
Probably you use dynamic keyword In .NetStandard Class library project. If so, you need to add a reference to Microsoft.CSharp library in the project. Hope it will resolve your problem.
NLog.dll 2.0 referenced from a .NET 4.0 project can cause this too.
I don't have a correct solution, but I'll add my data point:
In my case the error is caused by referencing GoogleSearchAPINet20
Here is what happens:
I close the solution that builds
I open the solution again. It still builds
As soon as I make any change and try to build, I get 19 "Missing compiler required member ..." errors
I remove the reference to GoogleSearchAPINet20
I add back the reference to GoogleSearchAPINet20
I build the solution. It builds without errors
I can now make code changes, build or perform any other actions with solution correctly as long as my Visual Studio is open
I close Visual Studio
Repeat from step one
I'm not referencing System.Core.dll in my solution at all and my target framework is .NET 4.
I'm a bit annoyed at this point ...
Got this error when trying to use async Tasks against .NET 4.0. Updating Target Framework to 4.5.2 fixed the problem.
I hit the same set of exceptions after I added some async methods to a winforms project. I needed to bump my .NET version from 4 to 4.5
For me, the problem occure when I add asynchronous method with async Task await in my .net4.0 project !
With previous versions of the .NET-Framework 4.5, you must install this package:
Install-package Microsoft.Bcl.Async –pre
or
Install-Package Microsoft.CompilerServices.AsyncTargetingPack
more info on Nuget or Nuget

How can compilation of C# code be made to require a given language or compiler version?

How can a C# program detect it is being compiled under a version of C# that does not contain support for the language features used in that program?
The C# compiler will reject the program, and produce some error message, on encountering the features of the language it does not support. This does not address the issue, which is to state that the program is being compiled with too old a version of the C# compiler, or a C# compiler that does not support the required version of C#
Ideally, it would be as simple as
#if CS_VERSION < 3
#error CSharp 3 or later is required
#end
I don't believe you can do that with a C# file, but if you're using MSBuild then the project/solution tools version number can stop it from being built with an older version of MSBuild.
Can you give the exact context of this? One "human" solution rather than a technical one might be to try compiling the code with all the "old" versions, and create a document with: "If you get an error like this it probably means you're using the wrong version..."
Another option you might want to consider to make that even simpler is to have a single "required features" file. This would be unused by your main app, but ask users to compile that first. If it works, the rest of your build should work. If it doesn't, it's due to using the wrong version. That's likely to produce a smaller range of errors from different versions (in particular it doesn't have the problem that the compiler could list errors from different files in a random order).
According to this list of preprocessor directives, it doesn't seem possible. We usually can tell by using generics (detects 2.0), using auto properties (3.0) or dynamic (4.0)
Easy: The compiler will fail and give you an error if it can't compile the code.
There is no predefined symbol for this; you could create your own symbols and define them in your build script. Note that you can fix the language version at the project level:
Project properties -> Build -> Advanced -> Language Version:
ISO-1 is C# 1.2
ISO-2 is C# 2.0
(maps to the csc /langversion parameter)
But note that this doesn't cover everything - there are a few things that this will let through - particularly in the area of generic type inference. This is only an issue if you need to support old compilers; in which case... test with an old compiler.
For example:
int[] arr1 = { 1, 2, 3, 4, 5 };
string[] arr2 = Array.ConvertAll(arr1, delegate (int i) {return i.ToString();});
This works in .NET 3.5/ISO-2 (pseudo C# 2.0), but doesn't work in .NET 2.0 (proper C# 2.0).
Perhaps you can read the supportedRuntime element:
Then you can define the directive you want based on the supportedRuntime, using CSharpProjectConfigurationProperties3.DefineConstants.
You would create a macro in VS to use this.

Categories

Resources