I researched this subject but I couldn't find any duplicate. I am wondering why you can use a struct in an array without creating an instance of it.
For example, I have a class and a struct:
public class ClassAPI
{
public Mesh mesh { get; set; }
}
public struct StructAPI
{
public Mesh mesh { get; set; }
}
When ClassAPI is used in an array, it has to be initialized with the new keyword before being able to use its properties and methods:
ClassAPI[] cAPI = new ClassAPI[1];
cAPI[0] = new ClassAPI(); //MUST DO THIS!
cAPI[0].mesh = new Mesh();
But this is not the case with StructAPI. It looks like StructAPI doesn't have to be initialized in the array:
StructAPI[] sAPI = new StructAPI[1];
sAPI[0].mesh = new Mesh();
If you try the same thing with ClassAPI, you would get a NullReferenceException.
Why is it different with structs when using them in an array?
I understand the difference between class and struct with struct being a value type but that still doesn't make sense. To me, without the array being involved in this, it would look like I am doing this:
StructAPI sp;
sp.mesh = new Mesh();
Notice that the sp variable is not initialized and it should result in a compile-time error that says:
Error CS0165 Use of unassigned local variable 'sp'
but that's a different story when the struct is put in an array.
Is the array initializing the struct in it? I would like to know what's going on.