Is this a valid syntax in C# .NET 4.6.2 - c#

public class MyClass
{
public string DeviceCommands { get; set; } = "DeviceCommands";
}
I have 30 errors on this kind of lines...

.NET 4.6.2 is a framework version, not a language version. To be able to do that line you must be using C# 6 or newer. If you are compiling with C# 6 you would be allowed to use that syntax in a .NET 2.0 project.
If you are using Visual Studio 2015 or newer you are using C# 6 or newer.
If you are using Visual Studio 2015 and are still getting errors there is some other problem with your code that you are not showing us.
UPDATE:
If you are using VS2015 and are getting a error that says
Error CS8026: Feature 'auto property initializer' is not available in C# 5. Please use language version 6 or greater.
That means in your project properties -> Build -> Advanced screen you set the language version manually to 5 or lower instead of default.
Setting it back to default will fix the problem.

The syntax you have are Auto Property Initializers.
It has nothing to do with the .NET Version. It is a language feature from C# 6.0.
You need the the roslyn compiler plattform to make this work.
If you can not support C# 6.0, you could do it the old way:
public class MyClass
{
public string DeviceCommands { get; set; };
public MyClass()
{
DeviceCommands = "DeviceCommands";
}
}

Related

Roslyn Source Generator not generating any source in a .net framework 4.7.2

Probably a simple learning issue, but I'm attempting to use the new roslyn source generators to automatically generate some source code for .net framework 4.7.2 (mvc is the goal, but I'll be happy if it worked in my test console app).
Here's my code
[Generator]
public class GenerateCommand : ISourceGenerator
{
public const string TestCode = #"
namespace Test
{
public static class Hello
{
public static string World = ""Hi from generated code."";
}
}";
public void Initialize(InitializationContext context) { }
public void Execute(SourceGeneratorContext context)
{
context.AddSource("Hint_Hello_World", SourceText.From(TestCode, Encoding.UTF8));
}
public void Test()
{
var x = Test.Hello.World; // <-- Refuses to build.
}
}
}
Package versions are Microsoft.CodeAnalysis.CSharp v 3.7.0 (and associated roslyn stuff)
This seems to be about as simple as I can make it and it seems to work if I'm targeting .net core, it's just when I'm trying to add it to a framework project that it does nothing. No errors, no output messages, just not running or generating source.
Any help would be appreciated.
Update: As of Roslyn 3.8 / Visual Studio 16.8 source generators are no longer behind a preview flag, and should work for any language version or target framework.
Ensure you check out the Breaking changes section of the cookbook to address any API differences between preview and release.
Currently source generators are gated behind <langversion>preview</langversion> as they aren't a released feature, and we don't want customers accidentally using them without realizing it.~~
At release time we'll remove the language version restriction and they'll work on any supported Roslyn compiler, although it will be up to the individual generator authors to ensure that the code they generate is correct for the project options the user has selected.
Edit thanks to Chris Sienkiewicz: Currently source code generators are gated behind the preview language version and thus not available for other .NET versions than .NET 5. This will however change once source code generators are released and stable.
Old Answer:
Source code generators are a .NET (Core) 5/ C# 9 feature, there is no way to get it to work with .NET Framework (or .NET Core != 5). If you need to generate code at compile time, you have a few options:
Use a T4 template
Add a pre-build event
Use a NuGet package like Clarius.TransformOnBuild

XMLSerializer class throwing "array must no be null" exception when compiled in Visual Studio 2017 and .NET 3.5

I have old code written using VS2008 which I transfered to VS2017. Code was using .NET 2.0
If I build it using VS2017 and .NET 2.0 I get an "Array cannot be null." in the XMLSerializer constructor
If I use VS2015 and .NET 2.0 the code is working. With VS2017 it only works if I switch to .NET 4.0 or higher. With VS2015 it is working with all .NET versions.
The call stack on exception looks like this:
at System.Reflection.Assembly.nLoadImage(...
at System.Reflection.Assembly.Load(...
at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(...
at Microsoft.CSharp.CSharpCodeGenerator.FromSourceBatch(...
at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromSourceBatch(...
at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromSource(...
at System.Xml.Serialization.Compiler.Compile(...
at System.Xml.Serialization.TempAssembly.GenerateAssembly(...at System.Xml.Serialization.TempAssembly..ctor(...
at System.Xml.Serialization.XmlSerializer.GenerateTempAssembly(...
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
at System.Xml.Serialization.XmlSerializer..ctor(Type type)
at XMLSerializerTestVS2017.Form1.button1_Click(....
I was able to reproduce the problem with just a few lines of code.
Exception pops up on the line
XmlSerializer serializer = new XmlSerializer(typeof(MyData));
And I have defined the MyData class like this (just for testing)
[XmlRoot(ElementName = "root")]
public class MyData
{
[XmlElement(ElementName = "MY_XML_A_ENTITY")]
public string A { get; set; }
[XmlAttribute(AttributeName = "xml_b_attrtibute")]
public string B { get; set; }
[XmlElement(ElementName = "MY_XML_C_ENTITY")]
public int C { get; set; }
}
Does anybody has an idea what could be the reason for this behaviour. The code compiles without problems. Why VS2017 with .NET 3.5 or older is not working on this simple example? I also tried to switch the VS2017 to use C# version 3.0 for compilationa but it made no difference. VS2015 and older (I have tried them out 2013, 2010 & 2008) are all working fine with any .NET version.
Any input is more than welcome! Thx!
REMARK:
I am not sure if this is the proper way to handle this, I didn't want to answer my own question because others came with ideas that explained the possible cause for my problem so I I though it would be unapropriate to take the credit for the answer. It seems that something is wrong with my machine (Thx Jack!). Testing the code built with VS2017 and .NET2.0 or 3.5 worked just fine in a fresh VMWare. So I guess there is something wrong on my machine causing the trouble. I still do not know what exactly it is, but if I find out I'll post here.
Thank you all for help!
REMARK No. 2
It seems it is not just my computer. Even though the compiled test code worked in a fresh VMWare, the exception showed again as I run the test code on a machine belonging to a colleague developer. Currently I am inclined to beleive that the problem has to do with VS2017.
REMARK No. 3
I did some more testing on other machines on our site. I have tried machines without Visual Studio 2017. The error popped up on those machines to. I am not sure what to conclude from that, but it seems that the combination of compiling with Visual Studio 2017 and running on machines with all the Microsoft updates on it somehow creates the described problem.

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>

Creating an extension method in a .Net 2.0 project, compiling with C# 4.0

I have an old product that I need to update, written in C# and .Net 2.0. The project has been updated to work with Visual Studio 2010 (which includes the C# 4.0 compiler) but I can not upgrade the framework from 2.0 to any higher version.
I've found multiple articles (like this question) that were written around the time of VS 2008, which shipped with the C# 3.0 compiler, stating that you can create your own extension methods by defining your own extension method attribute class for projects that were written with the 2.0 framework. However, I can not seem to find any reference stating if this is still necessary using C# 4.0 on a .Net 2.0 project.
With my project, will I still need to define the custom extension attribute class or has the C# 4.0 compiler been improved so that it can simplify the process?
I can not seem to find any reference stating if this is still necessary using C# 4.0 on a .Net 2.0 project.
Yes, it is. The compiler needs that attribute. Whether you define it yourself or use the one in System.Core is up to you. Though in your particular case System.Core is not an option since that is only a part of .NET 3.5.
Once you upgrade to a later version, 3.5 or later, you can safely remove this attribute from your project all together and just use the one in System.Core.
If you have upgraded to Visual Studio 2010; then you are using the C# 4.0 compiler. That means all you need is an ExtensionAttribute:
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class ExtensionAttribute : Attribute
{
}
}
It must be in this exact namespace.
Once you've got that somewhere, you can declare an extension method the normal way (since you are using the C# 4.0 compiler):
public static class Extensions
{
public static string ToTitleCase(this string str)
{
//omitted
}
}
And then use it like an extension method:
var str = "hello world";
str.ToTitleCase();
You yourself don't actually ever need to put the ExtensionAttribute on anything; the C# 4.0 compiler does it for you. Essentially, all the compiler needs is to be able to find an attribute named ExtensionAttribute.

C# versions compatibility

I'm developing an application whose target framework is version 3.5. But while looking at the code, I found a method using default parameters:
public void Contact(string name, string email, string phone, string phoneAreaCode = "")
{
//...
}
and got confused.
The language features are independent of the framework version? What is the relation between both and why is this the code above possible?
EDIT: I have created 2 projects (a class library and a console) in VS2010, both tageting the .NET 2.0 Framework. On the class library, I've created a method with an optional string parameter. I've used it in the console app with no problems, with and without passing the parameter. Does this have anything to do with VS2010? And by "VS2010" you mean C# compiler 4.0?
The compiler emits the information, but the 3.5 runtime doesn't use it - it just gets ignored.
See this blog post, and these SO questions - one, two.
In essence, the 3.5 runtime sees this:
public void Contato(string nome, string email, string telefone, string ddd)
{
//...
}
The language features are dependant on what version of Visual Studio you are using. The .Net Framework dictates what .Net functions and classes are available to you.
The code above is possible because you are using Visual Studio 2010. You can use all the features of the new code editor, regardless of what .Net version your assembly targets. But, the instant you try to use a .net 4.0 class or function in your .net 3.5 code, you will get a compiler error.
You must be using VS2010... because it supports it.

Categories

Resources