myfavoritemovies.us

September 26, 2008

? and ?? feature in C#

Filed under: C# 3.0 — @ 1:47 pm

In C# 3.0 there is a new feature assign and check the null values that lot of people doesn’t know it even exists. Well I didn’t know till couple of months ago. Even though I knew, there were couple of good circumstances I could have used it but never used it. So yesterday I decided to look at the code and see if I can save some typing by using this operators.

Lets jump into an example and look at the operator in action. I like examples more than theory so here it goes…

? is currently used as a trinary operator as we all know. Good example would be

string resturnResult = (value == null)?””:value;

in the previous statement, we are first checking to see if the value is null then assign an empty string to the returnResult else just assign the value in the value variable.

Now the use of ?? operator. The same statement we look at before would be

string returnResult = value ?? “”;

It does the same thing as the earlier statement we look at.  ?? operator will check and see if the value string is null and if it is null then it will assign the value to its right, else assign the value. Isn’t it elegant? I like this code better than the earlier one. We can argue about readability but once you start using it you will learn to read it as well.

Now going back to one other operator ‘?’ Currently it is used in the trinary operator, now it is a new face as well. Something like the following

int? age;

This basically says, the integer variable age could take null value. Why would someone want to do that, to be honest I haven’t used it. So in my limited knowledge on this subject, I could see the use in database side. You might run a stored proc and get user information from table and assign values to these variable which could take null values. If some rows doesn’t have age value set in the columns, that could come as null. So when the value is retrieved and it could be assigned to age variable without throwing an exception. Even though that is the intend, I haven’t sold on this idea yet. So if you any of you have used this operator, please drop me a note.

Thanks and happy coding…

September 16, 2008

Exception handling in NUnit

Filed under: NUnit,Tips and Tricks — Tags: , — @ 2:52 pm

This is very simple but I thought, it is worth a note (or for my note taking).  Before I go into handling exception, I need to tell you something I read couple of days ago. I can not remember which blog (I follow lot of blogs) but it kinda stuck with me. When you code you try to follow the following four things

  • Make it correct
  • Make it clear
  • Make it concise
  • Make it fast
I was tossed it to my friend Jim at work (I consider him very sharp and talented and look up to him). Here is what he has to say 
  • Write a test
  • Make it pass
  • Refactor
  • Optimize if needed <- condition seldom met, may be 1/10000 loops
  • repeat the loop
If you look closely both of them are same. What Jim specified in the loop above more of TDD in mind and the earlier one is much more general and it can adapt to any environment. But I thought it is worth sharing.
Lets go back to NUnit thing I was talking about. In one of coding situation, I need to throw an exception with just a string. Something like the following
throw new Exception(“Test exception”);
Now when you test it in NUnit, you need to make sure you use
[ExpectedException(“System.Exception”, ExpectedMessage=”Test exception”)]
thats it, nothing more. See this is very simple blog.

September 3, 2008

Some cool string manipulation in C#

Filed under: C# 3.0 — @ 2:04 am

Today I was writing a simple code which would readin a commandline parameters like

name param1=value1 param2=value2 param3=value

from the values it is very obivious the frst parameter is a individual name and others are named parameters with associated values. If we could do it in our normal mode, we would first assign the first parameter to the unique name field and then we would split each following arguments and put it in a array or arraylist or some sort.

Since it is key value pair the best bet would be Dictionary or Hash and I prefer Dictionary. For some reason I never came across a situation I had to use hash yet. Anyway, so I was going to write the split code and method and then I realised I could do the split and assign it o an arry in single statement and here is how I did it.

string[][] pharsed = argument.Skip(1).Select(s => s.split(‘=’)).ToArray();

IDictionary<string, string> dictionary = new Dictionary<string, string>();

foreach(string[] vaue in pharsed)

{

     dictionary.add(vaue[0], vaue[1]);

}

Thats it, what I liked was the ease to skip and split on the fly. I haven’t figured out, how to create Dictionary on the fly in that single statement. Once I find out how to do it, I will update it in here for my notes…

Have fun.

Powered by Qumana

September 2, 2008

Factory pattern through reflection.

Last week I came across a situation where, I need to implement bunch of classes which perform same task differently when it is called. (Simply put, factory pattern). So I thought, based on GOF it is a simple implementation.

Create a abstract factory class and then create sealed worker class which implement the actual task. Simple enough. In the main program have a switch which checks the incoming parameter and based on the parameter, we create instance of a proper worker class and vola we got the implementation done.

Now the point to remember here is, if we need to add a new worker class, what are all the elements involved? First you need to add a new case statement for the new worker class initation and then add the new worker class itself. Two code changes. Not a big deal. But if you happen to have too many implementation or in other words too many worker implementation then your switch statement could grow larger and larger.

This limiation forced me to think if there is any other way of creating classes on the fly. I talked to one my collegue and he pointed me to one his implementation he is currently using that is using reflection. So here is how it is implemented.

First create the interface you would like the factory workers to implement. Something like the following;

IWorker.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TraditionalFactory
{
public interface IWorker
{
void SayName(string name);
}
}

You can see all we are trying to implement is a ‘SayHello’ method. Following two are two worker implementation of the Factory Interface;

Worker1.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TraditionalFactory
{
public class Worker1:IWorker
{
#region IWorker Members

public void SayName(string name)
{
Console.WriteLine("Name from first worker is {0}", name);
}

#endregion
}
}

Worker2.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TraditionalFactory
{
public class Worker2:IWorker
{
#region IWorker Members

public void SayName(string name)
{
Console.WriteLine("Name from second worker {0}", name);
}

#endregion
}
}

Based on the interface and the worker implementation there is nothing new. The code that make this one work without big switch statement is in the main program.

Program.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace TraditionalFactory
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Which worker to run (Worker1 or Worker2?");
string workerName = Console.ReadLine();
Type workerType = Type.GetType("TraditionalFactory."+workerName);
IWorker worker = (IWorker)Activator.CreateInstance(workerType);
worker.SayName("data passed");
Console.ReadKey();
}
}
}

This factory model implementation compltly depends on the reflection feature of C#. This also depends on the the consumer to this program aware of which worker they need to consume by name or you need to create a dictionary mapping of the user input to worker class mapping of some sort. For this implementation I am assuming the consumer knows which worker to use.

The point of interests are, first creating the type of the class we are going to instantiate. In our class we are going to find the factory interface type of execuing assembly using ‘Type.GetType’ method call. Which looks at the executing assembly or clr to see if it finds matching type. If you look at the code closely, since we already know which worker that we are interested to consume based on ‘workerName’, we look for the namespace + workerName in the GetType. (This is where reflection come into get the type of the class we are trying to consume). Once the type identified, we call in the ‘Activator.CreateInstance’ method to create the instance of the worker class through the interface and then execute the public method from the interface. Thats it, we got ourself Factory pattern implemented.

The benefit of this implementation is that, when you want to add a new worker class, you simply add the worker class, compile it and deliver the exe. No more main program change. One code change and you are done.

The problems I see with the implementation is that, you need agree on how the consumers are going to consume the worker class and make appropriate mapping before hand or make the consure to call in with appropriate worker name explicitly (like the example below).

One for my notes….

Powered by WordPress