开发者

How to use a C# Object Array as a Property

开发者 https://www.devze.com 2023-04-01 12:39 出处:网络
I can use开发者_开发问答 this snippet: public object Obj { get; set; } Like this: public fubar() { ... Obj = SomeObject;

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?


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消