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();
        }
    }
2
  • What is the problem you have or what is the error message you get? Commented Jan 12, 2020 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. Commented Jan 12, 2020 at 12:57

1 Answer 1

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...

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.