Partly because you need to spell your method name the same way in the definition and the call...
But mostly because field initialization is performed before instance construction: and the constructor must be the first method called in the instance (or the other methods could not rely on any other information).
And fields must be initialized before the actual constructor begins to execute, or it could set values that are overwritten by the field initializers!
You can do it with static methods:
class SomeRandomName
{
public int age = ReturnAge();
public static int ReturnAge()
{
return 23;
}
}
Because a static method cannot access any instance data, and so must be completely prepared before an instance is created.
Quote:
So the instance field must contain data that is known at compile time or it should use a static method because the static class is created with its default static constructor before any instance object. Do I understand it correctly? But it works if you make the field an object reference that points to object of this type. Can you explain why this happens?
Also the same is the case if you use a nested class like this:
class SomeRandomName
{
public InnerRandomClass irc = new InnerRandomClass();
public class InnerRandomClass
{
}
}
Quote:
So the instance field must contain data that is known at compile time
No, the initializer data doesn't have to be known at compile time:
Quote:
class SomeRandomName
{
public int age = ReturnAge();
public static int ReturnAge()
{
MyDB db = new MyDB();
return db.GetAge();
}
}
Is fine - the MyDB class reads the data from SQL and returns it perhaps.
Quote:
it should use a static method because the static class is created with its default static constructor before any instance object.
Yes!
Quote:
But it works if you make the field an object reference that points to object of this type. Can you explain why this happens?
No, because that doesn't make any sense to me! :laugh:
Try explaining again, with examples.
Quote:
Also the same is the case if you use a nested class
That's not a problem because a "nested class" is just a class with a full name that includes all it's "parent classes" - the actual class is not constructed any different from a non-nested class, only the name is affected by nesting.