I was trying around a bit with Try Roslyn when I entered this piece of code:
using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.CSharp;
public class C {
public C()
{
x = 4;
}
public int x { get; } = 5;
}
And it gave me back this code:
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
[assembly: AssemblyVersion("0.0.0.0")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[module: UnverifiableCode]
public class C
{
[DebuggerBrowsable(DebuggerBrowsableState.Never), CompilerGenerated]
private readonly int <x>k__BackingField;
public int x
{
[CompilerGenerated]
get
{
return this.<x>k__BackingField;
}
}
public C()
{
this.<x>k__BackingField = 5;
base(); // This is not valid C#, but it represents the IL correctly.
this.<x>k__BackingField = 4;
}
}
What I don't get is why it would do the assignment of the backing field twice inside of the constructor:
this.<x>k__BackingField = 5;
base(); // This is not valid C#, but it represents the IL correctly.
this.<x>k__BackingField = 4;.
Is this an error of the website or does the Roslyn compiler actually do this (would be really dumb imo)?
What I mean is that if I do
public C(int x)
{
this.x = x;
}
public int x { get; } = 5;
And have that code created:
public C(int x)
{
this.<x>k__BackingField = 5;
base(); // This is not valid C#, but it represents the IL correctly.
this.<x>k__BackingField = x;
}
But shouldn't it optimize that out?