Karthik
Karthik

Reputation: 1074

Why IEnumerable<T> returns null here?

Can anyone please tell me why method parameter IEnumerable returns null even though it is assigned at the callee method. We all know interface is an reference type.

Dont consider the logic. I just replaced my business logic to suit the scenario

static void Main()  
{   
  IEnumerable<int> gEnumerable = null;  
  Foo(gEnumerable);    //here param gEnumerable always returns null even if i assign  value at my Foo(), why is it so???  
}    

static IEnumerable<int> Bar(List<int> lst)         
{  
  return lst.Select(k => k);  
}  

private  static  void Foo(IEnumerable<int> response)  
{  
  response = Bar(new List<int> { 1, 2, 3, 4, 5, 6 });  
}

Kindly explain me regarding this

Upvotes: 0

Views: 628

Answers (3)

Ed Swangren
Ed Swangren

Reputation: 124790

We all know interface is an reference type.

You need to study up a bit on how arguments are passed in C#. Everything is passed by value (by default). In the case of a reference type, the reference is copied when passed to the function (because the reference is its value). So, you are assigning a new value to a copy of a reference and it is not seen by the caller.

If you truly need to assign a completely new value to the reference then you must use either the ref or out specifier. If your method guarantees that it will assign a new value to its input then use out.

Upvotes: 4

Brian Dishaw
Brian Dishaw

Reputation: 5825

You need to pass the argument using the Ref keyword so that you modify gEnumerable instead of create new enumerations that will be disposed as soon as they leave scope.

static void Main()  
{   
  IEnumerable<int> gEnumerable = null;  
  Foo(ref gEnumerable);    //here param gEnumerable always returns null even if i assign       value at my Foo(), why is it so???  
}    

static IEnumerable`<int>` Bar(List`<int>` lst)         
{  
   return lst.Select(k => k);  
}  

private  static  void Foo(ref IEnumerable`<int>` response)  
{  
  response = Bar(new List`<int>` { 1, 2, 3, 4, 5, 6 });  
}

Upvotes: 2

BrokenGlass
BrokenGlass

Reputation: 161012

You have to pass response by reference, otherwise you are not changing the original reference passed - you should avoid this approach if you can avoid it:

static void Main()  
{   
  IEnumerable<int> gEnumerable = null;  
  Foo(ref gEnumerable);    
} 
private  static void Foo(ref IEnumerable<int> response)  
{  
   response = Bar(new List<int> { 1, 2, 3, 4, 5, 6 });  
}

Why not just redesign and make Foo return the value you want though? That is much cleaner imo.

private  static IEnumerable<int> Foo()  
{  
   return Bar(new List<int> { 1, 2, 3, 4, 5, 6 });  
}

Upvotes: 3

Related Questions