0

Pretty new to C# and OOP. I am trying to create a class called "Human" with some information initialization. However I get the following error a field initializer cannot reference the nonstatic field method or property. The error message points at first_name and last_name when trying to create the full_name variable

Heres the "simple" code

namespace World
{
    public class Human
    {
        // Personal traits
        public string first_name;
        public string last_name;
        public string full_name = first_name + " " + last_name;
    }
}

What exactly am I doing wrong? I dont get it..

Dean
  • 301
  • 1
  • 3
  • 13

2 Answers2

7

You can implement it as Property that returns the computed string in its getter

namespace World
{
    public class Human
    {
        // Personal traits
        public string first_name;
        public string last_name;
        public string full_name { get { return first_name + " " + last_name}};
    }
}

Is there a reason you use this way of writing member names? Normally I would do it like so:

namespace World
{
    public class Human
    {
        // Personal traits
        public string FirstName {get; set;} 
        public string LastName {get; set;} 
        public string FullName => $"{FirstName} {LastName}"; // C#7 notation notation
    }
}

Public properties using PascalCasing, private ones camelCasing is "normal" according to MS and will even produce hints in VS2017

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Thank you for your help! I generally like using all lowercase variable names with _ in between. That's all :P – Dean Nov 25 '17 at 15:24
4

The reason it will not work is because all your properties are nonstatic, this means that they are instance values. So they will be set on every new instance of the class thats created. Imagine you new up your class

  1. Memory is allocated
  2. Default properties are set
  3. The constructor is called

So the code you’ve shown will run during step 2. At that time there is no this, because there is not yet an instance to reference. But that is what you are doing when you say.

Public String FullName = FirstName + LastName;

This would be more fully qualified as

Public String FullName = this.FirstName + this.LastName

This is still not correct, but it's more descriptive and shows the real problem. At the time that this line of code runs there is not yet a self/this to reference.

solution You have a lot of options. Patrick Artner covered the best solution well in his answer.

KirstieBallance
  • 1,238
  • 12
  • 26
rayepps
  • 2,072
  • 1
  • 12
  • 22