AddRange() is not working when adding list items to a CollectionHow do I clone a generic list in C#?Why is it important to override GetHashCode when Equals method is overridden?List<T> or IList<T>When to use struct?Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?How to Sort a List<T> by a property in the objectWhy to use ICollection<T> instead of List<T> and if i use ICollection<T>, then how can i use AddRange,Insert and other list methodsWhy not inherit from List<T>?Multi threading with a list of input in C#C# Serialize with JSON.NET inherited private fields

"syntax error near unexpected token" after editing .bashrc

Draw the ☣ (Biohazard Symbol)

How to create large inductors (1H) for audio use?

Why there are construction cranes on apparently completed buildings in New York?

Do 643,000 Americans go bankrupt every year due to medical bills?

What are some countries where you can be imprisoned for reading or owning a Bible?

Why does the UK Prime Minister need the permission of Parliament to call a general election?

Why did Boris Johnson call for new elections?

Magento 2: Set order history page as default after login

What is the purpose of the rotating plate in front of the lock?

Project Euler Problem 45

Golfball Dimples on spaceships (and planes)?

Matlab fmincon for a problem with many nonlinear constraints

In High Performance Liquid Chromatography, why are ratios of solvents used?

Why there is no wireless switch?

What does it mean to count a group of numbers with their multiplicity?

What's this constructed number's starter?

Does the Commodore CDTV-CR contain a 65C02 for some reason?

Is there some sort of French saying for "a person's signature move"?

Prove that a function is bijective and show that G is a group

Remaining in the US beyond VWP admission period

Ceiling fan electrical box missing female screw holes

Why would one hemisphere of a planet be very mountainous while the other is flat?

Is the interior of a Bag of Holding actually an extradimensional space?



AddRange() is not working when adding list items to a Collection


How do I clone a generic list in C#?Why is it important to override GetHashCode when Equals method is overridden?List<T> or IList<T>When to use struct?Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?How to Sort a List<T> by a property in the objectWhy to use ICollection<T> instead of List<T> and if i use ICollection<T>, then how can i use AddRange,Insert and other list methodsWhy not inherit from List<T>?Multi threading with a list of input in C#C# Serialize with JSON.NET inherited private fields






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








-2















Recently I got a task to work on one of the FxCop warning - Do not expose generic lists. So I tried changing the List<T> to ICollection<T>. But later point of time, while doing the unit testing I found that the AddRange() is not working properly as expected. It is not adding the collection of elements to the collection object.



Here is the sample code



gc.ToList().AddRange(sampleList);


And I have two questions to ask




  1. Why it is not adding the items to the collection.
    Below is the code:



    public class GenericClass

    public int Id;
    public string Name;



    class Program

    static void Main(string[] args)


    ICollection<GenericClass> gc = new List<GenericClass>();

    var sampleList = new List<GenericClass>()

    new GenericClass Id = 1, Name = "ASD",
    new GenericClass Id = 2, Name = "QWER",
    new GenericClass Id = 3, Name = "BNMV",
    ;

    Console.WriteLine(gc.GetType()); // gc is of type

    gc.ToList().AddRange(sampleList); // sampleList items are not getting added to gc.
    Console.ReadKey();





  2. List<T> inherits from ICollection<T> and List<T> has AddRange(), etc functions. When I tried to cast to parent reference (ICollection<T>) to child class object (List<T>), why doesn't Intellisense suggest AddRange(). Instead I need to do .ToList() and then it shows AddRange().
    Screenshot


I searched a lot for this. But couldn't find a reason that satisfied me. So please help me with the understanding. It will be a great help.










share|improve this question


























  • Change ICollection<GenericClass> to var. There is no reason to use ICollection<GenericClass> in that context.

    – mjwills
    Mar 28 at 5:21











  • But couldn't find a reason that satisfied me. You told gc that it was a ICollection. ICollection lacks AddRange (it does have Add but not AddRange). It really is that simple. The solution is to use var so that the compiler knows that gc is a List.

    – mjwills
    Mar 28 at 5:22












  • Do not expose generic lists. You aren't exposing lists anywhere. Unless you are returning the list from a function, or declaring a property / field as List then you aren't exposing it. 95% of the time in those scenarios (which, again, you aren't in) then you would define the property / field / return type as IReadOnlyList<T> It avoids the issues with IList<T>.

    – mjwills
    Mar 28 at 5:25


















-2















Recently I got a task to work on one of the FxCop warning - Do not expose generic lists. So I tried changing the List<T> to ICollection<T>. But later point of time, while doing the unit testing I found that the AddRange() is not working properly as expected. It is not adding the collection of elements to the collection object.



Here is the sample code



gc.ToList().AddRange(sampleList);


And I have two questions to ask




  1. Why it is not adding the items to the collection.
    Below is the code:



    public class GenericClass

    public int Id;
    public string Name;



    class Program

    static void Main(string[] args)


    ICollection<GenericClass> gc = new List<GenericClass>();

    var sampleList = new List<GenericClass>()

    new GenericClass Id = 1, Name = "ASD",
    new GenericClass Id = 2, Name = "QWER",
    new GenericClass Id = 3, Name = "BNMV",
    ;

    Console.WriteLine(gc.GetType()); // gc is of type

    gc.ToList().AddRange(sampleList); // sampleList items are not getting added to gc.
    Console.ReadKey();





  2. List<T> inherits from ICollection<T> and List<T> has AddRange(), etc functions. When I tried to cast to parent reference (ICollection<T>) to child class object (List<T>), why doesn't Intellisense suggest AddRange(). Instead I need to do .ToList() and then it shows AddRange().
    Screenshot


I searched a lot for this. But couldn't find a reason that satisfied me. So please help me with the understanding. It will be a great help.










share|improve this question


























  • Change ICollection<GenericClass> to var. There is no reason to use ICollection<GenericClass> in that context.

    – mjwills
    Mar 28 at 5:21











  • But couldn't find a reason that satisfied me. You told gc that it was a ICollection. ICollection lacks AddRange (it does have Add but not AddRange). It really is that simple. The solution is to use var so that the compiler knows that gc is a List.

    – mjwills
    Mar 28 at 5:22












  • Do not expose generic lists. You aren't exposing lists anywhere. Unless you are returning the list from a function, or declaring a property / field as List then you aren't exposing it. 95% of the time in those scenarios (which, again, you aren't in) then you would define the property / field / return type as IReadOnlyList<T> It avoids the issues with IList<T>.

    – mjwills
    Mar 28 at 5:25














-2












-2








-2


2






Recently I got a task to work on one of the FxCop warning - Do not expose generic lists. So I tried changing the List<T> to ICollection<T>. But later point of time, while doing the unit testing I found that the AddRange() is not working properly as expected. It is not adding the collection of elements to the collection object.



Here is the sample code



gc.ToList().AddRange(sampleList);


And I have two questions to ask




  1. Why it is not adding the items to the collection.
    Below is the code:



    public class GenericClass

    public int Id;
    public string Name;



    class Program

    static void Main(string[] args)


    ICollection<GenericClass> gc = new List<GenericClass>();

    var sampleList = new List<GenericClass>()

    new GenericClass Id = 1, Name = "ASD",
    new GenericClass Id = 2, Name = "QWER",
    new GenericClass Id = 3, Name = "BNMV",
    ;

    Console.WriteLine(gc.GetType()); // gc is of type

    gc.ToList().AddRange(sampleList); // sampleList items are not getting added to gc.
    Console.ReadKey();





  2. List<T> inherits from ICollection<T> and List<T> has AddRange(), etc functions. When I tried to cast to parent reference (ICollection<T>) to child class object (List<T>), why doesn't Intellisense suggest AddRange(). Instead I need to do .ToList() and then it shows AddRange().
    Screenshot


I searched a lot for this. But couldn't find a reason that satisfied me. So please help me with the understanding. It will be a great help.










share|improve this question
















Recently I got a task to work on one of the FxCop warning - Do not expose generic lists. So I tried changing the List<T> to ICollection<T>. But later point of time, while doing the unit testing I found that the AddRange() is not working properly as expected. It is not adding the collection of elements to the collection object.



Here is the sample code



gc.ToList().AddRange(sampleList);


And I have two questions to ask




  1. Why it is not adding the items to the collection.
    Below is the code:



    public class GenericClass

    public int Id;
    public string Name;



    class Program

    static void Main(string[] args)


    ICollection<GenericClass> gc = new List<GenericClass>();

    var sampleList = new List<GenericClass>()

    new GenericClass Id = 1, Name = "ASD",
    new GenericClass Id = 2, Name = "QWER",
    new GenericClass Id = 3, Name = "BNMV",
    ;

    Console.WriteLine(gc.GetType()); // gc is of type

    gc.ToList().AddRange(sampleList); // sampleList items are not getting added to gc.
    Console.ReadKey();





  2. List<T> inherits from ICollection<T> and List<T> has AddRange(), etc functions. When I tried to cast to parent reference (ICollection<T>) to child class object (List<T>), why doesn't Intellisense suggest AddRange(). Instead I need to do .ToList() and then it shows AddRange().
    Screenshot


I searched a lot for this. But couldn't find a reason that satisfied me. So please help me with the understanding. It will be a great help.







c# generics generic-collections






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 28 at 4:57









Peter Duniho

51.4k4 gold badges56 silver badges91 bronze badges




51.4k4 gold badges56 silver badges91 bronze badges










asked Mar 28 at 4:40









VijayVijay

133 bronze badges




133 bronze badges















  • Change ICollection<GenericClass> to var. There is no reason to use ICollection<GenericClass> in that context.

    – mjwills
    Mar 28 at 5:21











  • But couldn't find a reason that satisfied me. You told gc that it was a ICollection. ICollection lacks AddRange (it does have Add but not AddRange). It really is that simple. The solution is to use var so that the compiler knows that gc is a List.

    – mjwills
    Mar 28 at 5:22












  • Do not expose generic lists. You aren't exposing lists anywhere. Unless you are returning the list from a function, or declaring a property / field as List then you aren't exposing it. 95% of the time in those scenarios (which, again, you aren't in) then you would define the property / field / return type as IReadOnlyList<T> It avoids the issues with IList<T>.

    – mjwills
    Mar 28 at 5:25


















  • Change ICollection<GenericClass> to var. There is no reason to use ICollection<GenericClass> in that context.

    – mjwills
    Mar 28 at 5:21











  • But couldn't find a reason that satisfied me. You told gc that it was a ICollection. ICollection lacks AddRange (it does have Add but not AddRange). It really is that simple. The solution is to use var so that the compiler knows that gc is a List.

    – mjwills
    Mar 28 at 5:22












  • Do not expose generic lists. You aren't exposing lists anywhere. Unless you are returning the list from a function, or declaring a property / field as List then you aren't exposing it. 95% of the time in those scenarios (which, again, you aren't in) then you would define the property / field / return type as IReadOnlyList<T> It avoids the issues with IList<T>.

    – mjwills
    Mar 28 at 5:25

















Change ICollection<GenericClass> to var. There is no reason to use ICollection<GenericClass> in that context.

– mjwills
Mar 28 at 5:21





Change ICollection<GenericClass> to var. There is no reason to use ICollection<GenericClass> in that context.

– mjwills
Mar 28 at 5:21













But couldn't find a reason that satisfied me. You told gc that it was a ICollection. ICollection lacks AddRange (it does have Add but not AddRange). It really is that simple. The solution is to use var so that the compiler knows that gc is a List.

– mjwills
Mar 28 at 5:22






But couldn't find a reason that satisfied me. You told gc that it was a ICollection. ICollection lacks AddRange (it does have Add but not AddRange). It really is that simple. The solution is to use var so that the compiler knows that gc is a List.

– mjwills
Mar 28 at 5:22














Do not expose generic lists. You aren't exposing lists anywhere. Unless you are returning the list from a function, or declaring a property / field as List then you aren't exposing it. 95% of the time in those scenarios (which, again, you aren't in) then you would define the property / field / return type as IReadOnlyList<T> It avoids the issues with IList<T>.

– mjwills
Mar 28 at 5:25






Do not expose generic lists. You aren't exposing lists anywhere. Unless you are returning the list from a function, or declaring a property / field as List then you aren't exposing it. 95% of the time in those scenarios (which, again, you aren't in) then you would define the property / field / return type as IReadOnlyList<T> It avoids the issues with IList<T>.

– mjwills
Mar 28 at 5:25













2 Answers
2






active

oldest

votes


















2
















The AddRange() method is working fine. The problem is, you didn't read the documentation for the ToList() extension method closely, and so don't realize that the ToList() method returns an entirely new object.



From the documentation:




Creates a List<T> from an IEnumerable<T>.




Since the object you're calling AddRange() with is not in fact the original collection, the original collection remains unchanged.



In a sense, your question is the List<T> equivalent to the very common question "why isn't string.Replace() working?"



In the example you give, there is not really a much better solution than simply not hiding the List<T> in the first place. You can, since you are using the generic ICollection<T> interface, write your own AddRange() as an extension method:



public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> range)

foreach (T t in range)

collection.Add(t);




But I'm not convinced this is really all that much better than just leaving the type as List<T>, if the goal is to be able to modify the object and use an AddRange() method.



Casting an ICollection<T> reference back to its underlying List<T> (as another answerer proposes) is pointless, as doing so would negate any value in using the ICollection<T> interface in the first place.



Just leave the reference as List<T>, at least in any context where you actually need to modify the collection. (It's fine, and even possibly beneficial, to expose that list in other contexts using only ICollection<T>, but that's an entirely different discussion.)



As long as I'm answering, I will mention that I am skeptical that you've correctly understood the intent of the FxCop warning, as exposing generic lists is not in and of itself inherently harmful.






share|improve this answer



























  • ICollection<T> interface doesn't allow modification of the collection at all. Could you please elaborate on that statement. And can you provide a resolution of how to add items to the collection object then??

    – Vijay
    Mar 28 at 5:17







  • 2





    ICollection<T> interface doesn't allow modification of the collection at all. That is false. docs.microsoft.com/en-us/dotnet/api/…

    – mjwills
    Mar 28 at 5:23











  • ICollection<T> interface doesn't allow modification of the collection at all. But when I am trying to do a ToList().AddRange(simpleList). Why doesn't the list is getting appended to the collection object. gc.ToList().AddRange(sampleList);

    – Vijay
    Mar 28 at 6:18












  • @mjwills: thanks...you won't believe it, but I did in fact look at the docs, was sure there was an Add() method, but couldn't find it, and so wrote what I did. Looks like I got confused about ICollection vs ICollection<T> (the OP's original post had some formatting issues, and the generic syntax wasn't showing up).

    – Peter Duniho
    Mar 28 at 6:54







  • 1





    @Vijay: while I wrote ICollection<T> in my statement, what I was actually thinking of was ICollection. You can modify ICollection<T>...see my edited answer above. As for this: "Why doesn't the list is getting appended to the collection object", I answered that directly in my first paragraph: when you call AddRange(), the this object the method applies to is not the gc object you started with. It's the entirely new List<T> object that was returned by the ToList() method.

    – Peter Duniho
    Mar 28 at 7:02



















1
















ToList() returns a new instance, which is why you are not able to see the result of AddRange in "gc". If you really want to use AddRange, you can do the following.



((List<GenericClass>)gc).AddRange(sampleList);





share|improve this answer

























  • Could you please be more specific about statement as after I put .ToList() to the object, then only I am see the AddRange function. Is your answer is about question (1) or (2)

    – Vijay
    Mar 28 at 5:12













Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55390284%2faddrange-is-not-working-when-adding-list-items-to-a-collection%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









2
















The AddRange() method is working fine. The problem is, you didn't read the documentation for the ToList() extension method closely, and so don't realize that the ToList() method returns an entirely new object.



From the documentation:




Creates a List<T> from an IEnumerable<T>.




Since the object you're calling AddRange() with is not in fact the original collection, the original collection remains unchanged.



In a sense, your question is the List<T> equivalent to the very common question "why isn't string.Replace() working?"



In the example you give, there is not really a much better solution than simply not hiding the List<T> in the first place. You can, since you are using the generic ICollection<T> interface, write your own AddRange() as an extension method:



public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> range)

foreach (T t in range)

collection.Add(t);




But I'm not convinced this is really all that much better than just leaving the type as List<T>, if the goal is to be able to modify the object and use an AddRange() method.



Casting an ICollection<T> reference back to its underlying List<T> (as another answerer proposes) is pointless, as doing so would negate any value in using the ICollection<T> interface in the first place.



Just leave the reference as List<T>, at least in any context where you actually need to modify the collection. (It's fine, and even possibly beneficial, to expose that list in other contexts using only ICollection<T>, but that's an entirely different discussion.)



As long as I'm answering, I will mention that I am skeptical that you've correctly understood the intent of the FxCop warning, as exposing generic lists is not in and of itself inherently harmful.






share|improve this answer



























  • ICollection<T> interface doesn't allow modification of the collection at all. Could you please elaborate on that statement. And can you provide a resolution of how to add items to the collection object then??

    – Vijay
    Mar 28 at 5:17







  • 2





    ICollection<T> interface doesn't allow modification of the collection at all. That is false. docs.microsoft.com/en-us/dotnet/api/…

    – mjwills
    Mar 28 at 5:23











  • ICollection<T> interface doesn't allow modification of the collection at all. But when I am trying to do a ToList().AddRange(simpleList). Why doesn't the list is getting appended to the collection object. gc.ToList().AddRange(sampleList);

    – Vijay
    Mar 28 at 6:18












  • @mjwills: thanks...you won't believe it, but I did in fact look at the docs, was sure there was an Add() method, but couldn't find it, and so wrote what I did. Looks like I got confused about ICollection vs ICollection<T> (the OP's original post had some formatting issues, and the generic syntax wasn't showing up).

    – Peter Duniho
    Mar 28 at 6:54







  • 1





    @Vijay: while I wrote ICollection<T> in my statement, what I was actually thinking of was ICollection. You can modify ICollection<T>...see my edited answer above. As for this: "Why doesn't the list is getting appended to the collection object", I answered that directly in my first paragraph: when you call AddRange(), the this object the method applies to is not the gc object you started with. It's the entirely new List<T> object that was returned by the ToList() method.

    – Peter Duniho
    Mar 28 at 7:02
















2
















The AddRange() method is working fine. The problem is, you didn't read the documentation for the ToList() extension method closely, and so don't realize that the ToList() method returns an entirely new object.



From the documentation:




Creates a List<T> from an IEnumerable<T>.




Since the object you're calling AddRange() with is not in fact the original collection, the original collection remains unchanged.



In a sense, your question is the List<T> equivalent to the very common question "why isn't string.Replace() working?"



In the example you give, there is not really a much better solution than simply not hiding the List<T> in the first place. You can, since you are using the generic ICollection<T> interface, write your own AddRange() as an extension method:



public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> range)

foreach (T t in range)

collection.Add(t);




But I'm not convinced this is really all that much better than just leaving the type as List<T>, if the goal is to be able to modify the object and use an AddRange() method.



Casting an ICollection<T> reference back to its underlying List<T> (as another answerer proposes) is pointless, as doing so would negate any value in using the ICollection<T> interface in the first place.



Just leave the reference as List<T>, at least in any context where you actually need to modify the collection. (It's fine, and even possibly beneficial, to expose that list in other contexts using only ICollection<T>, but that's an entirely different discussion.)



As long as I'm answering, I will mention that I am skeptical that you've correctly understood the intent of the FxCop warning, as exposing generic lists is not in and of itself inherently harmful.






share|improve this answer



























  • ICollection<T> interface doesn't allow modification of the collection at all. Could you please elaborate on that statement. And can you provide a resolution of how to add items to the collection object then??

    – Vijay
    Mar 28 at 5:17







  • 2





    ICollection<T> interface doesn't allow modification of the collection at all. That is false. docs.microsoft.com/en-us/dotnet/api/…

    – mjwills
    Mar 28 at 5:23











  • ICollection<T> interface doesn't allow modification of the collection at all. But when I am trying to do a ToList().AddRange(simpleList). Why doesn't the list is getting appended to the collection object. gc.ToList().AddRange(sampleList);

    – Vijay
    Mar 28 at 6:18












  • @mjwills: thanks...you won't believe it, but I did in fact look at the docs, was sure there was an Add() method, but couldn't find it, and so wrote what I did. Looks like I got confused about ICollection vs ICollection<T> (the OP's original post had some formatting issues, and the generic syntax wasn't showing up).

    – Peter Duniho
    Mar 28 at 6:54







  • 1





    @Vijay: while I wrote ICollection<T> in my statement, what I was actually thinking of was ICollection. You can modify ICollection<T>...see my edited answer above. As for this: "Why doesn't the list is getting appended to the collection object", I answered that directly in my first paragraph: when you call AddRange(), the this object the method applies to is not the gc object you started with. It's the entirely new List<T> object that was returned by the ToList() method.

    – Peter Duniho
    Mar 28 at 7:02














2














2










2









The AddRange() method is working fine. The problem is, you didn't read the documentation for the ToList() extension method closely, and so don't realize that the ToList() method returns an entirely new object.



From the documentation:




Creates a List<T> from an IEnumerable<T>.




Since the object you're calling AddRange() with is not in fact the original collection, the original collection remains unchanged.



In a sense, your question is the List<T> equivalent to the very common question "why isn't string.Replace() working?"



In the example you give, there is not really a much better solution than simply not hiding the List<T> in the first place. You can, since you are using the generic ICollection<T> interface, write your own AddRange() as an extension method:



public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> range)

foreach (T t in range)

collection.Add(t);




But I'm not convinced this is really all that much better than just leaving the type as List<T>, if the goal is to be able to modify the object and use an AddRange() method.



Casting an ICollection<T> reference back to its underlying List<T> (as another answerer proposes) is pointless, as doing so would negate any value in using the ICollection<T> interface in the first place.



Just leave the reference as List<T>, at least in any context where you actually need to modify the collection. (It's fine, and even possibly beneficial, to expose that list in other contexts using only ICollection<T>, but that's an entirely different discussion.)



As long as I'm answering, I will mention that I am skeptical that you've correctly understood the intent of the FxCop warning, as exposing generic lists is not in and of itself inherently harmful.






share|improve this answer















The AddRange() method is working fine. The problem is, you didn't read the documentation for the ToList() extension method closely, and so don't realize that the ToList() method returns an entirely new object.



From the documentation:




Creates a List<T> from an IEnumerable<T>.




Since the object you're calling AddRange() with is not in fact the original collection, the original collection remains unchanged.



In a sense, your question is the List<T> equivalent to the very common question "why isn't string.Replace() working?"



In the example you give, there is not really a much better solution than simply not hiding the List<T> in the first place. You can, since you are using the generic ICollection<T> interface, write your own AddRange() as an extension method:



public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> range)

foreach (T t in range)

collection.Add(t);




But I'm not convinced this is really all that much better than just leaving the type as List<T>, if the goal is to be able to modify the object and use an AddRange() method.



Casting an ICollection<T> reference back to its underlying List<T> (as another answerer proposes) is pointless, as doing so would negate any value in using the ICollection<T> interface in the first place.



Just leave the reference as List<T>, at least in any context where you actually need to modify the collection. (It's fine, and even possibly beneficial, to expose that list in other contexts using only ICollection<T>, but that's an entirely different discussion.)



As long as I'm answering, I will mention that I am skeptical that you've correctly understood the intent of the FxCop warning, as exposing generic lists is not in and of itself inherently harmful.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 28 at 7:05

























answered Mar 28 at 4:45









Peter DunihoPeter Duniho

51.4k4 gold badges56 silver badges91 bronze badges




51.4k4 gold badges56 silver badges91 bronze badges















  • ICollection<T> interface doesn't allow modification of the collection at all. Could you please elaborate on that statement. And can you provide a resolution of how to add items to the collection object then??

    – Vijay
    Mar 28 at 5:17







  • 2





    ICollection<T> interface doesn't allow modification of the collection at all. That is false. docs.microsoft.com/en-us/dotnet/api/…

    – mjwills
    Mar 28 at 5:23











  • ICollection<T> interface doesn't allow modification of the collection at all. But when I am trying to do a ToList().AddRange(simpleList). Why doesn't the list is getting appended to the collection object. gc.ToList().AddRange(sampleList);

    – Vijay
    Mar 28 at 6:18












  • @mjwills: thanks...you won't believe it, but I did in fact look at the docs, was sure there was an Add() method, but couldn't find it, and so wrote what I did. Looks like I got confused about ICollection vs ICollection<T> (the OP's original post had some formatting issues, and the generic syntax wasn't showing up).

    – Peter Duniho
    Mar 28 at 6:54







  • 1





    @Vijay: while I wrote ICollection<T> in my statement, what I was actually thinking of was ICollection. You can modify ICollection<T>...see my edited answer above. As for this: "Why doesn't the list is getting appended to the collection object", I answered that directly in my first paragraph: when you call AddRange(), the this object the method applies to is not the gc object you started with. It's the entirely new List<T> object that was returned by the ToList() method.

    – Peter Duniho
    Mar 28 at 7:02


















  • ICollection<T> interface doesn't allow modification of the collection at all. Could you please elaborate on that statement. And can you provide a resolution of how to add items to the collection object then??

    – Vijay
    Mar 28 at 5:17







  • 2





    ICollection<T> interface doesn't allow modification of the collection at all. That is false. docs.microsoft.com/en-us/dotnet/api/…

    – mjwills
    Mar 28 at 5:23











  • ICollection<T> interface doesn't allow modification of the collection at all. But when I am trying to do a ToList().AddRange(simpleList). Why doesn't the list is getting appended to the collection object. gc.ToList().AddRange(sampleList);

    – Vijay
    Mar 28 at 6:18












  • @mjwills: thanks...you won't believe it, but I did in fact look at the docs, was sure there was an Add() method, but couldn't find it, and so wrote what I did. Looks like I got confused about ICollection vs ICollection<T> (the OP's original post had some formatting issues, and the generic syntax wasn't showing up).

    – Peter Duniho
    Mar 28 at 6:54







  • 1





    @Vijay: while I wrote ICollection<T> in my statement, what I was actually thinking of was ICollection. You can modify ICollection<T>...see my edited answer above. As for this: "Why doesn't the list is getting appended to the collection object", I answered that directly in my first paragraph: when you call AddRange(), the this object the method applies to is not the gc object you started with. It's the entirely new List<T> object that was returned by the ToList() method.

    – Peter Duniho
    Mar 28 at 7:02

















ICollection<T> interface doesn't allow modification of the collection at all. Could you please elaborate on that statement. And can you provide a resolution of how to add items to the collection object then??

– Vijay
Mar 28 at 5:17






ICollection<T> interface doesn't allow modification of the collection at all. Could you please elaborate on that statement. And can you provide a resolution of how to add items to the collection object then??

– Vijay
Mar 28 at 5:17





2




2





ICollection<T> interface doesn't allow modification of the collection at all. That is false. docs.microsoft.com/en-us/dotnet/api/…

– mjwills
Mar 28 at 5:23





ICollection<T> interface doesn't allow modification of the collection at all. That is false. docs.microsoft.com/en-us/dotnet/api/…

– mjwills
Mar 28 at 5:23













ICollection<T> interface doesn't allow modification of the collection at all. But when I am trying to do a ToList().AddRange(simpleList). Why doesn't the list is getting appended to the collection object. gc.ToList().AddRange(sampleList);

– Vijay
Mar 28 at 6:18






ICollection<T> interface doesn't allow modification of the collection at all. But when I am trying to do a ToList().AddRange(simpleList). Why doesn't the list is getting appended to the collection object. gc.ToList().AddRange(sampleList);

– Vijay
Mar 28 at 6:18














@mjwills: thanks...you won't believe it, but I did in fact look at the docs, was sure there was an Add() method, but couldn't find it, and so wrote what I did. Looks like I got confused about ICollection vs ICollection<T> (the OP's original post had some formatting issues, and the generic syntax wasn't showing up).

– Peter Duniho
Mar 28 at 6:54






@mjwills: thanks...you won't believe it, but I did in fact look at the docs, was sure there was an Add() method, but couldn't find it, and so wrote what I did. Looks like I got confused about ICollection vs ICollection<T> (the OP's original post had some formatting issues, and the generic syntax wasn't showing up).

– Peter Duniho
Mar 28 at 6:54





1




1





@Vijay: while I wrote ICollection<T> in my statement, what I was actually thinking of was ICollection. You can modify ICollection<T>...see my edited answer above. As for this: "Why doesn't the list is getting appended to the collection object", I answered that directly in my first paragraph: when you call AddRange(), the this object the method applies to is not the gc object you started with. It's the entirely new List<T> object that was returned by the ToList() method.

– Peter Duniho
Mar 28 at 7:02






@Vijay: while I wrote ICollection<T> in my statement, what I was actually thinking of was ICollection. You can modify ICollection<T>...see my edited answer above. As for this: "Why doesn't the list is getting appended to the collection object", I answered that directly in my first paragraph: when you call AddRange(), the this object the method applies to is not the gc object you started with. It's the entirely new List<T> object that was returned by the ToList() method.

– Peter Duniho
Mar 28 at 7:02














1
















ToList() returns a new instance, which is why you are not able to see the result of AddRange in "gc". If you really want to use AddRange, you can do the following.



((List<GenericClass>)gc).AddRange(sampleList);





share|improve this answer

























  • Could you please be more specific about statement as after I put .ToList() to the object, then only I am see the AddRange function. Is your answer is about question (1) or (2)

    – Vijay
    Mar 28 at 5:12















1
















ToList() returns a new instance, which is why you are not able to see the result of AddRange in "gc". If you really want to use AddRange, you can do the following.



((List<GenericClass>)gc).AddRange(sampleList);





share|improve this answer

























  • Could you please be more specific about statement as after I put .ToList() to the object, then only I am see the AddRange function. Is your answer is about question (1) or (2)

    – Vijay
    Mar 28 at 5:12













1














1










1









ToList() returns a new instance, which is why you are not able to see the result of AddRange in "gc". If you really want to use AddRange, you can do the following.



((List<GenericClass>)gc).AddRange(sampleList);





share|improve this answer













ToList() returns a new instance, which is why you are not able to see the result of AddRange in "gc". If you really want to use AddRange, you can do the following.



((List<GenericClass>)gc).AddRange(sampleList);






share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 28 at 4:47









Anu ViswanAnu Viswan

7,3602 gold badges5 silver badges26 bronze badges




7,3602 gold badges5 silver badges26 bronze badges















  • Could you please be more specific about statement as after I put .ToList() to the object, then only I am see the AddRange function. Is your answer is about question (1) or (2)

    – Vijay
    Mar 28 at 5:12

















  • Could you please be more specific about statement as after I put .ToList() to the object, then only I am see the AddRange function. Is your answer is about question (1) or (2)

    – Vijay
    Mar 28 at 5:12
















Could you please be more specific about statement as after I put .ToList() to the object, then only I am see the AddRange function. Is your answer is about question (1) or (2)

– Vijay
Mar 28 at 5:12





Could you please be more specific about statement as after I put .ToList() to the object, then only I am see the AddRange function. Is your answer is about question (1) or (2)

– Vijay
Mar 28 at 5:12

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55390284%2faddrange-is-not-working-when-adding-list-items-to-a-collection%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해