开发者

Default initialisation creating an Array of struct vs class objects

开发者 https://www.devze.com 2023-04-08 22:58 出处:网络
I understand that struct is value type and class is reference type in .Net. I would like to know if there is any better solution here.

I understand that struct is value type and class is reference type in .Net. I would like to know if there is any better solution here.

Example,

public struct Holder
{
    public double Value { get; set; }

    public Holder()
    {
        this.Value = 0.0;
    }
}

Usage of this struct:

void SomeFunction(int n)
{
    Holder[] valueHolders = new Holder[n];
    ...
    valueHolders[0].Value = someValue;
}

This works perfectly fine. Now just changing Holder to class. It throws an null object reference because valueHolders contails all values as null.

Now I have changed my code to

valueHolders[0开发者_如何学Go] = new Holder();
valueHolders[0].Value = someValue;

It works fine. Is there any way to create all elements in valueHolders at once like it was doing when it was a struct type.


C# requires a reference type to be initialized explicitly. This can be done quite easily within a loop:

Holder[] valueHolders = new Holder[n];
for (int i = 0; i < n; i++)
{
    valueHolders[i] = new Holder();
}

You can take this a bit further and expose a static method on your class like this:

public class Holder    {
    static public Holder[] InitArray(ulong length) {
        Holder[] holders = new Holder[length];
        for (ulong i = 0; i < length; i++) {
            holders[i] = new Holder;
        }
        return holders;
    }
}

...

var valueHolders = Holder.InitArray(n);

You can take it even further with a generic extension method:

public static class ArrayInitializer
{
    public static T[] Init<T>(this T[] array) where T : new()
    {
        for(int i = 0; i < array.Length; i++)
        {
            array[i] = new T();
        }
        return array;
    }
}

...

var valueHolders = new Holder[n].Init();
0

精彩评论

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