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] = 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:
You can take this a bit further and expose a static method on your class like this:
You can take it even further with a generic extension method: