Shan Shan - 1 year ago 137
C# Question

Array declaration in C# from a Service Class

I have a array type something like this

ZData and this array has a field called "field1"

I am trying to declare something like

ZData data1= new Zdata[]{}

The above code throws me a index out of bounds exception error but it builds successfully

This is a predefined array with only one field and I have to pass this array to an method

[System.Runtime.Serialization.DataContractAttribute(Name="ZData", Namespace="")]
public partial class ZData : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {

private System.Runtime.Serialization.ExtensionDataObject extensionDataField;

private string Field1Field;

public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
get {
return this.extensionDataField;
set {
this.extensionDataField = value;

public string Field1 {
get {
return this.Field1Field;
set {
if ((object.ReferenceEquals(this.Field1Field, value) != true)) {
this.Field1Field = value;

Answer Source

ZData data1 = new Zdata[]{} declares an empty array - there are no elements.

So, data1[0], referring to the first element, is out of bounds.

Instead, declare the length of your array:

ZData data1 = new ZData[1];     // length 1

Note that, unless ZData is a struct, you also have to instantiate every array entry before using it:

data1[0] = new ZData();
data1[0].field1 = "12345";

Alternatively, use a List<T> instead of an array, and you won't have to declare the length up front:

List<ZData> data1 = new List<ZData>();
data1.Add(new ZData() { field1 = "12345" });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download