Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access own class properties during creation

Tags:

c#

When initially creating a new class record, how can you access its own properties?

Below is my example structure which I am wanting to set Total as the sum of No1 and No2

    class ROWDATA
    {
        public int No1;
        public int No2;
        public int Total;
    }

    ROWDATA RowData = new ROWDATA
    {
        No1 = reader.GetInt32(reader.GetOrdinal("fuel_tank_no_1")),
        No2 = reader.GetInt32(reader.GetOrdinal("fuel_tank_no_2")),
        Total = No1 + No2 // this does not work
     };

I get an error stating that The name 'No1' does not exist in the current context

like image 432
Dan Avatar asked Mar 24 '26 05:03

Dan


2 Answers

You can update the Total property like this:

public int Total { get { return No1 + No2; } }

You can use this also:

var RowDataNo1 = reader.GetInt32(reader.GetOrdinal("fuel_tank_no_1"));
var RowDataNo2 = reader.GetInt32(reader.GetOrdinal("fuel_tank_no_2"));

ROWDATA RowData = new ROWDATA 
{
   No1 = RowDataNo1,
   No2 = RowDataNo2,
   Total = RowDataNo1 + RowDataNo2
};
like image 126
Shmwel Avatar answered Mar 26 '26 20:03

Shmwel


You are using object initialiser syntax and in there you do not have access to read properties. You can either use the two values you've already read or change the property.

Using the values

ROWDATA RowData = new ROWDATA
{
    No1 = reader.GetInt32(reader.GetOrdinal("fuel_tank_no_1")),
    No2 = reader.GetInt32(reader.GetOrdinal("fuel_tank_no_2")),
    Total = reader.GetInt32(reader.GetOrdinal("fuel_tank_no_1")) + 
            reader.GetInt32(reader.GetOrdinal("fuel_tank_no_2"))
 };

In this case it would probably be preferable to store the values in variables and use them rather than repeated access to the reader object.

Change Total Property

The preferred option is to change your Total property to something like this:

public int Total
{
    get { return No1 + No2; }
}
like image 21
DavidG Avatar answered Mar 26 '26 18:03

DavidG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!