C # Variable initialization problem: Field initializers cannot reference non-static fields, methods, or properties

Source: Internet
Author: User


Problem: Field initializer cannot reference a non-static field, method, or property problem

The reason for the following code error is why the fields defined in the class are not available.
public class Test
{
Public Test ()
{
}
public int age=23;
public int temp = age;//error field initializer cannot reference a non-static field, method, or property
}

C # stipulates that only attributes or variables can be defined within a class and initialized and cannot be referenced directly by variables.

The field was called before initializing the class instance

The initialization of a field in C # is preceded by a constructor.

String y = "asdf" + x; is actually y = "asdf" + this.x;

Because this is not yet initialized, the compilation will have an error.

The property memory and variable memory allocations are not the same time.
Attributes are allocated when they are used, and variables are allocated at the time of class initialization.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.