This is the code:
class Program
{
void Add2Array(object arr, object item)
{
if (arr.GetType() == typeof(string[]))
{
int iLen = (arr as Array).Length;
var c = Array.CreateInstance(typeof (String), 3);
Array v = Array.CreateInstance((arr as Array).GetValue(0).GetType(), iLen+1); // this works but when if arr is empty it wont work
Array.Copy(ar, v, iLen);
v.SetValue(item, iLen);
}
}
public string[] sarr = new string[1];
static void Main(string[] args)
{
Program p = new Program();
p.sarr[0] = "String Item";
p.Add2Array(p.sarr, "New string item");
}
}
I want to create a method which can take every type of arrays and put new item into them.
Above code is my solution (if you know better please share) and if arr parameter hasn't any item, it won't work properly. Because if I use this Array.CreateInstance(arr.GetType(),3) it will create new array like this v.GetType() => string[2][] because arr is string array and if i create with same type it is returning two dimensonal array.
How can I extend an array(given as a parameter) and put new item into it ?
Listobject?