문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top