views:

135

answers:

5

I've recently started learning C#. I just learned about properties and decided to make a simple program in order to understand them more. this is the code I wrote:

  class Dog
{
    private int weight;
    private string colour;
    public string colour { get; set; }
    public Dog(int theWeight, string theColour)
    {
        weight = theWeight;
        colour = theColour;
    }
}

And i get an ambiguity error. As far a I understand, this shouldn't happen.

+6  A: 

You have field and property with the same name colour. That is why the compiler produces an error.

DixonD
+4  A: 

You can't have both a field and a property with the same name.

You need to rename one of the two colour identifiers.

Lasse V. Karlsen
+5  A: 

ambiguity error is that you named field and property tha same name "colour". change the property definition f.e.

public string Colour
{
 get { return colour;}
 set { colour = value;}
}
Arseny
+3  A: 

In the line

colour = theColour;

the compiler can't tell what you mean. It could be either

private string colour;

or it could be

public string colour { get; set }

To disambiguate choosing a different naming convention helps. For example you could choose that properties have an uppercase first letter and fields start with an underscore and a lower case letter. In that case your class would look as follows:

class Dog
{
   private int _weight;
   private string _colour;
   public string Colour { get; set; }
   public Dog(int theWeight, string theColour)
   {
      _weight = theWeight;
      _colour = theColour;
   }
}

Note, though, that you probably have a duplication here anyways. Chances are that it wasn't your intention to have both the automatic property Colour and the field _colour in the first place.

You can also choose a tool to help you follow recommended guidelines. As an example have a look at FxCop. There is not right or wrong but it is certainly easier to work with rules that are generally accepted. (Admittedly my suggestion to use underscores for fields is not in line with what is generally accepted. However, I don't use public fields.)

John
using this way will end up with 2 different colour properties/variables. Probably the user only wants one (remove _colour)
PoweRoy
Yes. That's why I mentioned in my answer: "Note, though, that you probably have a duplication here anyways. Chances are that it wasn't your intention to have both the automatic property Colour and the field _colour in the first place."
John
A: 

Note that in your example, and if you're using C# 3.0 or above, you don't really those private fields and can use auto-implemented properties:

More details about it here... http://msdn.microsoft.com/en-us/library/bb384054.aspx

It will avoid the confusion problems, by either the programmer and the compiler, and improve readability.

Kharlos Dominguez