Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want a String field to consist of two other fields

Tags:

c#

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);
}
like image 301
jeroen Avatar asked Dec 14 '22 11:12

jeroen


2 Answers

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;
}
like image 117
Yuval Itzchakov Avatar answered Dec 17 '22 02:12

Yuval Itzchakov


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);
            }
        }
    }
}
like image 24
MikeT Avatar answered Dec 17 '22 02:12

MikeT