Dan
Dan

Reputation: 313

Access own class properties during creation

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

Upvotes: 2

Views: 108

Answers (3)

Shmwel
Shmwel

Reputation: 1697

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
};

Upvotes: 4

ClickRick
ClickRick

Reputation: 1568

As stated by DavidG, you do not have access to get property accessors when using object initialiser syntax.

The C# specification1 specifically states

It is not possible for an object or collection initializer to refer to the object instance being initialized.


1 Specifically, C# 3.0 spec, section 26.4 Object and Collection Initializers

Upvotes: 3

DavidG
DavidG

Reputation: 119156

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; }
}

Upvotes: 4

Related Questions