Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi. I am curious about why it isn't allowed to initialize a field via an instance method?

An example code:
C#
class SomeRandomName
        {
            public int age = ReturnAge();

            public int ReturnAnAge()
            {
                return 23;
            }
        }


What I have tried:

Looked at Microsoft Docs. It mentions that an instance field is not allowed to refer to another instance field but doesn't say anything about instance methods.
Posted
Updated 17-Mar-18 23:17pm

1 solution

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:
C#
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.
 
Share this answer
 
v2
Comments
The_Unknown_Member 18-Mar-18 6:04am    
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?
The_Unknown_Member 18-Mar-18 6:13am    
Also the same is the case if you use a nested class like this:
class SomeRandomName
{
public InnerRandomClass irc = new InnerRandomClass();

public class InnerRandomClass
{

}

}
OriginalGriff 18-Mar-18 6:38am    
Answer updated.
The_Unknown_Member 18-Mar-18 7:02am    
"No, because that doesn't make any sense to me! :laugh:
Try explaining again, with examples." Well You are right. It gives a StackOverflowException. Why is it giving a StackOverflowException? however it works fine with baseclass field in the derived class:
public class BaseClass
{

}

public class DerivedClass : BaseClass
{
public DerivedClass dc = new DerivedClass(); // Doesn't work at all
public BaseClass bc = new BaseClass(); // Works fine!!!
}
OriginalGriff 18-Mar-18 7:20am    
You are surprised that gives a stack overflow? I'm not...
Suppose you create an instance of DerivedClass in your main method:
void main()
   {
   DerivedClass dc = new DerivedClass();
   }
The first thing the system has to to is allocate the memory (fine) and initialise the fields. And the first field it tries to initialise creates a new instance of the same class. Which tries to init it's fields, which creates a new instance, which ... *BOOM*

The BaseClass instance is fine, because it doesn't try to create an instance of itself (or DerivedClass) and set up an infinite loop of object creation.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900