C# 3.0 Language Enhancements for LINQ – Part 2 – var Keyword, Extension Methods and Partial Methods

13 04 2008

The var Keyword

We come across this new keyword called var when we use LINQ, what does this var keyword do?

The var keyword is used to declare and initialize anonymous types

That’s really confusing! – What are these anonymous types?

To understand the var keyword, we need to understand what really anonymous types are, and to understand anonymous types we need to know about var keyword, lol! Both go hand in hand.

Let’s start with an example,

   1: var Student = new { Id = 1234, Name = "Chakkaradeep" };

Now we have an anonymous type which has the properties Id and Name declared and initialized using the var keyword. To illustrate what is happening here,


So we can come to a conclusion that the var keyword deduces the data type of an object with the initialization of that object.

Now you can do something like this,

   1: var query =
   2:       from name in names
   3:       select new
   4:       {
   5:             firstPart = name[0],
   6:             lastPart = name.Substring(1, (name.Length - 1))
   7:       };

And then used it this way,


But do not consider that var variable is loosely coupled and can change its type! Take an example,

   1: var FullName = "Chakkaradeep Chandran";
   2: FullName = 12;

When you compile the above code, it fails because the object FullName is initialized as a String and we are trying to assign an Integer value to it!

This brings up an important point – var variables must be initialized when they are being declared and that helps the var keyword to deduce its type

The introduction of anonymous types has also led to another change in the way objects and collections are initialized

Say, we have a Class Person

   1: public class Person
   2: {
   3:     public string Name;
   4:     public string Address;
   5:     public int Pincode;
   6: }

If you want to initialize an object of type Person and give default values to those properties, the normal way would be,

   1: Person person = new Person();
   2: person.Name = "Chakkaradeep";
   3: person.Address = "Dunedin";
   4: person.Pincode = 9016;

But now we could directly do this,

   1: Person person = new Person
   2: {
   3:     Name = "Chakkaradeep",
   4:     Address = "Dunedin",
   5:     Pincode = 9016
   6: };

That certainly looks easier and neat!

This doesn’t stop with only Classes; it’s even possible with Collections,

   1: List<string> persons = new List<string>
   2: {
   3:     "Wellington",
   4:     "Dunedin",
   5:     "Invercargill"
   6: };

Extension Methods

The best way to understand Extension Methods is from an example

Let’s take our previous post’s example of filtering names that contains a character. We did something like this,

   1: List<string> FilteredNames =
Utility.FilterNames(names, n => n.Contains('c'));

Wouldn’t it be really nice and useful to provide something like this?

   1: List<string> FilteredNames =
   2:       names.Filter(n => n.Contains('c'));

That’s what Extension Methods allows us to do!

What are we actually doing in our above code block?

– We have “added” a method called Filter to an existing type which is string[] (array of strings)

This has one advantage. It doesn’t require you modify anything in the type string[], we just extend it and add our method

So, how are these done?

Extension Methods are nothing but static methods in a static class that can be called by using instance method syntax

We need to do some changes to our Utilty class to make it ready for Extension Methods. We need to change the class to a static class and include a static method called Filter

   1: namespace LINQEnhancements
   2: {
   3:     public static class Utility
   4:     {
   5:         public static List<string>
   6:            Filter(this string[] names,
   7:                 Func<string, bool> customFilter)
   8:         {
   9:             List<string> NamesList = new List<string>();
  11:             foreach (string name in names)
  12:             {
  13:                 if (customFilter(name))
  14:                     NamesList.Add(name);
  15:             }
  17:             return NamesList;
  18:         }
  19:     }
  20: }

And now you can use the way we want it,

   1: List<string> FilteredNames;
   2: FilteredNames = names.Filter(n => n.Contains('c'));

The reason I have shown the Utility class along with namespace is that, if your extension methods are in a different namespace, you have to import that namespace to actually make use of those extension methods

   1: public static List<string>
   2:   Filter(this string[] names,
   3:       Func<string, bool> customFilter)

The above line is where our trick lies. We explicitly tell that Filter is a static method applied on a static variable of type string[] (array of strings)

Where are these used? Remember our Standard Query Operators in LINQ?

   1: IEnumerable<string> query = names
   2:                             .Where(n => n.Equals(matchName))
   3:                             .Select();

Yes, you got it right!

And all these Standard Query Operators are available to use by importing the namespace System.Linq

using System.Linq;

Partial Methods

A partial method has its signature defined in a partial type and its implementation defined in another part of the type. This sounds very similar to Partial Class. Yes, partial methods always reside inside partial classes so that they can be used in another part of the type.

Here is an example,

   1: public partial class MyPartialClass
   2: {
   3:     partial void MyPartialMethod();
   5:     public void NotPartial()
   6:     {
   7:         Console.WriteLine("Ooops..Not Partial!");
   8:     }
  10:     public void InvokePartialMethod()
  11:     {
  12:         MyPartialMethod();
  13:     }
  14: }

We have a partial class and a partial method called MyPartialMethod

Now, what happens if we do something like this?

   1: MyPartialClass partialClass = new MyPartialClass();
   2: partialClass.NotPartial();
   3: partialClass.InvokePartialMethod();

We do see that the method NotPartial gets invoked but nothing happens when we call the InvokePartialMethod

Now let us create another declaration for MyPartialClass and implement the partial method MyPartialMethod

   1: partial class MyPartialClass
   2: {
   3:     partial void MyPartialMethod()
   4:     {
   5:         Console.WriteLine("Hey, its a Partial Method!");
   6:     }
   7: }

And now do the same thing,

   1: MyPartialClass partialClass = new MyPartialClass();
   2: partialClass.NotPartial();
   3: partialClass.InvokePartialMethod();

We now see that our partial method too gets called as we have implemented it!

Well, there is lot of arguments going on in the community that why do we need Partial Methods when this can be achieved in many other ways. Partial methods are mostly used in design tools for use with auto-generated code. If you want to make use of those methods, you could write your own implementation and it’s going to be used, else the compiler just doesn’t execute them and moves on.

Partial Methods are heavily used by LINQ-to-SQL designer tools and that’s the reason I wanted to explain about them here.

There are some golden rules that we need to follow if we are writing partial methods,

· Partial method declarations must begin with the contextual keyword partial and the method must return void.

· Partial methods can have ref but not out parameters.

· Partial methods are implicitly private, and therefore they cannot be virtual.

· Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.

· Partial methods can have static and unsafe modifiers.

· Partial methods can be generic. Constraints are put on the defining partial method declaration, and may optionally be repeated on the implementing one. Parameter and type parameter names do not have to be the same in the implementing declaration as in the defining one.

· You cannot make a delegate to a partial method.

Useful Resources

1) Standard Query Operators

2) LINQ-to-SQL