The assignment order of class fields isn't guaranteed by the run-time. That's why the compiler is warning you with a compile time error.
If FullName
was a public property, you'd be able to do:
class Employee
{
public string FirstName { get; }
public string LastName { get; }
public string FullName => $"{FirstName} {LastName}";
}
For anyone not using 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 don't want it to be public, you'll need to instantiate the fields via 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;
}