1

I can use this snippet:

public object Obj
{
    get;
    set;
}

Like this:

public fubar()
{
    ...
    Obj = SomeObject;
}

But cannot seem to use this snippet:

public object[] ObjectAsArray
{
    get;
    set;
}

Like this or any other way I have tried so far:

public fubar()
{
    ...
    Obj[n] = SomeObject;
    //or 
    var x = Obj[0] as SomeObject;
    //or other ways...
}

I seem to be missing something here.

Can somebody give a simple example of the correct declaration of a C# property that is of type object[] and consumption thereof?

1
  • If the existing answers don't help, please say what's going wrong, and provide a short but complete program demonstrating the problem. Commented Aug 31, 2011 at 20:35

3 Answers 3

2

As soon as you change it from Obj to ObjectAsArray it should compile. You'll still need to actually create the array though:

ObjectAsArray = new object[10];
ObjectAsArray[5] = "Hello";
Sign up to request clarification or add additional context in comments.

Comments

2

You're trying to set Obj[n] before Obj itself is initialized... so, I imagine you're getting a null-reference exception. You need to perform an assignment, like so:

Obj = new Object[];

... and in context:

public fubar()
{

  Obj = new Object[13]{}; // where 13 is the number of elements
  Obj[n] = SomeObject;
}

Comments

0

I would suggest adding a private backing field for the object[] property and initialize it - either directly or in the getter.

object[] _objectsAsArray = new object[10];

OR

public object[] ObjectAsArray   
{       
     get 
     { 
         if(_objectsAsArray == null)
             _objectsAsArray = new object[10];
         return _objectsAsArray;
     }
     set
     {
        _objectsAsArray = value;   
     } 
}

The complier is creating a private backing field anyhow so why not be explicit about it. Also, auto-implemented properties have some drawbacks (serialization, threading, etc). Doing it the "old-fashioned" way also gives you a nice place to actually create the array. Of course if you don't need to worry these issues - go ahead and use the auto-implemented property.

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.