2

I have a class with two properties one filled with the new auto-property initializer of c# 6.0 and one implementing only the getter shorthand:

public SampleEnum SampleProp1 { get; } = SampleEnum.Value1;
public SampleEnum SampleProp2 { get { return SampleEnum.Value1; } }

this class is a parameter of an wcf endpoint, when this endpoint is called the SampleProp1 contains only the default enum value.

Why is this happening?

jansepke
  • 1,933
  • 2
  • 18
  • 30

2 Answers2

4

The auto-property initializer in C# 6.0 is syntactic sugar and the compiler will create a backing field for the property that is initialized to the given expression.

Therefore, your code is equivalent to the following declaration (I added a class ´SampleClass` for clarification):

class SampleClass
{
    // compiler-generated backing field initialized by the field initializer
    private readonly SampleEnum __sampleProp1 = SampleEnum.Value1;

    public SampleEnum SampleProp1 { get { return __sampleProp1; } }

    public SampleEnum SampleProp2 { get { return SampleEnum.Value1; } }
}

Your problem comes from the fact that the deserializer used by WCF does not execute the field initializers.

A possible solution would be to make use of the OnDeserializing or OnDerserialized attributes and place all your initialization code into a separate method (as described in this question: Field Initializer in C# Class not Run when Deserializing).

Community
  • 1
  • 1
Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
0

Is SampleEnum really an enum? I tried your code in a simple class with an actual enum and it seemed to work fine.

I can see where there might be a problem of SampleEnum was actually a class though, and Value1 had not yet been initialized when the class with the properties was initialized.

Here's what I tried that works as expected:

class Program
{
    static void Main(string[] args)
    {
        var x = new MyClass();
        Debug.Print("{0}", x.SampleProp1);
        Debug.Print("{0}", x.SampleProp2);
    }
    public class MyClass
    {
        public enum SampleEnum { Value0, Value1 , Value2 };
        public SampleEnum SampleProp1 { get; } = SampleEnum.Value1;
        public SampleEnum SampleProp2 { get { return SampleEnum.Value1; } }
    }
}
Steve In CO
  • 5,746
  • 2
  • 21
  • 32
  • The problem comes from the deserializer which is not executing the field initializer. Simply creating an instance of the class using `new` will work fine any way. – Dirk Vollmar Jul 15 '16 at 13:28
  • Yup. Just saw your answer about the same time as mine and upvoted yours. I hadn't considered serialization. Well done. – Steve In CO Jul 15 '16 at 13:30