#602 – Initializing Fields in a Class

You can initialize instance-level fields in a class when you declare them.  If you do not initialize them, all fields are initialized to default values (0 for numeric types, null for reference types).

In the fragment of the Dog class below, we initialize two instance-level fields and one static field.

    public class Dog
    {
        // Instance fields
        public string Name = "Bowser";
        public int Age = 1;

        // Static fields (one for entire type, rather than 1/instance)
        public static string CanineMotto = "We're here to serve you";

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

        public Dog() { }
    }
            Dog myDog = new Dog();
            Console.WriteLine("My dog {0} is aged {1}", myDog.Name, myDog.Age);

            Dog yourDog = new Dog("Kirby", 15);
            Console.WriteLine("Your dog {0} is aged {1}", yourDog.Name, yourDog.Age);

            Console.WriteLine("Dog motto: {0}", Dog.CanineMotto);

Advertisement

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

One Response to #602 – Initializing Fields in a Class

  1. Pingback: #669 – Initializing Fields by Calling A Method « 2,000 Things You Should Know About C#

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: