Exploring Nullable types : Part 1

In this post, I am going to talk about Nullable types. Actually most of developers know, in c# we have
mainly two types.
– Reference type
– Value type.
But we have more type, that is called Nullable type.

Actually it is a value type but it has feature of both reference and Value type.

Continue reading

Generics and Constraints over Generics

In this post,  I am going to discuss about Generic Classes and bit more on this.  Just for a smooth start,

“Generics were introduced in .NET 2.0, which provides us a way to create Classes/Methods/Types and many more without specifing the specific type of parameters. Parameters must be provided at the time of creating the instances. So we can say Generics are only a blueprint/templated version and actual type is defined at Runtime.”

So lets first create a simple Class say Point Continue reading…

Concurrent Collections with .NET4.0

Earlier we used Collections, they were never ThreadSafe. Generics introduced in .NET 2.0 are TypeSafe but not ThreadSafe.

Generics are Typesafe means whenever you are going to declare any generic type, you need to specify the type that is going to be held by the List. And whenever you are going to retrieve any item from list you will get the actual type item, not an Object like we get from Arraylist.

But Generics are not ThredSafe, it’s a programmer’s responsibility. Means let’s say if you have an list collecting some objects. That list is shared amongst several threads, the it may work hazardous if two threads try to access the List at the same point of time, like adding/removing/iterating  items from the same list at the same time.

Thread safety can be implemented with the help of locking the collection and other similar ways. But locking the entire list for the sake of adding/removing an item could be a big performance hit for an application based on the circumstances.

.NET 4.0 provides new classes for the concurrency as Concurrent collections. These are

  • ConcurrentDictionary< Key , Value> Thread safe dictionary in key value pairs.
  • ConcurrentQueue<T> Thread safe FIFO datastructure.
  • ConcurrentStact<T> Thread safe LIFO datastructure.
  • ConcurrentBag<T> Thread safe implementation of an unordered collection.
  • BlockingCollection<T> Provides a Classical Producer Consumer pattern.

Above all classes are available in the namespace System.Collections.Concurrent .

These collections allow us to share the data amongst several thread without any worry.

Concurrent Collections are the key of Parallel programming, that is introduced in .NET 4.0

So let’s discuss the very commonly used list ConcurrentDictionary

  • A thread safe add/remove from dictionary.
  • Very user friendly methods that make it unnecessary for code to check if a key exists before add/remove.
  • AddOrUpdate : Adds a new entry if doesn’t exist else updates existing one
  • GetOrAdd : Retrieves an item if exists, else first adds it then retrieve it
  • TryAdd, TrygetValue,TryUpdate, TryRemove : Allows to do the specified operation like Add/Get/Update/Remove and if it fails the does the alternative action.

Benefits of the above Concurrent collections:

  • Now programmer doesn’t need to take care on threadsafety.
  • Uses light weight synchronization like SpinWait, SpinLock etc that use spinning before putting threads to wait – for short wait periods, spinning is less expensive than wait which involves kernel transition.
  • Means faster add/remove/iterate in multithreading environment without writing the code for it.
  • Some other classes like ConcurrentQueue & ConcurrentStack don’t rely on Interlocked operations instead of locks which make them faster.

There is lot more to discuss on this. But keeping it short and simple, let’s finish it we’ll discuss other things coming subsequent posts.

Looking in Func Delegates

This is an extension of my earlier blog post. I myself, find delegates as one of  the most powerful type to use in C#. It helps in writing very flexible and scalable program.

As I already discussed in my last blog that in the traditional way, we need to write more code.There I also discussed, One predefined delegate Action delegate that is provided by the framework.There are four flavors of Action delegate is provided.

One more type of predefined delegate that is provided by .NET that is counterpart Action delegate  . As we saw that it always returns void. But Func returns a value instead of void as Action does.

There is also 5 flavours of the Func delegate is provided.These are

– Public delegate TResult Func<TResult>()

— Public delegate TResult Func<TResult>()  // Take no parameter and returns a value

–  Public delegate TResult Func<T, TResult>(T t)  // Take one input parameter and returns a value

– Public delegate TResult Func<T1, T2, TResult>(T1 t1, T2 t2)  // Take 2 input parameter and returns a value

– Public delegate TResult Func<T1, T2, T3, TResult>(T1 t1, T2 t2, T3 t3)  // Take 3 input parameter and returns a value

– Public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 t1, T2 t2, T3 t3,T4 t4)  // Take 4 input parameter and returns a value

If we see the declaration, TResult is put at last, this is just a convention. One can put it wherever s/he wants.

First lets see first one , with no parameter and returning a value

public class Program
{
static void Main(string[] args)
{
//Creating the Func variable and assigning it a function
Func<string> myFunc = SayHello;

//Calling function using Func Delegate
string returnedString = myFunc();

Console.WriteLine(returnedString);

Console.ReadKey();
}

private static string SayHello()
{
return "Hello Dude!!";
}
}

Now lets move to code to another overload of Func Delegate. It takes two input parameter and resturns a value.

public class Program
{
static void Main(string[] args)
{
//Creating the Func variable (which takes two input parameters and returns a value) and assigning it a function
Func<double, double, double> myFunc1 = Add;

//Calling function using Func Delegate
double sum = myFunc1(3.5, 4.5);

Console.WriteLine(sum);

Console.ReadKey();
}

private static double Add(double first, double second)
{
return first + second;
}
}

It is also same as Action delegate. i e It can also be used with Anonymous functions and Lambda functions. Lets have a quick look on both

Anonymous Function:

public class Program
{
static void Main(string[] args)
{
//Creating the Func variable (which takes three input parameters and returns a value) and assigning it an Anonyomus function
Func<double, double, double, double> myFunc1 = delegate(double d1, double d2, double d3)
{
return d1 + d2 + d3;
};

//Calling function using Func Delegate
double sum = myFunc1(3.5, 4.5, 5.5);

Console.WriteLine(sum);

Console.ReadKey();
}
}

Lambda Function:

public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Program
{
static void Main(string[] args)
{

Func<Employee,string> checkEmployee = s=>{
if (s.Id > 11)
return s.Name;
else
return "Employee is not with the given Criteria.";
};

Console.WriteLine(checkEmployee(new Employee() {Id=12, Name="Brij"}));
Console.WriteLine(checkEmployee(new Employee() {Id=10, Name="Abhijit"}));

Console.ReadKey();
}
}

Hope you all must have enjoyed the delegates.

We use delegates a lot. But most of us, use the traditional way in programs. When I learnt first these Action and Func delegates few weeks back, I found it very useful. It helps us writing better and well organised code, also less error prone code. I talked to lot of developers, they didn’t have any idea about these predefined delegates. So I thought of sharing to you all.

Please share your valuable feedback.

Cheers,

Brij