I created a sample project, with C#6.0 goodies - null propagation and properties initialization as an example, set target version .NET 4.0 and it... works.
public class Cat
{
public int TailLength { get; set; } = 4;
public Cat Friend { get; set; }
public string Mew() { return "Mew!"; }
}
class Program
{
static void Main(string[] args)
{
var cat = new Cat {Friend = new Cat()};
Console.WriteLine(cat?.Friend.Mew());
Console.WriteLine(cat?.Friend?.Friend?.Mew() ?? "Null");
Console.WriteLine(cat?.Friend?.Friend?.TailLength ?? 0);
}
}
Does it mean that I can use C# 6.0 features for my software that targets .NET 4.0? Are there any limitations or drawbacks?
Yes (mostly). C# 6.0 requires the new Roslyn compiler, but the new compiler can compile targeting older framework versions. That's only limited to new features that don't require support from the framework.
For example, while you can use the string interpolation feature in C# 6.0 with earlier versions of .Net (as it results in a call to string.Format
):
int i = 3;
string s = $"{i}";
You need .Net 4.6 to use it with IFormattable
as only the new framework version adds System.FormattableString
:
int i = 3;
IFormattable s = $"{i}";
The cases you mentioned don't need types from the framework to work. So the compiler is fully capable of supporting these features for old framework versions.