Home > Blockchain >  How to add new object in array of object in C#?
How to add new object in array of object in C#?

Time:11-06

I have one object which contains one array inside as below

public class LiveData
{
        public string? serverTime { get; set; }
        public string? msgId { get; set; }
        public string? status { get; set; }
        public string? statusMessage { get; set; }
        public Data[] data {get; set}        
}

public class Data
{
      [Required] 
      public DateTime Date { get; set; }  
      public string Description{ get; set;}
}

I want to add new element to Data array.

I tried to add as below

//get length of array
int arrayLength= liveData.data.Length; 
liveData.data[length]= new LiveData
{
   Date = DateTime.Now,
   Description = "New value" 
}

But this throws exception System.IndexOutOfRangeException: Index was outside the bounds of the array.

CodePudding user response:

Here are three ways of adding a new element to an array:

var array = new LiveData[] {};

// add new element to array using Append
array = array.Append(new LiveData()).ToArray();

// add new element to array using Resize
Array.Resize(ref array, array.Length   1);
array[array.Length - 1] = new LiveData();

// convert array to list, add element then convert back to array
var list = array.ToList();
list.Add(new LiveData());
array = list.ToArray();

If you don't have a fixed size for your array I would recommend using List instead.

  • Related