C#: Struct Constructor: "fields must be fully assigned before control is returned to the caller."

Posted by Rosarch on Stack Overflow See other posts from Stack Overflow or by Rosarch
Published on 2010-03-28T23:13:28Z Indexed on 2010/03/28 23:23 UTC
Read the original article Hit count: 914

Filed under:
|
|

Here is a struct I am trying to write:

  public struct AttackTraits
        {
            public AttackTraits(double probability, int damage, float distance)
            {
                Probability = probability;
                Distance = distance;
                Damage = damage;
            }

            private double probability;
            public double Probability
            {
                get
                {
                    return probability;
                }
                set
                {
                    if (value > 1 || value < 0)
                    {
                        throw new ArgumentOutOfRangeException("Probability values must be in the range [0, 1]");
                    }
                    probability = value;
                }
            }

            public int Damage { get; set; }

            public float Distance { get; set; }
        }

This results in the following compilation errors:

The 'this' object cannot be used before all of its fields are assigned to

Field 'AttackTraits.probability' must be fully assigned before control is returned to the caller

Backing field for automatically implemented property 'AttackTraits.Damage' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.

Backing field for automatically implemented property 'AttackTraits.Distance' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.

What am I doing wrong?

© Stack Overflow or respective owner

Related posts about c#

Related posts about struct