#287 – You Don’t Have to Define a Constructor

It’s not mandatory for a user-defined class to define a constructor.  If one is not defined, the compiler will automatically generate a constructor. This internal constructor will just call the constructor of the class’ base class.  (E.g. The constructor in System.Object).

You can use the IL DASM tool to inspect the code for your class and see this automatically generated constructor.

For example, let’s say that we have a Dog class that does not define a constructor.  Below is an image of the IL DASM, showing the metadata for the Dog class.  Note that it shows the following elements in the class:

  • Age and Name properties
  • get and set accessors for the properties
  • Backing variables for the properties
  • A Bark method
  • A method called .ctor–this is the automatically-generated constructor

This constructor just calls the System.Object constructor:

Advertisements

#286 – A Constructor is Called When an Instance of a Class Is Created

A constructor is a method that is called when a new instance of a class is created.  (Technically, this definition applies to instance constructors–I’ll cover static constructors later).

A constructor normally allows a class to initialize its data members, as part of the process of creating a new instance.

A constructor is defined by using the class’ name as the method name.  The simplest form of constructor, known as the default constructor, takes no parameters.

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

        // Constructor, called when we create a new Dog
        public Dog()
        {
            // Set a default name
            Name = "Pooch";
        }
    }

The constructor in the above example is called when we create a new instance of a Dog, using the new operator.

            Dog someDog = new Dog();

            Console.WriteLine(someDog.Name);       // Pooch

#285 – Class Member Overview

A class in C# can contain the following types of members:

Member Type Description Private / Public Instance / Static
Constants Constant values x
Fields Variables that can be read/written x x
Methods Procedure that can be called to perform some logic x x
Properties Data storage item that can have associated get/set behavior x x
Indexers Allows an instance of class to be indexed like an array x
Events Allows the class to notify client code when some condition occurs x x
Operators Defines behavior for class when instances are used within expressions using standard operators public static
Constructors Method that is called when an instance of the class is created x x
Destructors Method that is automatically called by the garbage collector before an object’s memory is released

Types Nested type declared inside the class x
x

#284 – Static Methods Can Call Instance Methods

Static methods can call instance methods in a class–provided that they have access to a reference to an instance of the class.

In the example below, we have a static method of the Dog class that dumps out a bunch of information about every Dog instance in a collection of dogs passed to it.

        public static void ListDogs(List<Dog> dogList, Cat cat)
        {
            foreach (Dog d in dogList)
            {
                string likes = d.LikesCat(cat) ? "Yes" : "No";

                Console.WriteLine("{0}: {1} yrs old.  Motto is [{2}]. Likes {3}? {4}",
                    d.Name,
                    d.Age,
                    d.Motto,
                    cat.Name,
                    likes);
            }
        }

Note that the static Dog method can also call an instance method of the Cat class.

Here’s how we might call this method:

            List<Dog> dogs = new List<Dog>();

            dogs.Add(new Dog("Kirby", 14, "Chase balls"));
            dogs.Add(new Dog("Jack", 17, "Lounge around house"));
            dogs.Add(new Dog("Ruby", 1, "Stare out window"));

            Cat morris = new Cat("Morris");

            Dog.ListDogs(dogs, morris);

Output:

#283 – Instance Methods Can Call Static Methods

Instance methods in a class can access static data or call static methods.  The instance method accesses static data or methods in the same way that other code does–by using the class name to qualify the data or method name.

Here’s an example, where the Dog.Bark instance method makes use of the private static Dog.FormatTheCreed method:

        // Static property -- one value for all dogs
        public static string Creed { get; set; }

        // Private static method to format our Dog creed
        private static string FormatTheCreed()
        {
            return string.Format("As dogs, we believe: {0}", Dog.Creed);
        }

        // Instance method, in which a Dog barks
        public void Bark()
        {
            // Dump out my name and the universal Dog creed.
            Console.WriteLine("{0}: 'Woof'!  (Creed: [{1}])", this.Name, Dog.FormatTheCreed());
        }

Calling the Bark method:

            // Set static property
            Dog.Creed = "We serve man";

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

#282 – Creating Private Static Methods

Like instance methods, static methods can be public or private.  A private static method is a method that works with the class’ static data, but is not visible from outside the class.

Below is an example of a private static method.  Note that it’s making use of some public static data.  It could also work with private static data.

        // Static property -- one value for all dogs
        public static string Creed { get; set; }

        // Public static method, to recite our creed
        public static void RepeatYourCreed(int numRepeats)
        {
            string creed = FormatTheCreed();

            for (int i = 0; i < numRepeats; i++)
                Console.WriteLine(creed);
        }

        // Private method to format our Dog creed
        private static string FormatTheCreed()
        {
            return string.Format("As dogs, we believe: {0}", Dog.Creed);
        }

We can call the public static method that makes use of this private method:

            // Set static property
            Dog.Creed = "We serve man";

            // Call static method
            Dog.RepeatYourCreed(3);

#281 – Declaring and Using Static Methods in a Class

A static method in a class is similar to an instance method, except that it acts upon the class’ static data–fields and properties–rather than on the instance data stored with a single instance of the class.

There is only one copy of each static data item, no matter how many instances of the class exist.

Here’s an example of defining a static method in a class.

        // Static property -- one value for all dogs
        public static string Creed { get; set; }

        // Static method acts on static data
        public static void RepeatYourCreed(int numRepeats)
        {
            for (int i = 0; i < numRepeats; i++)
                Console.WriteLine("My creed is: {0}", Creed);
        }

To call a static method, you just prefix the method with the name of the class (rather than with a reference to an instance of the class).

            // Set static property
            Dog.Creed = "We serve man";

            // Call static method
            Dog.RepeatYourCreed(3);