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

#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

#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}",

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


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

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

        // 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

#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

#280 – Implicitly-Typed Arrays

In the same way that you can declare an implicitly-typed variable, letting the compiler figure out the type of the variable’s value, you can declare implicitly-typed arrays.

In the example below, we declare and initialize both implicitly-typed variables and implicitly-typed arrays.  The compiler infers the type–shown in the associated comment.

            // Implicitly-typed variables
            var x = 42;         // int
            var s = "Hooey";    // string

            // Implicitly-typed arrays
            var someArray = new[] { 5, 6, 7 };             // int[]
            var arrB = new[] { new Dog("Bob"), null };     // Dog[]

#279 – Passing a Multidimensional Array to a Method

You can pass multi-dimensional arrays to methods.  Like arrays with a single dimension, the array is passed by value, with a copy of the reference passed to the method.  This means that the method can change elements in the array.

Here’s an example of a method that takes a two-dimensional array as an input parameter.

        public static void CountPawns(ChessPiece[,] chessboard, out int redPawns, out int blackPawns)
            redPawns = 0;
            blackPawns = 0;

            for (int row = 0; row < 8; row++)
                for (int col = 0; col < 8; col++)
                    ChessPiece piece = chessboard[row,col];
                    if (piece != null)
                        if (piece.PieceType == PieceTypeEnum.Pawn)
                            if (piece.PieceColor == PieceColorEnum.Red)

When calling the method, you just pass the name of the array to the method.

            ChessPiece[,] board = new ChessPiece[8, 8];

            board[0, 1] = new ChessPiece(PieceTypeEnum.King, PieceColorEnum.Red);
            // continue to set up board here

            int redPawns;
            int blackPawns;
            Chess.CountPawns(board, out redPawns, out blackPawns);

#278 – Passing an Array by Reference

You can pass an array by reference to a method, using the ref or out parameter modifier, when you want the method to change the parameter to refer to a different array.

Here’s an example of a method that accepts an array and then overwrites the reference so that it points to a new array.

        public static void DoubleADogList(ref Dog[] list)
            Dog[] bigList = new Dog[2 * list.Count()];

            int i2 = 0;
            foreach (Dog d in list)
                bigList[i2++] = new Dog(d.Name, d.Age, d.Motto);
                bigList[i2++] = new Dog(d.Name + " Clone", d.Age, d.Motto);

            // Change original reference to refer to new list
            list = bigList;

We can call this method, passing it an array. When the method returns, the array variable points to the new (larger) array.

            Dog d1 = new Dog("Kirby", 13, "Chase balls");
            Dog d2 = new Dog("Jack", 17, "Bark");

            Dog[] list = new Dog[] { d1, d2 };

            Dog.DoubleADogList(ref list);