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?
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; }
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With