Hello LINQ

In Microsoft Pakistan Developers Conference (PDC) 2007, I attended a sessions on Language Integrated Query (LINQ) but until recent I didn’t utilize it seriously. But recently I go through some videos on LINQ at MSDN. I was impressed at all 🙂

LINQ is used to query data from objects. There are three basic categories of LINQ:

  • LINQ to Objects
  • LINQ to XML
  • LINQ to SQL

If you are new to LINQ, I would recommend to skim through article on LINQ on MSDN. Let’s see a simple example of LINQ to Objects. LINQ to Objects is used to query in-memory data stores. Suppose we have a collection of countries’ name and we want to get list of countries starting with ‘C’.

string[] countriesCollection = 
{ "Pakistan", "India" , "UAE", "US", "Australia", "UK", "Canada",
"China"};

Without LINQ, we need to traverse the list and manually add a check on each string. LINQ do that for me in a simpler way:

var queryResult = from country in countriesCollection
                  where country.StartsWith("C")
                  orderby country
                  select country;

Now simply print the list return, ordered, in queryResult

foreach (var item in queryResult)
    Console.WriteLine(item.ToString());

The ouput will comprise of two items:

Canada
China

Similarly, we can query to not only primitive data types but also custom data types as well. For instance, let’s say we have a class Student as shown below:

public class Student
{
    public string Name { get; set; }
    public int Id { get; set; }
    public string Grade { get; set; }
    public Student(string stName, int stId, string stGrade)
    {
        Name = stName;
        Id = stId;
        Grade = stGrade;
    }
}

Let’s create a List of student type and manually feed some data to it. After that we will query to get all the student having grade B:

List studentsList = new List();
studentsList.Add(new Student("Adil", 1, "A"));
studentsList.Add(new Student("Sami", 10, "B"));
studentsList.Add(new Student("Faisal", 100, "B"));
var query = from student in studentsList
            where student.Grade == "B"
            select student;

Printing result in query will be

Sami
Faisal

In short, LINQ to Objects allows us to query in memory objects not just on primitive data types but also on our custom data types and provide an ease to developer for querying data from in memory objects.

Object Initializers in C# 3.0

C# 3.0 facilitates programmer by providing the feature of Object Initializers for both Named and Anonymous types. Object Initializer let you assign values to any accessible fields or properties without the need to create a explicit constructor. Consider the code below:

private class Student

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

static void SomeMethod()
{
    // Object initializer
    Student stObj= new Student {Name = “Adil”,  Age = 24 };

}

If we notice in the code above, the properties of student are assigned values directly with the use of braces { } around it and comma in between each member. Without object initializer this will be done in the way as shown below:

Student stObj=new Student();
stObj.Name=”Adil”;
stObj.Age= 24;

Again features such as Automatic properties, Implicitly typed local variables and Object Initializer are provided in C# 3.0 specially to support LINQ.

Implicitly Typed Local Variables

Earlier we saw a new feature “Automatic Properties” in C# 3.0. Today we are going to see the use of new ‘var’ keyword.

C# 3.0 allows local variables in methods to have an implicit type by identifying it from the type of its initial value. For instance,

var str = “Adil“; // str is compiled as a string

var col = new[] { 0, 1, 2 }; // col is compiled as int[]

var anoType= new { Name = “Terry“, Age = 34 }; //anonymous type

When you call the GetType method on str, it will return System.String type.

A point of consideration is that var keyword is not like var in javascript and it does not mean that variable is late-bound. It is actually a keyword for compiler to determine and assign the type with respect to the value initialized.

Also note that var keyword cannot be used in class variables and also in passing variables to method or returning from method. It does not support nullable type as well. Further you need to give it some value at the time of declaring otherwise it will be an error. Let say,

var someVar;  someVar= 1; // not allowed

The var keyword does not impress until it is used with LINQ. We will see it’s use with LINQ in some later post.

Design Patterns

Design Patterns are reusable solutions to a commonly occurring problem in software. It’s not a ready to use code instead it is more like a general template or solution for a particular problem. When you get understanding of Design Patterns then at a time designing solutions you can come across a situation like “Oh Yes! I can apply here that particular design pattern” 🙂

Design Patterns provides you a proven and tested solution to a particular problem. They speed up design process and hence enhances productivity. I’m not going to give detail introduction to Design Patterns as purpose here is to understand and see how we can apply a particular design pattern in a language here C#. Briefly, there are four basic categories of Design Patterns

  • Creational Patterns
  • Behavior Patterns
  • Structural Patterns
  • Concurrency Patterns

Personally, I have more hands on of Creational Patterns. There are numerous design patterns in each category. We will look some of the more common in them.

So Let’s begin with a very simple design pattern which I learnt first and i.e. Singleton.

Singleton Design Pattern

Singleton ensures a single instance of the class and have global access. To apply singleton to a class we make it’s constructor(s) private and the class itself creates its object. For external world to get the object of the class it uses a static method that returns the object. Lets see the code below:

public class Singleton
{
private static Singleton instance;

private Singleton() {}

public static Singleton GetInstance()
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}

Here you can see, the class has a static object of itself. Whenever the want the instance of that class you will call GetInstance Method. If the object is not initialized, the method will initialize itself or it’s done already it will give you the same object. In this way, the class will ensure a single instance and will provide a global access through static method GetInstance.

Note that it is the simple way of creating Singleton class, There are optimized version as well that provides multi-thread safe version by using lock mechanism of C# and .NET. For details please visit Implementing Singleton in C#

In the coming posts, we will see different design patterns belonging to different categories. Besides, a very good material dedicated to Patterns and Practices is available on MSDN.

Bye for now! Have a good time.

Binding Enum to ComboBox

Hi,

Whether it’s Windows Forms or Windows Presentation Foundation While working with ComboBox, we usually want to bind any list as ComboBox Items.

For example,

//In windows forms
string[] names = { “Microsoft”, “IBM”, “Apple” };
cmbNames.DataSource = names;  //cmbNames is comboBox ID

or

//In windows presentation foundation
string[] names = { “Microsoft”, “IBM”, “Apple”};
cmbNames.ItemsSource = names;  //cmbNames is comboBox ID

That’s simple! But today I wanted to convert enum constants into an array of string and I wanted to make it ItemsSource of combo. So I created an enum type “Names” and tried that

public enum Names

    Microsoft, 
    IBM, 
    Apple
}

Names nameList;
cmbNames.ItemsSource = nameList ; //compile time error-

A compile time error is raised claiming that Cannot implicitly convert type ‘Names’ to ‘System.Collections.IEnumerable’. So i searched for that and find a good single line solution 🙂

//For WPF
cmbNames.ItemsSource = Enum.GetNames(typeof(Names));

//and In windows forms
cmbNames.DataSource = Enum.GetNames(typeof(Names));

It will convert enum contants into string[]. To convert back from string to constant you can use Enum.Parse(…).

Nice Feature! Isn’t it?

Generic Methods in C#

Hi,

One of the great features of C# is Generic Method. Back in sometime I wrote a Generic Method which serializes or de-serializes an object. The Generic methods are declared with type parameters. So here is the code snippet I wrote some time earlier:

public static void DoSerialization(Stream stream, SerializationType sType, ref T objToUse)
{
try
{
if (objToUse == null)
throw new Exception(“Missing object to serialize/De-serialize”);
XmlSerializer serializer = new XmlSerializer(typeof(T));
if (sType == SerializationType.Serialization)
serializer.Serialize(stream, objToUse);
else if (sType == SerializationType.DeSerialization)
objToUse = (T)serializer.Deserialize(stream);
}
catch (Exception ex)
{ //catching of exceptions
}
}

Let me explain this code. The method takes stream to be de-serialized or serialized depending upon the second argument. SerializationType is enum Type something like

public enum SerializationType
{
Serialization,
DeSerialization
};

and finally the reference of object to serialize or de-serialize. Well let me tell you due to support of type parameter, I was able to make a general function which will serialize or de-serialize any type of object and saved me from re-writing methods for different data type and at the same time its type safe as well 🙂

Isn’t it a great feature. If you do not use Generic Method, start considering them.

C# ? According to Microsoft

“C# is a simple, type-safe, object oriented, general-purpose programming language. Visual C# provides code-focused developers with powerful tools and language support to build rich, connected web and client applications on the .NET Framework.” -MSDN

Automatic properties in C# 2008 (Language Feature)

The C# 2008 supports number of new constructs such as lambda expression, automatic properties, implicitly typed local variables, partial methods etc. Let’s examine automatic properties.

Up till now we have been encapsulating our private fields as

class TestClass
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}

}

This approach is good enough but let say if we require 20 fields as public interface then it requires a little effort of creating private field first and then encapsulating it as a public property.

As the word “automatic” refers, you can now create just properties and C# will automatically create a backing private field for you at compile time though it’s not visible to you.

class TestClass
{
public string Name { get; set; }
}

The automatic properties are initialized by default values i.e. integers are initialized with zero, strings with empty, reference type with null etc.

You can apply restricting access similarly as one can apply on normal properties such as

public string Address { get; private set; }

having public scope of get and private scope of set. However you cannot write read only fields as you previously like

public string Address { get; } //error

read only should be done by restricting access through access modifiers. We will access the automatic properties in the similar way as we did in case of normal properties.

TestClass tc = new TestClass();
tc.Name = “CD”;

Console.Write(tc.Name);

The automatic properties are one of the good extensions C# 2008 provides, if you are just need a simple public property to access private fields outside class then automatic properties are the good alternative.

String vs. StringBuilder

Well some juniors told me that they have started C# so they want me to start some beginner level discussion on C# .NET

The first thing that came in my mind for novice was comparison between string and string builder class.

I don’t know whether you have noticed it or not.

In C# .NET strings are immutable and hence it also do not allow us to change it.

By immutable i mean, whenever we change the string it will create a new instance of it in memory rather than changing value on same memory location.

Let me clear this with the help of code.

Consider following code snippet :

string str= “Immutable”; //line 1
str += ” Test”; //line 2

when i appended ” Test” in str (in line 2), rather than appending it in the same instance, it will create another instance (somewhere else in memory) with value “Immutable Test” and str will now refer to “Immutable Test” in memory leaving the old one in memory unreferred for garbage collector.

It means that whenever we will change string, the .net framework will create a new one at any other place in the memory.

Plus because of this you are not allowed to change any string like
str[1]= ‘c’; because of immutability…

For the required behavior StringBuilder class is used.

String is faster than StringBuilder

thats all i want to say right now… Please correct me if i m wrong somewhere…

bye for now and keep saying

.NET Rocks :p