#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;


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: