Reputation: 51
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);
}
Upvotes: 4
Views: 110
Reputation: 149578
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;
}
Upvotes: 9
Reputation: 5500
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);
}
}
}
}
Upvotes: 2
Reputation: 980
I think you need to put that in the class constructor. The error is because you are trying to use values that don't exist, or rather might not at the time you are using them.
Upvotes: 1