Home > Mobile >  Set value to model instance - ArgumentOutOfRangeException
Set value to model instance - ArgumentOutOfRangeException

Time:05-31

i have an error while I set value to model instance

Controller

var operatingDTO = new List<OperatingDTO>();

      operatingDTO[0].Id = 1;

Model

public class OperatingDTO
    {
        public int Id { get; set; }
    }

Error

'operatingDTO[0].Id' threw an exception of type 'System.ArgumentOutOfRangeException'

CodePudding user response:

You should instantiated the element and then add to the list. There is a whole guide about that: Object and Collection Initializers (C# Programming Guide).

C# lets you instantiate an object or collection and perform member assignments in a single statement.

Replace with either

var operatingDTO = new List<OperatingDTO>();
operatingDTO.Add(new OperatingDTO { Id = 0 });

or even

var operatingDTO = new List<OperatingDTO> { new OperatingDTO { Id = 0 } };

Try it online!

  • Related