I have a list and a string
var Resnames= new List<string>();
string name = "something";
I want to append string to it like
Resnames += name;
How can I do it
You can't append to an array. When you define the array variable, C asks the is for enough contiguous memory. That's all the memory you ever get. You can modify the elements of the array (A[10]=5) but not the size.
Use the Add() method or object initializer syntax to add elements in an ArrayList . An ArrayList can contain multiple null and duplicate values. Use the AddRange(ICollection c) method to add an entire Array, HashTable, SortedList, ArrayList , BitArray , Queue, and Stack in the ArrayList .
ArrayLists vs Lists in C# The List class must always be preferred over the ArrayList class because of the casting overhead in the ArrayList class. The List class can save us from run-time errors faced due to the different data types of the ArrayList class elements.
Since you are using List (not a legacy fixed-size array) you able to use List.Add() method:
resourceNames.Add(name);
If you want to add an item after the instantiation of a list instance you can use object initialization (since C# 3.0):
var resourceNames = new List<string> { "something", "onemore" };
Also you might find useful List.AddRange() method as well
var resourceNames = new List<string>();
resourceNames.Add("Res1");
resourceNames.Add("Res2");
var otherNames = new List<string>();
otherNames.AddRange(resourceNames);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With