The assignment order of class fields is not guaranteed by runtime. Therefore, the compiler warns you about a compile-time error.
If FullName
it 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;
}
source
share