1

I am developing a C# Winform app in .NET CF 3.5 environment.

I understand that a TypeInitializationException occurs in the example below.

static int [] ArrayB = new int [ArrayA.Length];
static int [] ArrayA = new int [] {1, 2, 3, 4};

This is because ArrayA is null when ArrayB is declared. Therefore, there is no error if you change it as shown below.

static int [] ArrayA = new int [] {1, 2, 3, 4};
static int [] ArrayB = new int [ArrayA.Length];

So why does not the following example throw a TypeInitializationException?

static int [] ArrayB = new int [len];
static int len ​​= 4;

ArrayB is declared before len. I think that an error should occur because len is not yet initialized when declaring ArrayB.

But why does not the error occur?

help
  • 87
  • 1
  • 6

1 Answers1

1

Even tho it does not throw exception the length of ArrayB is still zero (default value for int). Here's explanation by someone: "The cause of the unexpected value can be found in the C# Language Specification. This is the definitive documentation for C# syntax and usage. The document specifies that static fields can never be seen as uninitialised values. If they are accessed before a value has been applied, the default value for their data type is returned. For integer values, this is zero. The C# Language Specification also tells us that when static fields are initialised by applying a value in their declaration, as we have done above, they are set in the order in which they appear in the code. This means that when the ArrayB value is calculated, we are using two uninitialised values, each of which yields a result of zero." For more info: Doc

Gray_Rhino
  • 1,153
  • 1
  • 12
  • 31