Reputation: 645
I have the following c# class
public class smallclass
{
public Vector3 var1 = new Vector3(1,2,3);
public string var2 = "defaultval";
public smallclass()
{
var1 = new Vector3(11,22,33);
var2 = "constructor";
}
}
And I have another c# class
public class bigclass
{
public smallclass[] smallclasses;
}
Then somewhere else in my program, I increment smallclasses size with
smallclasses = new smallclass[3];
but I realize that the three elements are null... is this correct behavior?
Allow me to clarify that I need that, whenever I resize the smallclasses array, its elements get automatically 'constructed'... I just don't know if such a thing can be done.
Differently than what I'd have expected, setting default values has no effect. Immediately after I resize the smallclasses array, the elements are null...
Any advice appreciated.
Thanks.
Upvotes: 1
Views: 1424
Reputation: 43056
smallclasses = new smallclass[3];
is not resizing the array. It is creating a new array.
Your array declaration (public smallclass[] smallclasses;
) creates a field in the class bigclass
whose initial value is null
. The statement smallclasses = new smallclass[3];
creates a new array object and assigns a reference to that object to the field smallclasses
.
Whenever you create a new array of a reference type (i.e., a class), all elements of the array are null. This is expected behavior. See section 1.8 of the C# specification, which says in part: "The new operator automatically initializes the elements of an array to their default value, which, for example, is zero for all numeric types and null for all reference types."
Upvotes: 2
Reputation: 613461
You are asking for your array of objects to be automatically created for you. This is not how the language works. You need to construct each object individually, or in a loop.
If you do not initialize an array when you declare it, the members are initialized to the default initial value for the array type. For a reference type this is null
.
Upvotes: 1
Reputation: 74450
If I understand your question correctly, check out the Array.Resize method. It will help you keep the values of the objects from the original array, when the newly sized array is created. From the linked article:
This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one.
Update based on comment:
If you want the references in the array to refer to valid objects, you must allocate these objects and store them in the array. With a C# array you just have a reference to an array object. You still have to allocate the objects themselves and store their references into the array, if you want it to contain actual objects.
Upvotes: 1
Reputation: 2909
Try using List of Smallclass instead of the smallclass[]. You can also do Array.Resize on arrays. But the list solution is better for performance.
Upvotes: 0