views:

82

answers:

3

Why is this valid

public struct MyStruct
{
    public MyStruct(double value)
    {
        myField = value;
    }

    private double myField;

    public double MyProperty
    {
        get
        {
            return myField;
        }
        set
        {
            myField = value;
        }
    }
}

and this is not

public struct MyStruct
{
    public MyStruct(double value)
    {
        MyProperty = value;
    }
    public double MyProperty
    { 
        get; 
        set;
    }
}
A: 

you don't need the get set, if you are not going to make then do anything. They should be used for type checking. To make the secound work remove: { get; set; }

Euclid
I still want the encapsulation provided by it being a property. removing the get;set; would change it to a field.
Simon
+2  A: 

You need this syntax:

public struct MyStruct 
{
    public MyStruct(double value) : this()
    {
        MyProperty = value;
    }

    public double MyProperty { get; set; }
}

I got that information from the following SO post.

David Hall
+3  A: 

Hi,

Can you change your constructor to this:

public MyStruct(double value)  : this()
{
    myField = value;
}

The reason is that you cant access properties until the backing fields have been populated. By calling the default constructor the auto implemented property backing field will get populated and then you can have access to the properties. The downside is that you are now setting the property twice (once in the base constructor and once in your constructor).

If you don't need to use properties and can use fields instead then you can avoid the problems.

Leigh Shayler