I want the String field to consist of two other fields

I want to Fullnameconsist of FirstNameand Lastname, but I get the following exception:

The field initializer cannot refer to a non-stationary field, method or property 'Employee.FirstName' / 'Employee.LastName'

class Employee
{
    public string FirstName { get; }
    public string LastName { get; }
    private string FullName = string.Format("{0}, {1}", FirstName, LastName);
}
+4
source share
3 answers

The assignment order of class fields is not guaranteed by runtime. Therefore, the compiler warns you about a compile-time error.

If FullNameit was publicly available, you could do:

class Employee
{
    public string FirstName { get; }
    public string LastName { get; }
    public string FullName => $"{FirstName} {LastName}";
}

For those who do not use C # -6:

class Employee
{
    public string FirstName { get; private set; }
    public string LastName { get; private set; }
    public string FullName 
    {
        get { return string.Format("{0} {1}", FirstName, LastName); } 
    }
}

Or, if you do not want it to be publicly available, you need to create field instances through the class constructor

class Employee
{
    public Employee(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
        fullName = $"{FirstName} {LastName}";
    }

    public string FirstName { get; }
    public string LastName { get; }
    private string fullName;
}
+9
source

get,

class Employee{
    public String FirstName { get; }
        public String LastName { get; }
        public String FullName {
            get{
                return String.Format("{0}, {1}", FirstName, LastName);
            }
        }
    }
}
+2

I think you need to put this in a class constructor. The error is that you are trying to use values ​​that do not exist, or rather, cannot while you are using them.

+1
source

Source: https://habr.com/ru/post/1611427/


All Articles