0

I cannot compile it, I have problem with array of struct. Is it possible to define it at struct or what?

struct MojaStruktura
    {
        public int CeoBroj1;
        public int CeoBroj2;
        string[] str = new string[5]; // here is the problem that I'd like to solve
    }
    class Program
    {
        static void Main(string[] args)
        {
            MojaStruktura m = new MojaStruktura();
            Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(m));
            Console.ReadLine();
        }
    }
Enlico
  • 23,259
  • 6
  • 48
  • 102
  • What is the problem you have or what is the error message you get? – Progman Jan 12 '20 at 12:11
  • 1
    The CLR does not support this kind of initialization since it requires executing code. The C# compiler normally solves it by moving the code into the constructor. Problem is, a struct cannot have a parameterless constructor. Gives you a good reason to make it a class instead of a struct. Or a property with a lazy getter. Or a factory method. Using a class in pinvoke code is fine, it needs a [StructLayout] attribute and no ref/out in the [DllImport] declaration. – Hans Passant Jan 12 '20 at 12:57

1 Answers1

0

I believe all information are exist on learn.microsoft.com

...the default value of a struct consists of the value that results from setting all value type fields to their default value and all reference type fields to null. For this reason, a struct does not permit instance field declarations to include variable initializers. This restriction applies only to instance fields...

Serhii Matvienko
  • 292
  • 3
  • 15