#669 – Initializing Fields by Calling A Method

You can initialize fields in a class at the point where you declare them, using a constant. ¬†You can also initialize a field to a value returned from a call to a method–as long as the method is not an instance method within the same class.

Here’s an example, where we call a static method in the same class to initialize a field.

    public class Dog
    {
        private static string GenerateCreationInfo()
        {
            return string.Format("I was created at {0}", DateTime.Now);
        }

        public string CreationInfo = GenerateCreationInfo();

        public string Name { get; set; }
        public int Age { get; set; }

        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }
    }