Reputation: 969
[DataContract]
public class PersonField
{
private string _fieldName;
private object _fieldValue;
public PersonField()
{
}
public PersonField(string FieldName, object FieldValue)
{
_fieldName = FieldName;
_fieldValue = FieldValue;
}
[DataMember]
public string FieldName
{
get { return _fieldName; }
set { _fieldName = value; }
}
[DataMember]
public object FieldValue
{
get { return _fieldValue; }
set { _fieldValue = value; }
}
}
I have this class above which is used in my WCF service. when i try to create array on client side for this like
PersonField[] test = new PersonField[2];
test[0].FieldName = "test";
i get Object reference not set to an instance of an object. not sure what am i doing wrong?
Upvotes: 0
Views: 292
Reputation: 22076
For this you have to do this. Yo need to initialize test[0]
with new
keyword as well.
PersonField[] test = new PersonField[2];
test[0] = new PersonField();
test[0].FieldName = "test";
test[1] = new PersonField();
test[1].FieldName = "test2";
Value Type and Reference Type Arrays
Consider the following array declaration: C#
SomeType[] array4 = new SomeType[10];
The result of this statement depends on whether SomeType is a value type or a reference type. If it is a value type, the statement results in creating an array of 10 instances of the type SomeType. If SomeType is a reference type, the statement creates an array of 10 elements, each of which is initialized to a null reference.
For more information on value types and reference types, see Types (C# Reference).
Upvotes: 0
Reputation: 564383
Since this is a class, you're creating an array of references, not the actual objects. You still need to allocate the instance(s) yourself:
PersonField[] test = new PersonField[2];
test[0] = new PersonField();
test[0].FieldName = "test";
test[1] = new PersonField();
Upvotes: 3