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.
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 classbigclasswhose initial value isnull. The statementsmallclasses = new smallclass[3];creates a new array object and assigns a reference to that object to the fieldsmallclasses.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.”