Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Already contains a definition for

I have a class called Assign and

    private int SeatNumber;

    public Assign(int SeatNum)
    {
        SeatNumber = SeatNum;
    }

    public int SeatNumber
    {
        get { return SeatNumber; }
        set { SeatNumber = value; }

    }

I have no idea why I am getting the following error

EThe type 'WindowsFormsApplication1.Assign' already contains a definition for 'SeatNumber'

What is wrong?

like image 763
Kostas Mar Avatar asked Dec 07 '12 19:12

Kostas Mar


2 Answers

You're declaring the same variable twice here.

private int SeatNumber;
public int SeatNumber
{
    get { return SeatNumber; }
    set { SeatNumber = value; }

}

That code defines the same variable twice. If you're using .net 3.0+, you can do auto-implemented properties like this with no private int SeatNumber:

public int SeatNumber
{
    get;
    set;
}

otherwise, you should do this:

private int SeatNumber_;
public int SeatNumber
{
    get { return SeatNumber_; }
    set { SeatNumber_ = value; }
}
like image 198
Mike Corcoran Avatar answered Oct 01 '22 03:10

Mike Corcoran


You should make sure that the variable that backs the property has a different name. It is common to use camelCase for it:

private int seatNumber;

public Assign(int SeatNum)
{
    SeatNumber = SeatNum;
}

public int SeatNumber
{
    get { return seatNumber; }
    set { seatNumber = value; }
}

Moreover, in situations where the getter ans setter are trivial, starting with C# 3.0 you can use automatic properties, like this:

public int SeatNumber {get; set;}

This lets you remove the backing variable: the compiler will take care of it for you.

like image 37
Sergey Kalinichenko Avatar answered Oct 01 '22 03:10

Sergey Kalinichenko