Tuesday, March 28, 2006

 

C# makes a struct invalid by default

C# creates invalid structures when there are array members, as illustrated in the following example:

    class Program
    {
        public struct Problems
        {
            public int[] iArray;
        }
        static void Main(string[] args)
        {
            Problems oProblems = new Problems();
            Console.WriteLine("Length = {0}",
             oProblems.iArray.Length);
        }
    }

This example will build but fail when run. The default constructor for Problems does not initialize iArray. It is impossible to remedy the situation by writing a default constructor, because C# insists on providing the default constructor of a struct automatically.

A workaround is to provide any struct that contains an array with an initializing method, as in the following:

    class Program
    {
        public struct Problems
        {
            public int[] iArray;
            public void Initialize()
            {
                iArray = new int[0];
            }
        }
        static void Main(string[] args)
        {
            Problems oProblems = new Problems();
            oProblems.Initialize();
            Console.WriteLine("Length = {0}",
             oProblems.iArray.Length);
        }
    }

Neither Microsoft's opaque C# documentation nor Herb Schildt's generally useful book, "C# 2.0 The Complete Reference," describe this problem or explain that a struct may include methods. The workaround is not really satisfactory, because programmers must remember to invoke initializing methods or otherwise initialize array members of a struct.

Comments: Post a Comment

Subscribe to Post Comments [Atom]





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]