Suwandy
Suwandy

Reputation: 45

C# Change Object Value Through Another Class

I'm trying to change an object value from other class. Ideally, I want to pass the object as parameter into constructor/method. What I've read so far, object behaves as reference when passed as parameter, and parameter value are copied locally for use in the method's body. So here are few configuration that I tested:

Case #1. Failed

class Processor 
{
   DataTable table;

   public Processor(DataTable table)
   {
       this.table = table;
   }

   public void InitializeTable()
   {
       if (table != null)
       {
           // Fill data into DataTable.
       }
   }
}

static void Main(string[] args) 
{
   DataTable mainTable = new DataTable();

   Processor processor = new Processor(mainTable);
   processor.InitializeTable();
   // mainTable still empty       
}

I thought Processor table holds the same reference to mainTable, but by the end of Main execution mainTable was still EMPTY while Processor table was filled.

Case #2. Failed

public Processor(ref DataTable table)
{
   this.table = table;
}

I've tried using ref signature, but result still the same (mainTable was EMPTY).

Case #3. Failed

public void InitializeTable(DataTable table)
{
   // Fill data into table
}

I've removed the constructor and feed mainTable into InitializeTable() method, and result still the same (mainTable was EMPTY).

Case #4. Works!

public void InitializeTable(ref DataTable table)
{
   // Fill data into table
}

Finally this works! Feeding ref mainTable into InitializeTable now fills mainTable successfully. What are the explanation behind this? Why constructor didn't have the same reference to mainTable? Why ref keyword still needed when passing object as parameter already means passing its reference?

Upvotes: 0

Views: 2209

Answers (1)

Suwandy
Suwandy

Reputation: 45

Credit goes to David:

Then that explains the behavior. You're re-assigning the local table variable to a new DataTable instance (returned by .SelectArray()). So it no longer refers to the same instance as the mainTable variable and no longer modifies that instance.

Upvotes: 1

Related Questions