0

I have an observation which I couldnt figure what I am doing wrong with the way I am using List.

I have a list of a Custom Object called 'CalculateObj' as follows.

public List<CalculateObj> DoSomething(int case1)
{
  public List<CalculateObj> obj = new List<CalculateObj>();
  
 switch(case1)
{
  case 1 : 
         await DoSomethingElse(obj)
          break;
}
//Now this obj has count as 0
 return obj;
}

public Task DoSomethingElse(List<CalculateObj> obj)
{
  obj = await //Call a db table and populate
  //This obj has 5 items
}
 

I am creating List<CalculateObj> in DoSomething() and passing to DoSomethingElse() . In the DoSomethingElse() I see the list is populated with 5 rows.

But when the control goes back to DoSomething() , obj count is always 0. Why is this happening? Arent lists supposed to be Reference type?

VA1267
  • 145
  • 7
  • 1
    Unless you use `ref` or `out`, everything is passed by _value_ (i.e. a copy is made). It's just that for reference types, the thing that gets copied is the reference, not the instance of the type itself. The moment you assign a new value to the `obj` variable, it's now pointing at something else in memory. As indicated by [this question](https://stackoverflow.com/questions/65057089/in-c-sharp-what-is-the-benefit-of-passing-value-by-ref), you can use `ref` if you want the method to change where the original variable (i.e. the one in `DoSomething`) points to. – DiplomacyNotWar Feb 10 '22 at 07:29

0 Answers0