Hello World: the ‘new’ keyword

Everyone knows what the new keyword is for in C# – you use it to call constructor of an object, right? What can be simpler? Actually, that’s true, but not the whole truth. That’s the most common way to use it. However, new is one of contextual keywords, which means, it can have different meaning, depending on the context where it’s being used.

The new keyword can be used in three scenarios:

  • the one presented above, everyone immediately thinks of – creating objects.
  • as modifier, to hide members of a base class.
  • as generic constraint.

Creating objects is pretty straightforward, and there’s no magic there:

string[] stringArray = new string[] { "kot", "knur", "pies" };  //creating array

List<string> stringList = new List<string>(stringArray);        //creating class

DateTime dateTime = new DateTime(2000, 1, 1);                   //creating struct

Action myDelegate = new Action(delegate { });                   //creating delegate

var myAnonymousType = new { A = 1, Name = "My name" };          //creating anonymous type

The only thing that may look unfamiliar, is new C# 3.0 anonymous types initializing. It works in similar way to anonymous delegates. Here I created a nameless class, that two fields: A (of type int) and Name (of type string). This is the most basic stuff.

Not everyone however, knows about two other usages of that keyword. Let’s consider very simple example:

class Program

{

    static void Main(string[] args)

    {

        InheritedClass inherited = new InheritedClass();

        inherited.Write();

        UseBaseWrite(inherited);

    }

 

    public static void UseBaseWrite(BaseClass item)

    { item.Write(); }

}

 

public class BaseClass

{

    public void Write()

    { Console.WriteLine("Hello. I'm a BaseClass' Write!"); }

}

 

public class InheritedClass : BaseClass

{

    public new void Write()

    { Console.WriteLine("Hello. I'm a InheritedClass' Write!"); }

}

We have two classes, BaseClass, and InheritedClass that inherits from BaseClass. They both have non-virtual method Write, that writes a string to the console, and inherited class has a new keywords as its modifier (the code would actually work the same without that keyword, we would however receive compile time warning). We then create InheritedClass’ instance, and pass it to UseBaseWrite, method, that calls its Write method.

So what would be the outcome of that program?

Hello. I’m a InheritedClass’ Write!

Hello. I’m a BaseClass’ Write!

 

If you bet on that answer you can give yourself a reward. Now the question for those of you who guessed differently is – why? Notice that Write in BaseClass is not virtual, and as such we’re not overriding it in InheritedClass. We just create brand new method, that has no connection whatsoever to BaseClass’ Write, except the fact that it has the same name. This way,(as InheritedClass inherits from BaseClass) we have in it two unrelated methods with the same name. And here comes the tricky part: Which one of those two methods will be called, depends on the type of reference you’re holding to your object. If you reference it as InheritedClass (as we did in 6th line), we call Write implemented in InheritedClass. When we however reference the same object as BaseClass (as we did in 10th line) BaseClass’s implementation gets called. That’s why new is not inheritance modifier, but it let’s you have method in inherited class with the same name as base class, you don’t get however polymorphic  behavior. In this context it’s usability is really limited.

More interesting usage is new as generic constraint:

static void Main(string[] args)

{

    GenericClass<DateTime> d = new GenericClass<DateTime>();//ok

    DateTime dateTime = d.GetNewItem();

    GenericClass<string> s = new GenericClass<string>();//compile error

}

 

public class GenericClass<T> where T : new()

{

    public T GetNewItem()

    {

        return new T();

    }

}

When you specify new() on constraints list for your generic type, you demand, that generic type T has to have public parameterles constructor.

In the example above, it’s ok to pass DateTime as generic parameter, as it meets the constraint. String however does not have default constructor, that’s why this code would fail to compile.

It let’s you then call new T() anywhere in your code. It can be very useful sometimes. One more thing to keep in mind, is that when you specify more than one generic constraint, new() must be the last one of them.

//compilation error

public class GenericClass<T> where T :  new(), IEnumerable

{ public T GetNewItem() { return new T(); } }

 

//now ok

public class GenericClass<T> where T : IEnumerable, new()

{ public T GetNewItem() { return new T(); } }

And that’s basically all. I hope it was informative and I didn’t miss anything. Happy coding.

Technorati Tags: , , ,

Extension Methods "Hello World" I: Introduction

I decided that it’s about time to familiarize myself with new features of .NET 3.5 and C# 3.0. And I don’t mean see an overview, because I’ve read many times about what’s new in it, and I have basic understanding of all those new goodies that new version of framework/language brings. What I mean by familiarize is understand thoroughly and that is what this “Hello World” series (hopefully) is (hopefully) about.

I’m gonna start with extension methods as this is what I’ve started playing with already, and then… well we’ll see 🙂

Extension Methods are a completely new concept to OOP world (at least from what I know), and they may seem odd to people with strong OOP background. We’re used to, that in order to extend a class with new behavior we inherit a new class from it, and add methods to this inherited class. Plain and simple. But how about, for example, sealed classes? Let’s take a basic example: You want to be able to alter a string to have first letter in each world capitalized.

To accomplish this you would probably want to do something like:

using System;
public class MyString:String
{
    public string ToFirstCapitalized()
    { 
        //any implementation you'd like (as long as it's black)
    }
}

Plain and simple, isn’t it? Unfortunately this code has one flaw: It won’t compile. System.String is marked as sealed, so you can’t inherit from it. The only option you have left is to delegate this work to some other class, for example like this:

using System;
public static class MyStringCapitalizator
{
    public static string ToFirstCapitalized(string input)
    { 
        //any implementation you'd like (as long as it's black)
    }
}

Well, this at least will compile, although now instead of this:

string someString = "It's SoME weIrD StrING. Isn'T iT? IT BEcamE liKE This FRoM ListTENING to JINGLE from BETTer kNOW a FRAmEwoRK";
string capitalizedString = someString.ToFirstCapitalized();

You have to write something like this:

string someString = "It's SoME weIrD StrING. Isn'T iT? IT BEcamE liKE This FRoM ListTENING to JINGLE from BETTer kNOW a FRAmEwoRK";
string capitalizedString = MyStringCapitalizator.ToFirstCapitalized(someString);

You now are able to accomplish the goal, but you have to explicitly call another class’s method, so of makes your code more difficult to use.

This is one of possible places where you might want to use Extension Method. As most new things in C# 3.0 (and VB9.0, or Chrome 2.0 for that matter), Extension Methods we’re introduced to enable LINQ. They basically are a syntactic sugar, but they can greatly improve readability of your code, and make it easier to use, like in this example.

Using Extension method you can pin methods to classes you don’t control (like System.String), so that although implementation of the method is contained in some custom class, you can call the method as if it was implemented by System.String.

Using Extension Methods in its core is plain and simple. You create a  static class with static method, where first parameter is of type you want to extend, preceded by keyword this.

 

namespace ExtensionMethodsHelloWorldPartI
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            string someString =
                "It's SoME weIrD StrING. Isn'T iT? IT BEcamE liKE This FRoM ListTENING to JINGLE from BETTer kNOW a FRAmEwoRK";
            
            //you can call method explicitly
            string capitalizedString1 = MyStringCapitalizator.ToFirstCapitalized(someString);
 
            //or as if it was implemented by System.String
            string capitalizedString2 = someString.ToFirstCapitalized();
        }
    }
    public static class MyStringCapitalizator
    {
        public static string ToFirstCapitalized(this string input)
        {
            //any implementation you'd like (as long as it's black)
        }
    }
}

Thanks to this little cosmetic change you can call our new method directly on type string. It is convenient for users of your code, as they will see this method in their IntelliSence dropdown. Notice that it has different icon, with little dropping arrow, that will enable you to immediately distinguish Extension Methods from other. ExtensionMethodsHelloWorldPartI

In Part II we will take a closer look at how compiler decides which of several candidate extension methods to call.