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.
Related
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
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());
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";
}
}
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.
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.