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

Advertisements

#256 – Using Static Fields

Let’s say that we have both instance and static fields defined in a class:

        public string Name;

        public static string Creed;

This allows us read and write the Name property for each instance of the Dog class that we create.

            Dog kirby = new Dog();
            kirby.Name = "Kirby";

            Dog jack = new Dog();
            jack.Name = "Jack";

Notice that each instance of a Dog has its own copy of the Name field, since Name is an instance field.

We can also read/write the static Creed field, using the class name to qualify the field, rather than an instance variable.

            Dog.Creed = "Man's best friend";

There is only one copy of the Creed field, since Creed is a static field.