1

Can I use an extension method over a list that may be null, and if that is the case then instanciate it just inside the Extension method??

Instanciate the list INSIDE the extension method that applies over it... sounds like when you try to add or remove an item from a list that your are your are iterating with foreach loop.

public static void AddOrUpdate(this List<blabla> i, Person p)
{
i = i ?? new List<blabla>(); //Is it OK no instantiate inside?
i.RemoveAll(t => t.Id == p.Id && t.Role == RoleEnum.Admin);
i.Add(p); //Since it is a reference type, I dont need to return it (even "this" parameter) right?
}

And then use it like this:

//List<blabla> TeamWork comes from anywhere else, instantiated or not
TeamWork.AddOrUpdate(aPersonA);
TeamWork.AddOrUpdate(aPersonB);
DoSomething(Teamwork);
Ramankingdom
  • 1,478
  • 2
  • 12
  • 17
Fernando Torres
  • 1,070
  • 8
  • 19
  • it's ok to create extension method and use wherever they ease the programming task .As Explained by GUSMAN you cannot. As per me you should not do that. Will create confusions for other list of similar types. Better to go with a wrapper class which will fulfill you requirement. – Ramankingdom Jul 28 '17 at 04:15

1 Answers1

3

No, that will not work, for that the parameter should be passed as ref and you can't use ref combined with the this keyword.

But you can always do something likle this:

public static List<blabla> AddOrUpdate(this List<blabla> i, Person p)
{
    i = i ?? new List<blabla>();
    i.RemoveAll(t => t.Id == p.Id && t.Role == RoleEnum.Admin);
    i.Add(p);
    return i;
}

TeamWork = TeamWork.AddOrUpdate(aPersonA);
TeamWork = TeamWork.AddOrUpdate(aPersonB);
DoSomething(Teamwork);
Gusman
  • 14,905
  • 2
  • 34
  • 50
  • OK that's fine, no problem with that. But what about the part of new List(); INSIDE the extesion method? – Fernando Torres Jul 28 '17 at 04:04
  • 1
    @FernandoTorres what's the problem? you are returning the list and assigning it again to the original variable, if it's the old instance it will remain the same, if it's a new instance the reference will be updated, that's why you must reassign the variable. – Gusman Jul 28 '17 at 04:06
  • Instanciate the list INSIDE the extension method that applies over it... SOUNDS LIKE when you try to add or remove an item from a list that your are your are iterating with foreach loop. But you are right, it's just a "SOUNDS LIKE" issue :P – Fernando Torres Jul 28 '17 at 04:09