2023-05-03 11:06:20 +02:00
== Why is this an issue?
2020-06-30 12:48:39 +02:00
Static field initializers are executed in the order in which they appear in the class from top to bottom. Thus, placing a static field in a class above the field or fields required for its initialization will yield unexpected results.
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2020-06-30 12:48:39 +02:00
2022-02-04 17:28:24 +01:00
[source,text]
2020-06-30 12:48:39 +02:00
----
class MyClass
{
public static int X = Y; // Noncompliant; Y at this time is still assigned default(int), i.e. 0
public static int Y = 42;
}
----
2023-05-03 11:06:20 +02:00
=== Compliant solution
2020-06-30 12:48:39 +02:00
2022-02-04 17:28:24 +01:00
[source,text]
2020-06-30 12:48:39 +02:00
----
class MyClass
{
public static int Y = 42;
public static int X = Y;
}
----
or
2021-02-02 15:02:10 +01:00
2022-02-04 17:28:24 +01:00
[source,text]
2020-06-30 12:48:39 +02:00
----
class MyClass
{
public static int X;
public static int Y = 42;
static MyClass()
{
X = Y;
}
}
----