Shan Shan - 3 months ago 23
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[]{}
data1[0].field1="12345"

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="http://schemas.datacontract.org/2004/07/csservice.data")]
[System.SerializableAttribute()]
public partial class ZData : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged {

[System.NonSerializedAttribute()]
private System.Runtime.Serialization.ExtensionDataObject extensionDataField;

private string Field1Field;

[global::System.ComponentModel.BrowsableAttribute(false)]
public System.Runtime.Serialization.ExtensionDataObject ExtensionData {
get {
return this.extensionDataField;
}
set {
this.extensionDataField = value;
}
}

[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public string Field1 {
get {
return this.Field1Field;
}
set {
if ((object.ReferenceEquals(this.Field1Field, value) != true)) {
this.Field1Field = value;
this.RaisePropertyChanged("Field1Field");
}
}
}

Answer

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" });