Archive | April 2012

What is a Virtual Method, Anyway?

Something which I feel carries a lot of confusion in the .NET realm is virtual methods. During interviews, I tend to ask candidates about virtual methods: why and when they’d use one, what the purposes is, how a virtual method “works” under the hood, and how it differs from “shadowing”. Surprisingly, in what has probably been over one hundred interviews with senior-ish candidates, I don’t believe that more than one or two of them have answered anything about virtual methods correctly. From this I conclude that the understanding of virtual methods is not strong among the typical developer… And so, let us dive in.

Virtual methods exist to allow you to not just override, but completely replace functionality within a derivation hierarchy. In other words, you can change the functionality of a less derived class from within a more derived class. This is different from shadowing in that shadowing overrides the functionality of a method for the given derived class only and not the entire class hierarchy.

Shadowing is accomplished by declaring the same non-virtual method which exists in the base class, while adding the “new” keyword to indicate that shadowing behaviour was intended.

Overriding is accomplished by declaring the same virtual method which exists in the base class, while adding the “override” keyword to indicate that overriding behaviour was intended.

A code sample will make these differences very clear. Let us define a base Vehicle class (as abstract so that it cannot be instantiated) and a deriving Motorcycle class. Both will output information to the Console about the number of wheels that they have:

/// <summary>
/// Represents a Vehicle.
/// </summary>
public abstract class Vehicle
{
    /// <summary>
    /// Prints the Number of Wheels to the Console. 
    /// Virtual so can be changed by more derived types.
    /// </summary>
    public virtual void VirtualPrintNumberOfWheels()
    {
        Console.WriteLine("Number of Wheels: 4");
    }

    /// <summary>
    /// Prints the Number of Wheels to the Console.
    /// </summary>
    public void ShadowPrintNumberOfWheels()
    {
        Console.WriteLine("Number of Wheels: 4");
    }
}

/// <summary>
/// Represents a Motorcycle.
/// </summary>
public class Motorcycle : Vehicle
{
    /// <summary>
    /// Prints the Number of Wheels to the Console. 
    /// Overrides base method.
    /// </summary>
    public override void VirtualPrintNumberOfWheels()
    {
        Console.WriteLine("Number of Wheels: 2");
    }

    /// <summary>
    /// Prints the Number of Wheels to the Console. 
    /// Shadows base method.
    /// </summary>
    public new void ShadowPrintNumberOfWheels()
    {
        Console.WriteLine("Number of Wheels: 2");
    }
}

Above we’ve defined two classes: an abstract base Vehicle class which has a virtual and non-virtual method which both do the same thing, and a Motorcycle class which implements the Vehicle class while overriding the virtual method and shadowing the normal method. Now we will call the methods with different Type signatures to see the differences:

static void Main(string[] args)
{
    // Instantiate a Motorcycle as type Motorcycle
    Motorcycle vehicle = new Motorcycle();

    Console.WriteLine("Calling Shadow on Motorcycle as Type Motorcycle");
    vehicle.ShadowPrintNumberOfWheels();
    Console.WriteLine("Calling Virtual on Motorcycle as Type Motorcycle");
    vehicle.VirtualPrintNumberOfWheels();

    // Instantiate a Motorcycle as type Vehicle
    Vehicle otherVehicle = new Motorcycle();

    Console.WriteLine("Calling Shadow on Motorcycle as Type Vehicle");
    otherVehicle.ShadowPrintNumberOfWheels();
    Console.WriteLine("Calling Virtual on Motorcycle as Type Vehicle");
    otherVehicle.VirtualPrintNumberOfWheels();

    Console.ReadKey();
}

Before we reveal the results, ask yourself: what do you expect the outcomes for each call to be? You may be surprised. And now, the results:

Shadow vs Virtual Results

Shadow vs Virtual Results

Were your assumptions about the code correct? The virtual method’s override has changed the functionality within the base Vehicle class as well. Therefore, it should be clear to see that virtual methods should be used whenever you wish to change not just the functionality of a method within your currently derived class, but within all deriving and base classes.

Finally, I’d like to address one more constant “debate”. You will undoubtedly hear repeatedly in your career that virtual methods are very expensive to override and use. This is because of the fact that the actual instance method to call can only be determined at runtime, and not compile time. This is an old wives tale that has very little basis in reality (due to the intelligent use of “vtables”): virtual methods have little to no additional cost over regular methods. Proof (courtesy, Davy Brion).

Why Use Interfaces?

I’m a bit tipsy at the moment, so hopefully this post goes well.

A question that I like to ask while interviewing individuals is: “why would you want to use an interface?” I get a ton of answers that span the supposed gamut of programming; some are good and some are of course terrible, however I’d like to share some input on what I feel is the importance of interfaces.

Interfaces allow for the application of polymorphism (the ability of an object to exhibit multiple behaviours). In short: more polymorphism = less refactoring in the future when you change code. Less changes to do new things = happier programmers.

Let’s say that your customer/business asks you to write an application that makes a Dog speak. So you code something similar to this:

/// <summary>
/// Represents a Dog.
/// </summary>
public class Dog
{
    /// <summary>
    /// Makes the Dog Speak.
    /// </summary>
    public void Speak()
    {
        Console.WriteLine("Woof!");
    }
}

/// <summary>
/// Makes a Dog Speak.
/// </summary>
/// <param name="dog">The Dog to make Speak.</param>
public static void MakeDogSpeak(Dog dog)
{
    // Sanitize
    if (dog == null)
    {
        return;
    }

    // Make the Dog Speak
    dog.Speak();
}

In this scenario, making the Dog Speak is quite easy:

static void Main(string[] args)
{
    var dog = new Dog();

    MakeDogSpeak(dog);
}

Now imagine that the customer/business changes their mind – which of course never ever happens. They tell you that they have a Cat which can also speak, and that you need to change your program to allow both the Dog and Cat to speak. What a pain in the butt! Now we need to create the Cat class and add another method:

/// <summary>
/// Represents a Cat.
/// </summary>
public class Cat
{
    /// <summary>
    /// Makes the Cat Speak.
    /// </summary>
    public void Speak()
    {
        Console.WriteLine("Meow! (while glaring at you since Cats are evil)");
    }
}

/// <summary>
/// Makes a Cat Speak.
/// </summary>
/// <param name="dog">The Cat to make Speak.</param>
public static void MakeCatSpeak(Cat cat)
{
    // Sanitize
    if (cat == null)
    {
        return;
    }

    // Make the Cat Speak
    cat.Speak();
}

Now, making the Dog and Cat Speak is also quite easy, if a bit cumbersome:

static void Main(string[] args)
{
    var dog = new Dog();

    MakeDogSpeak(dog);

    var cat = new Cat();

    MakeCatSpeak(cat);
}

Are you seeing the tedious trend here? What happens when the customer/business now wants a Horse to speak, and a Lamb to speak, and a Tiger to speak, and even an Elephant to speak? What about a Unicorn or Human or Computer that needs to speak? Creating a method for each of these objects totally sucks and destroys your ability to write efficient OO code. So, what are we to do? Enter interfaces.

Interfaces exist to define a contract for common functionality which can be used in polymorphic ways. Let me repeat that once more to stress importance, interfaces are an important part of OO programming that allows you to capture common functionality and avoid tedious (and unnecessary) code.

Let’s look at the prior examples. We know that we have a Dog and a Cat, and that they both Speak. From this we can analyze and see some common functionality. We realize that we can define a common interface for these objects that encapsulates speaking:

/// <summary>
/// Represents an object that can Speak.
/// </summary>
public interface ICanSpeak
{
    /// <summary>
    /// Makes the object Speak.
    /// </summary>
    void Speak();
}

Let us now update our Dog and Cat such that they implement this interface:

/// <summary>
/// Represents a Dog.
/// </summary>
public class Dog : ICanSpeak
{
    /// <summary>
    /// Makes the Dog Speak.
    /// </summary>
    public void Speak()
    {
        Console.WriteLine("Woof!");
    }
}

/// <summary>
/// Represents a Cat.
/// </summary>
public class Cat : ICanSpeak
{
    /// <summary>
    /// Makes the Cat Speak.
    /// </summary>
    public void Speak()
    {
        Console.WriteLine("Meow! (while glaring at you since Cats are evil)");
    }
}

Finally, let’s take advantage of the polymorphism that this interface now offers and reduce our two speaking methods into one useful method:

/// <summary>
/// Makes something Speak.
/// </summary>
/// <param name="speaker">The Speaker to make Speak.</param>
public static void MakeSomethingSpeak(ICanSpeak speaker)
{
    // Sanitize
    if (speaker == null)
    {
        return;
    }

    // Make the Speaker Speak
    speaker.Speak();
}

Two methods become one. In fact, N methods become one if they implement the common functionality encapsulated in the interface. This means that you can sleep peacefully at night knowing that no matter how many things the customer/business wants to have speak tomorrow, it’s not that hard to update your code to handle it. Finally, let us update our Main which runs the speak commands just to close the example:

static void Main(string[] args)
{
    var dog = new Dog();

    MakeSomethingSpeak(dog);

    var cat = new Cat();

    MakeSomethingSpeak(cat);
}

Now, no matter how many objects are defined that are to speak, we need only the single method as long as those objects implement the appropriate interface.

There are many other benefits to interfaces which we will discuss in future posts. However, I hope that this begins to exhibit the purpose and usefulness of defining interfaces and having types which share common functionality implement them. Cheers!

An Overview of Generic Constraints

This is my first post. I hope that it doesn’t suck.

As of .NET 2.0, Microsoft introduced the concept of generics. Generics is a concept that allow you to “template” methods and types such as classes and interfaces in a (generally) type-safe way. Upon compilation, generic type metadata is stored in IL, and JIT’d as you reference the generic method or class with an actual type at runtime. Value types each get their own “copy” of the JIT’d generic code, whereas reference types share a single instance of the code. This is because the generic implementation is identical for reference types – they’re all just pointers.

Anyway, you probably use generics daily, whether or not you know them by name. Ever used List<T>? IEnumerable<T>? Dictionary<TKey, TValue>? Those are pre-built generic classes and interfaces which are included in the .NET libraries.

You can build your own generic classes and methods in C#. Many people do this also daily. Perhaps to create a custom collection or caching method… but, have you ever used generic constraints?

Generic constraints allow you to constrain, or restrict, the types that can be used by your generic classes and methods. This enables you to examine the generic type with certainty about it’s functionality. Why does this matter? It allows you to invoke methods or properties on your type without using reflection.

The syntax is such that at the type or method definition, you add “where T : your constraints here“. An example:

public static T Create<T> where T : new()

The “new()” in this case indicates that whatever type is passed to this method MUST have a parameterless constructor. What does this afford you? You can now new up T in your method!

As a simple example, let us create the static factory method above that serves only to return a newly created instance of the generic type parameter:

/// <summary>
/// Creates an object of Type T.
/// </summary>
/// <typeparam name="T">The Type to Create.</typeparam>
/// <returns>An instantiated Type of T.</returns>
public static T Create<T>() where T : new()
{
    return new T();
}

Sweet! Now we can new up stuff like crazy. Let’s define a “Hat” class that represents a hat:

/// <summary>
/// A Hat.
/// </summary>
public class Hat
{
    /// <summary>
    /// The Size of the Hat.
    /// </summary>
    public int Size { get; set; }
}

Now let’s new that bad boy up:

static void Main(string[] args)
{
    var myHat = Create<Hat>();
}

Voila, we just made a hat with generics and generic constraints! But that’s pretty boring, and you might ask “why not just new up the bloody hat and skip all of that factory stuff?” Good question. We’ll discuss that in the future, but there are many reasons you might wish not to directly instantiate a concrete type in your methods or classes.

Let’s take a more practical example. Let us define the Size property in an interface and make the Hat implement that interface:

/// <summary>
/// A Hat.
/// </summary>
public class Hat : IHaveASize
{
    /// <summary>
    /// The Size of the Hat.
    /// </summary>
    public int Size { get; set; }
}

/// <summary>
/// Represents an object that has a Size.
/// </summary>
public interface IHaveASize
{
    /// <summary>
    /// The Size.
    /// </summary>
    int Size { get; set; }
}

Now let’s create a generic method that checks if a size is “valid” which we’ll define as being greater than 0.

/// <summary>
/// Determines whether or not Type T has a Valid Size.
/// </summary>
/// <typeparam name="T">The Type.</typeparam>
/// <param name="sizedObject">The object which has a Size.</param>
/// <returns>true if the Size is greater than 0, false otherwise.</returns>
public static bool IsSizeValid<T>(T sizedObject) where T : IHaveASize
{
    return sizedObject.Size > 0;
}

Note that we can access the Size property in the IsSizeValid method because of our generic constraint! Now to execute the code:

static void Main(string[] args)
{
    var myHat = Create<Hat>();

    // Note that we don't have to say IsSizeValid<Hat>(myHat) - the type is inferred by the parameter!
    var result = IsSizeValid(myHat);
}

And there you have it. An introduction into generic constraints!