Question

Hi all kindly help me to understand why cant we define Arrays in structs in c#

i tried the other asked question but most of them suggests to use class instead of a struct. that is ok for implementation purpose but i want to understand why can't we define arrays in structs.

Was it helpful?

Solution

You can have an array in a structure, but that is quite pointless in most cases.

An array is an object, so the structure will only contain a reference for an array. If you create an array and assign to the reference, the array is created on the heap. The usual reason for using a structure is to avoid creating objects on the heap.

OTHER TIPS

You can but you have to initialize the array in all constructors because structs require that you assign values to all members in the constructor(s).

 public struct YourStruct
 {
     public char[] arr; 

   public YourStruct(int size)
   {
      arr = new char[size];
   }
 }

Like others have mentioned, if you are creating an ARRAY of OBJECTS (not value types) then a struct is not appropriate to begin with. Look here: How to initialize char array in struct

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top