I want Fullname
to consist of FirstName
and Lastname
but I get the following exception:
A field initializer cannot reference the non static 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);
}
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;
}
you are trying to set the value before you have initialised the variable
if you change from a set to a get then you will have more success
class Employee{
public String FirstName { get; }
public String LastName { get; }
public String FullName {
get{
return String.Format("{0}, {1}", FirstName, LastName);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With