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?

3
  • 2
    possible duplicate of What is a NullReferenceException in .NET? Commented May 8, 2012 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. Commented May 8, 2012 at 23:39
  • Why the downvote? Its a simple answer, but I see nothing wrong with the question itself. Commented May 8, 2012 at 23:42

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.