0
[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?

Amit
  • 21,570
  • 27
  • 74
  • 94
Natasha Thapa
  • 979
  • 4
  • 20
  • 41
  • 2
    possible duplicate of [What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net) – John Saunders May 08 '12 at 23:39
  • 1
    Try `PersonField[] test = new PersonField[2]; test[0] = new PersonField(); test[0].FieldName = "test";` This has nothing at all to do with serialization. – John Saunders May 08 '12 at 23:39
  • Why the downvote? Its a simple answer, but I see nothing wrong with the question itself. – John Saunders May 08 '12 at 23:42

2 Answers2

3

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();
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
0

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).

Here is MSDN link

Amit
  • 21,570
  • 27
  • 74
  • 94