Click here to Skip to main content
Click here to Skip to main content

Sexy C#

, 18 Dec 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
In this article I will explain one by one of those hot and sexy features with code example. In some section I use question(Q) and answer(A) pattern so that audience can understand better.

Table of Contents  

1. Introduction  

Sexy CSharp 

C# is a very popular programming language. It is mostly popular in the .NET arena. The main reason behind that is the C# language contains so many useful features. It is actually a multi-paradigm programming language.

Q. Why do we call C# a muti-paradigm programming language?

A. Well, C# has the following characteristics: 

  • Strongly typed  
  • Object Oriented 
  • Functional 
  • Declarative Programming 
  • Imperative Programming  
  • Component based Programming
  • Dynamic Programming

So we can say it is multi- paradigm programming language. C# has many interesting features that seems so hot and sexy. For that reason we can say it is a sexy language too. In this article I will explain one by one of those hot and sexy features with code example. In some sections I use question(Q) and answer(A) pattern so that audience can understand better. 

2. Background       

 

July 2000 C# was born. Anders Hejlsberg is the father of this modern language. C# was born with many programming features and when any new version release, it comes with new features. In real life I see many C# developers did not understand few  sexy features properly or not to use those. If they would understand that features properly then they can create more reusable, powerful, sexy code and which will add more value to their software products.

3. Sexy Features   

Sexy Features 

Again I repeat, there are so many programming features are available in C# and all those are very useful and help us to write complex logic with easy code. Every developers should know all of them. But all features are not sexy features. Question may come, based on what criteria I say one feature is sexy and another is not. There is no hard and fix rule that I applied for judging sexy features. In my development experience I feel some features are really more attractive, more interesting, high appealing than others. Only those features I am saying sexy features. I am focusing all those features in this article. Now I will explain with code example all those one after another.  

3.1. Extension Method  

Extension Method 

C# introduce Extension Method from version 3.0. In straight forward way you can say it is a special kind of static method that allows us to add methods to an existing type. The magic is it adds that without recompile code. That means you can extend any type, it does not matter whether that type's source code you have or not. So summary is you can extend build in .Net types or any 3rd party types without their source code modification. Impressed? 

You need to follow following rule to create extension method: 

  • Method should be static. 
  • Method access modifier should be public.
  • Method must be located in a static class. 
  • Method namespace must be include in using block where it will use. 

Q. I want to create an extension method which name will be "CountSpace" and it will return no. of spaces and it should be available .NET string object. How can I write this?

A. See the code block first:

public static class ExtensionMethods
{
    public static int CountSpace(this string str)
    {
        if (string.IsNullOrEmpty(str)) return 0;
 
        return str.Count(c => c == ' ');
    }
 
    public static string ToString(this string str)
    {
        return "codeproject.com";
    }
}
[TestMethod]
public void Count_No_of_Space_In_A_Sentence()
{
    string data = "this is a beautiful laptop.";
    int totalSpace = data.CountSpace();
    Assert.IsTrue(totalSpace == 4);
}

You just need to follow 3 steps: 

  1. Create a static class named ExtensionMethods
  2. Inside this class, create a static method named CountSpace with a parameter with this keyword with string type. This will create magic for you.  CountSpace  method will calculate the no of spaces from its argument and return its value.
  3. If ExtensionMethods class's namespace not included in your using method then first you add that and write your test code like my Count_No_of_Space_In_A_Sentense. 

One thing you should remember your CountSpace method not only you can use with Extestion Method but also you can use it like a static method.

[TestMethod]
public void Count_No_of_Space_In_A_Sentence_As_Static_Method()
{
    string data = "this is a beautiful laptop.";
    int totalSpace = ExtensionMethods.CountSpace(data);
    Assert.IsTrue(totalSpace == 4);
}

But point to be noted that this is not recommended approach to use.

3.1.1. Should Know Before Use: 

  • Extension method scope is namespace level.
  • Extension method override is not supported.
  • Extension method can use Interface level.
  • If object instance method and extension method are same including signature then instance method get priority. For that reason need to use extension method carefully.
  • If you write extension method for a type that's source code you are not maintaining then always have a chance to break extension method.

3.2. Anonymous Type

C# introduce Anonymous Type from version 3.0, It is a special class, compiler creates it at run time. r that reason you can called it compiler generated class too. Anonymous Type helps to encapsulate public read only property without explicitly defined type. In many scenarios extra class creation may seems to be overhead specially when you know class will use only one time and no chance to re use it in future or no manageability benefit comes . In those scenarios Anonymous Type will very useful. 

The main characteristics of anonymous types are as follows: 

  • Anonymous type should not be child of other type. It implicitly derived from built in object type.
  • It should not be parent of another type. That means it should not be extendable.
  • Compiler provide anonymous type name and developer have no control on it.
  • Only public property are allowed to be member of anonymous type.
  • Need to use var or dynamic keyword for take reference of anonymous type object.

Q. I want to create anonymous type. How can I create this? 

A.

 

To create anonymous type you just use "new" constructor method is as follows:

var obj = new {Id=1, Name="Mr. Bill"}; 

instead of var you can use dynamic as replace of var keyword.

dynamic obj = new{Id=1, Name="Mr. Bill"};

[TestMethod]
public void Check_Anonymous_Type()
{
    var obj = new { Id = 1, Name = "Mr. Bill" };
    Assert.IsTrue(obj.Id == 1);
    Assert.IsTrue(obj.Name.Equals("Mr. Bill"));
}

Q. Is it possible to create anonymous type as argument or return type of a method?

A. Yes it is possible to use argument or return type of created anonymous type. In both method argument or return type, you need to defind type should be:

  • object or  
  • dynamic 

If you use object as type, you need to use reflaction for retrive property values. So use dynamic is smart approach in this case.

The following code sample will show how to use dynamic type with anonymous type as a method argument and also return type.  

[TestMethod]
public void Check_Anonymous_Type_As_Argument_As_ReturnType()
{
    var obj = new { Id = 1, Name = "Mr. Bill" };
    var result = ProcessAnonymousType(obj);
    Assert.IsTrue(result.Code == "101");
}
private dynamic ProcessAnonymousType(dynamic employee)
{
    int id = employee.Id;
    string name = employee.Name;
    var newEmployee = new { Code = (id + 100).ToString(), Name = name };
    return newEmployee;
} 

Q. What are the scenarios anonymous type might be use?

A. If you want to create a sub type (actually it is also new type) from another type then without creating explicit type, you can create anonymous type. Specially you will find that many linq expression where main object contain lots of property but you need few of them for working. In this case you can use anonymous type.   

[TestMethod]
public void Create_Anonymous_Type_Using_Linq()
{
    var empList = new List<Employee>();
    empList.Add(new Employee { Id = 1, Name = "Mr. A" });
    empList.Add(new Employee { Id = 2, Name = "Mr. B" });
    empList.Add(new Employee { Id = 3, Name = "Mr. C" });
 
    var people = empList.Select(e => new { e.Id, e.Name });
    foreach (var person in people)
    {
        int id = person.Id;
        string name = person.Name;
    }
    Assert.IsTrue(people.Count() == 3 && people.First().Id == 1);
}
private class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
} 

Here I created people list, which is created from existing empList (List of Employee). Actaully people is a list of anonymous type object which has only 2 properties Id and Name. This properties created from Employee object Id and Name property. It is also possible to create additional property that are not exists in Employee class. These are the power of anonymous type.

3.3. Delegate

Delegate 

Delegate feature is first introduced with C# 1.0 

Q. What is delegate? 

A. A short definition: “A delegate is a special kind of reference type that defines a method signature instead of an object”. Though delegate is a Type so you can create object from this type and associate compatible method  with this object. A delegate actually represents a function, that's why people often call it a function pointer. 

Q. Can you explain little more with code sample? 

A. See the following code block: 

public delegate string GetEmployeeNameDelegate(int employeeId);
[TestMethod]
public void Named_Delegate_Test()
{
    var employee = new GetEmployeeNameDelegate(GetFullTimeEmployeeName);
    /*
        another way you can call as follows.
        GetEmployeeNameDelegate employee =  GetFullTimeEmployeeName;
        framework will create employee delegate object and bind it 
        with GetFullTimeEmployeeName method
        */
    string employeeName = employee(1);
    Assert.IsTrue(employeeName.Equals("FullTimeEmployee-1"));
 
    employee = new GetEmployeeNameDelegate(GetPartTimeEmployeeName);
    employeeName = employee(1);
    Assert.IsTrue(employeeName.Equals("PartTimeEmployee-1"));
}
public string GetFullTimeEmployeeName(int empId)
{
    return string.Concat("FullTimeEmployee-", empId);
}
public string GetPartTimeEmployeeName(int empId)
{
    return string.Concat("PartTimeEmployee-", empId);
}  

GetEmployeeNameDelegate is a delegate type which represent a method signature which signature should contains  

  • 1 int (integer) type parameter
  • string return type    

GetFullTimeEmployeeName and GetPartTimeEmployeeName are two methods which are matched with this GetEmployeeNameDelegate delegate. We can bind those two methods with this delegate and execute method via delegate. After analyzing the code block you will understand that delegate is another type of feature which supports popular OOP feature named polymorphism (run-time).   

Another way to use delegate: 

[TestMethod]
public void Anonymous_Delegate_Test()
{
    GetEmployeeNameDelegate getEmployeeName = delegate(int x)
    {
        return string.Concat("Employee", x);
    };
    string employeeName = getEmployeeName(1);
    Assert.IsTrue(employeeName.Equals("Employee1"));
} 

You can see above code block that binding in-line code block to GetEmployeeNameDelegate type and execute that code block via delegate. This is different way to use delegate and it is different from previous one. Previously we directly bind a method with delegate and above code block we did not bind with any method, instead bind inline code block. This inline method binding is called anonymous method. Here we can say that we find two types of delegate

  1. Named delegate, which is directly bind with any method.
  2. Anonymous method/delegate which is bind with in line code block.  

In real life, we may find many scenarios where extra method creation seems to be overhead. Specially you find that some code block will use only one time and you will sure enough that  these code blocks will never be re-use or no need to create functional decomposition. In these cases extra method creation seems to be overhead and we can use anonymous method there. 

Q. I want to know when anonymous method converted to delegate?

A. Well, it is very important to know each developers. Actually at compile time anonymous methods are converted to delegate type.

3.3.1. Callback: 

By definition when code block send to another method as argument for execution is called callback. Execution of callback happened two ways:

  1. Synchronous way
  2. ASynchronous way 

Code block might be a method or inline code  block. We can not directly send a method  to another method as argument. We need to take delegate's help for sending code block/method to another method.

[TestMethod]
public void Method_As_Method_Argument_Test()
{
    GetEmployeeNameDelegate getEmployeeName = GetFullTimeEmployeeName;
    string employeeName = ProcessEmployeeName(getEmployeeName);
    Assert.IsTrue(employeeName.Equals("Full Name is: FullTimeEmployee-1"));
}
public string ProcessEmployeeName(GetEmployeeNameDelegate employeeNameDelegate)
{
    string name = employeeNameDelegate(1);
    return string.Concat("Full Name is: ", name);
} 

Here I am sending getEmployeeName delegate type object which points GetFullTimeEmployeeName method as another ProcessEmployeeName method argument. This ProcessEmployeeName method then execute GetFullTimeEmployeeName via delegate and receive the result and process it and return final result to its caller.

3.3.2. Multi-Cast Delegate:  

We already saw that one method is bind with one delegate. Means we saw one to one relation between delegate and method.  When delegate is executed under the hood the bind method is executed. But 1 delegate can bind with multiple methods too. Means  

1 Delegate = n Methods 

If that is happened for method bindings, we can say that is multi-cast delegate. Just point to be remember that every method should have same signature.

Q. How to create multi-cast delegate?

A. C# has 2 operators by which methods are bind and unbind with multi-cast delegate. These are:

  1. +=
  2. -=  

 += operator is used for binding method and -= is used for un-bind method.

[TestMethod]
public void MultiCast_Delegate_Test()
{
    GetEmployeeNameDelegate multiCastDelegateObject = GetFullTimeEmployeeName;
    //bind another new method
    multiCastDelegateObject += GetPartTimeEmployeeName;
    //It will return 2nd method string but execute both methods
    string employeeNames = multiCastDelegateObject(1);
 
    employeeNames = string.Empty;
    IEnumerable<Delegate> delegateList = multiCastDelegateObject.GetInvocationList();
    foreach (Delegate delegateObject in delegateList)
    {
        var del = delegateObject as GetEmployeeNameDelegate;
        employeeNames += del(1);
    }
    Assert.IsTrue("FullTimeEmployee-1PartTimeEmployee-1" == employeeNames);
 
    //un-bind last method
    multiCastDelegateObject -= GetPartTimeEmployeeName;
    employeeNames = string.Empty;
    foreach (Delegate delegateObject in multiCastDelegateObject.GetInvocationList())
    {
        var del = delegateObject as GetEmployeeNameDelegate;
        employeeNames += del(1);
    }
    Assert.IsTrue("FullTimeEmployee-1" == employeeNames);
} 

Q. How can I call multi-cast delegate? 

A. You can call multi-cast delegate same way as you call simple delegate. 

delegateObject(); Or delegateObject.Invoke(); //synchornous call 

But problem will raise when delegateObject will return values and you need to capture those values. If you simply execute: 

string result = delegateObject(); 

if delegateObject bind with 3 different methods and each of them returns string data then result variable will store only last method's return value.

Q. What will be solution?

A. For capture all return values, you need to execute delegate with different ways: 

  • You need to retrieve all delegates from the delegate invocation list.
  • Cast it as its desired type
  • Execute each delegate
  • Store each return value individually or concat all in a one. 

string employeeNames = string.Empty;
IEnumerable<Delegate> delegateList = multiCastDelegateObject.GetInvocationList();
foreach (Delegate delegateObject in delegateList)
{
    var del = delegateObject as GetEmployeeNameDelegate;
    employeeNames += del(1);
}
Assert.IsTrue("FullTimeEmployee-1PartTimeEmployee-1" == employeeNames); 

3.3.3. Delegate for Asynchronous Method Execution: 

Suppose you have a long running method which you are currently executing synchronously. Now you decide for better performance you will execute this method asynchronously. How can you do this with very simple way? In this scenario delegate is your friend. Delegate object has a method named BeginInvoke. It will help to execute any synchronous method asynchronously.  

There are few ways to call BeginInvoke() method for asynchronous calling. I show here a very simple way:

[TestMethod]
public void AsyncMethod_Using_Delegate()
{
    Action ac = Synchronous_Method_Will_Call_Asynchronously;
    IAsyncResult asycnResult = ac.BeginInvoke(null, null);
    //your next code block run parally...
    ac.EndInvoke(asycnResult);
}
public  void Synchronous_Method_Will_Call_Asynchronously()
{
    Thread.Sleep(15000);
} 

3.3.4. Delegate Vs Interface: 

Delegate and Interface are two distinct concept of C# but both have common features:

  • Both contain only declaration type.
  • Different method/class can implement them. 
  • Both support run-time polymorphism. 

For those common features in real life, you can find same or similar problem can solve with both Delegate and Interface.

Q. Can you explain it with code example? 

A. Yes certainly. Strategy design pattern is an example. Strategy pattern solved problem like where function output is same but ways of complete the function is different and run-time/dynamically ways might be switch. Strategy pattern is implemented by Interface. Declare an Interface and write 2 or 3 implementation classes of this interface. Run time you should define which implementation you will use to produce desire output. In this implementation you can replace interface with delegate and get same output. Similar like scenario you may get in real life.

Q. When to use Interface When to Delegate? 

A.  There is no clear and straight forward rule for selecting Interface or Delegate. The following are represent some point which may use as guide line. 

Delegate  Interface  
Encapsulate static method.  Grouping related methods. 
A class may need more than one implementation of a method. Need to cast from one class to another. 
Caller have interested only for a particular method. Class needs only implementation of methods.  
Publisher-Subscriber pattern implementation.  

At the end if we summarize delegate features we can pin the following points: 

  • Delegate is type-safe method pointer.
  • Delegate allows us to send code-block from one method to another.
  • Delegate supports run-time polimorphism
  • Delegate can use as a callback method.
  • Delegate can use as a chain i.e. multi-cast delegate.
  • Delegate can create one method (anonymous method) inside another method.
  • Some scenarios delegate can use in replace of Interface. 

3.4. Lambda Expression  

 

 Lambda expression is a special form of anonymous function. After using lambda,  we can create either 

  1. Delegate or  
  2. Expression Tree 

 After creating delegate we can execute code directly. But if we create Expression Tree we need to do one extra step. That is first compiled expression tree, after compilation done it will create delegate and this delegate run code.

Q. Why one extra step is needed for Expression Tree?

A. Expression Tree is not code block rather it is actually data block. Though it is data block so directly execute is not possible. For that reason compilation is needed, after compilation using Compile() method it creates delegate which is executable. 

Q. Can you explain more with code sample?

A.  Please see the following code blocks:

3.4.1. Delegate Creation: 

[TestMethod]
public void Use_Lambda_Create_Delegate()
{
    CalculationDelegate addition = (x, y) => x + y;
    int result = addition(2, 3);
    Assert.IsTrue(result == 5);
} 

 3.4.2. Expression Tree Creation: 

[TestMethod]
public void Use_Lambda_Create_ExpressionTree()
{
    Expression<CalculationDelegate> additionExpressionTree = (x, y) => x + y;
    CalculationDelegate additionDelegate = additionExpressionTree.Compile();
    int result = additionDelegate(3, 2);
    Assert.IsTrue(result == 5);
} 

3.4.3. Lambda Types: 

Usage of Lambda 

 There are 2 types of lambda:  

  1. Expression Lambda
  2. Statement Lambda  

 1. Expression Lambda: Lambda use an operator called lambda operator. It looks => and pronounced "Such that"  

(input parameters) => expression; 

  • Left side of => is called parameters. 
  • Right side of => is called expressions.

Code Example:

Lambda expression with 2 input parameters:

private delegate bool EqualityCheckDelegate(int x, int y);
[TestMethod]
public void Expression_Lamda()
{
    EqualityCheckDelegate delegateObject = (x, y) => x == y;
    bool matched = delegateObject.Invoke(2, 2);
    Assert.IsTrue(matched);
} 

() empty parenthasis is also used if no parameter is defined:

private delegate bool EqualityCheckDelegateNoParam();
[TestMethod]
public void Expression_Lamda_No_param()
{
    EqualityCheckDelegateNoParam delegateObject = () => 2 == 2;
 
    bool matched = delegateObject.Invoke();
    Assert.IsTrue(matched);
}  

 2. Statement Lambda: Statement  lambda is similar to expression lambda but started with curly bracket and it defies its block. If delegate have return type then manually need to return value inside lambda statement similar way we use in method.

(input parameters) => { statement(s); }; 

Example:

[TestMethod]
public void Statement_Lamda()
{
    EqualityCheckDelegate delegateObject = (x, y) =>
    {
        if (x == y)
            return true;
        else
            return false;
    };
    bool matched = delegateObject.Invoke(5, 5);
    Assert.IsTrue(matched);
} 

3.4.4. Async Lambda: 

If we create lambda expression or statement with asynchronous processing we can call that async lambda. It actually a very simple way to create asynchronous delegate. 

For asynchronous processing we need to tools: 

  1. Async modifier
  2. Await statement  

Example:

[TestMethod]
public void Async_Lambda()
{
    Func<Task> task = async () =>
        {
            await Task.Delay(5000);
        };
    //Your another logic code...
    task().Wait();
} 

 I will explain async and await in details in another section of this article. 

3.4.5. Type Inference: 

if you analyze the code, you will see that we do not define parameter type in lambda parameter section.

Q. How compiler knows the parameter type?

A. Based on lambda body, compiler infer parameter types. If you see the linq api 

IEnumerable<Employee> employeeList = GetEmployees();
IEnumerable<Employee> newEmployeeList = employeeList.Where(e => e.Salary > 10000); 

Here input parameter e is inferred by compiler as Employee type object and in lambda body you can use any public member of employee object. One important point should be remember that lambda expression themselves do not have a type. 

3.4.6. Lambda Expression Rules:

lambda expression follows some general rules that we should know:

  • No. of Lambda parameters should be equal to its delegate parameters.                                                      n lambda parameters = n delegate parameters; 
  • Each Lambda parameter must implicitly convertible with  its corresponding delegate parameter. 
  • If lambda return any value then value type must be implicitly convertible with its delegate return type. 

3.4.7. Variable Scope:  

[TestMethod]
public  void Lambda_Variable_Scope()
{
    var salary = new Salary();
    int newSalary = salary.AddAndGetSalary(100);
    Assert.IsTrue(newSalary == 100);
 
    int newSalary2 = salary.IncreaseSalary(100);
    Assert.IsTrue(newSalary2 == 200);
}
private class  Salary
{
    public Func<int,int> IncreaseSalary = null;
    public  int AddAndGetSalary(int addedAmount)
    {
        int salaryAmount = 0;
        salaryAmount += addedAmount;
        IncreaseSalary = (int addedNewAmount) =>
            {
                salaryAmount += addedNewAmount;
                return salaryAmount;
            };
        return salaryAmount;
    }
} 

If you analysis the above code you will find that local variable salaryAmount, its scope define in method AddAndGetSalary method. That means if AddAndGetSalary  method execution complete then local variable salaryAmount will automatically remove from memory by the help of garbage collector. But here inside the lambda statement this local variable is use as its outer variable reference and increase its value.

When I directly called

salary.AddAndGetSalary(100);

it returns 100.  

But after that when i execute 

salary.IncreaseSalary(100);

it returns 200. Means it stored previous 100. That is the interesting part. Though destroyed salaryAmount variable scope, still the variable is in memory.

Q. How it is possible?

A. The reason is delegate still referencing this variable.

Q. I see it previously in JavaScript. Is it that Closures?  

A. Yes. The concept of this is called Closures. Now I am talking about C# Closures. Actually Closures is language independent concept. In a short we can define Closures: inner scope/method takes reference of its outer scope/method local variable. Lambda use closures to manage that. Closures concept is very important concept which should be clear to all developers specially who are working with lambda expression. 

3.5. Async-Await Pair 

Async and awair are actually 2 different code markers. What they mark? They mark the code position where the code need to restart after task is completed. Asyc use with a method like a modifier which indicates inside the method body, await statement is there, code statement may need to restart after task completion.   

Microsoft introduced Task Based Asynchronous Pattern ( TAP ) from .NET version 4. This TAP is used based on 2 types: 

  1. Task
  2. Task<TResult> 

Task object represent executing code that will provide result in future. Task object has some features:

  • Task Scheduling
  • Establish relationship between parent and child task.
  • Support cooperative cancellation
  • Without external wait handles, wait can be signaled.
  • Attach task continuously. 

Microsoft recommended for current development,  TAP is the best approach for asynchronous programming.  

C# introduced async and await pair c# version 5 and it is used with TAP.

[TestMethod]
public void Async_Await()
{
    var list = new List<Task>();
    for (int i = 0; i < 3; i++)
    {
        Task t = WriteFileAsync(i);
        list.Add(t);
    }
    Task.WaitAll(list.ToArray());
}
private async Task WriteFileAsync(int x)
{
    await Task.Run(new Action(WriteFile));
}
private readonly object _locker = new object();
private void WriteFile()
{
    Thread.Sleep(4000);
    lock (_locker)
    {
        File.AppendAllLines("D:\\ABC.log", new[] { DateTime.Now.ToString("hh:mm:ss:t") });
    }
} 

For better responsive application development, async based asynchronous processing is very useful. Some useful cases: 

  • File Input/Output
  • Download data from Web
  • Network streaming
  • Responsive UI (without blocking main ui thread)  

Before use async-await pair for asynchronous programming you should know the following:

  • As a strong convention you use async as post prefix for method where use async modifier.
  • You should know that compiler works and manage everything related to asynchronous processing by state machine workflow.
  • In async method, at lease one await should be exists otherwise method will work synchronously. 

3.5.1. Exception Handling: 

[TestMethod]
public  void ExceptionHandling_With_Async_Wrong_Way()
{ 
    var tId = Thread.CurrentThread.ManagedThreadId;
    bool exceptionCatched = false;
    Task t = null;
    try
    {
        t = LongProcessAsync();
    }
    catch(Exception ex)
    {
        exceptionCatched = true;
    }
    t.Wait();
    Assert.IsTrue(exceptionCatched);
} 
private  async Task LongProcessAsync()
{
    await Task.Run(new Action(LongProcess));
}
private void LongProcess()
{
    var tId = Thread.CurrentThread.ManagedThreadId;
    throw new InvalidOperationException("operaton is invalid. Please verify your code.");
    Thread.Sleep(5000);
}  

if you see and run above code block, the result will be test case failure. Why it will failed? Because we did not set try block in a proper way. I intentionally throwing InvalidOperationException from LongProcess() method but try block do not catch this exception. Reason behind that is inside 2 different thread, the code is running and it is not possible to catch exception which is thrown from another thread without join the threads. (I use here a variable tId by  which we will test 2 are different thread or not.) Task.Wait() method will join the threads so if we set try block for Wait() method then it is possible to catch exception.

[TestMethod]
public void ExceptionHandling_With_Async_Right_Way()
{
    var tId = Thread.CurrentThread.ManagedThreadId;
    bool exceptionCatched = false;
    Task t = LongProcessAsync();
    try
    {
        t.Wait();
    }
    catch (AggregateException ex)
    {
        exceptionCatched = true;
    }
    Assert.IsTrue(exceptionCatched);
}  

Another observation! If you analysis the code you will find that from method LongProcess() throwing InvalidOperationException but in catch block  using AggregateException. The reason behind that when any exception throws from async method first it wraps with AggregateException and then throw it. So if you need actual exception you need to explore AggregateException.InnerException property. 

3.5.2. Cancel Asynchronous ongoing Task: 

Question is how to cancel ongoing/running task? CancellationTokenSource is an object which helps us to cancel ongoing task. 

Q. Can you show me few code sample?

A. Following is the code:    

private CancellationTokenSource _cancelTokenSource;
[TestMethod]
public  void Cancel_OnGoing_Async_Task()
{
    Task t = LongProcessAsync2();
    CancelTask();
    if (!_cancelTokenSource.IsCancellationRequested)
    {
        t.Wait();
    }
}
private void CancelTask()
{
    _cancelTokenSource.Cancel();
}
private async Task LongProcessAsync2()
{
    _cancelTokenSource = new CancellationTokenSource();
    await Task.Run(new Action(LongProcess2));
}
private void LongProcess2()
{
    Thread.Sleep(15000);
}  

Previously it was always a challenge to cancel running code. Using CancellationTokentSource object any time we can cancel ongoing task without facing much challenge. Thanks to CancellationTokentSource for its nice support!  

3.6. Generics  

 

public class MyFirstGenericClass<T> where T : struct
{
    public T GetDouble(T value)
    {
        var input = (Convert.ChangeType(value, typeof(int)));
        int newA = int.Parse(input.ToString());
        newA *= 2;
        return (T)(Convert.ChangeType(newA, typeof(T)));
    }
}   

C# introduced Generics from its version 2 and latter its feature is enhanced. Generic introduce concept of type parameter. Based on this type parameter it is possible to create new class or method that can work with various type without explicitly declare those types.

You can apply generic with following items: 

  • Class 
  • Method 
  • Interface 
  • Delegate 
  • Event  

Q. What are the benefits we can get using generics? 

A. The following benefit we can get using generics:

  • Clean code.  
  • Maximum code reuse. 
  • Type safety. 
  • Extract generic type information at run time using reflection.
  • Produce higher quality code.  

Q. Need to know how generic type is constructed? 

A. During compilation time, when generic types or generic methods are converted to MSIL (Microsoft Intermediate Language) that time it contains meta data where generic type parameters are defined. Actual construction process of generics type is based on parameter constraint either

  • Value type or
  • Reference type.

Value type and Reference type generic type construction are different.  

3.6.1. Generic Type Parameter Constraint: 

We can apply constraints when create generic type. Creating object of this generic type, client code must respect the constraints otherwise it will produce compile time error. Following table will show few constraints: 

Constraint  Description 
 T: class All reference type i.e. class, interface, delegate 
 T: new()  Type argument must have a parameter less constructor. 
T: struct   Any kind of value type i.e. int, long etc  
 

 3.6.2. Multiple Generic Type Parameter: 

 No problem for defining multiple type parameters for a generic type.  

public class MultiParametersGenericClass<T1, T2>
{
    public void Process(T1 value1, T2 value2)
    {
        //code block...
    }
} 

3.6.3. Generic Method:

[TestMethod]
public  void Generic_Method_Test()
{
    int returnValue = GenericMethod<int>(5);
    Assert.IsTrue(returnValue == 10);
}
public  T GenericMethod<T>(T inputValue) where T:struct 
{
    var r =Convert.ToInt32(inputValue) * 2;
    return (T)Convert.ChangeType(r, typeof(T));
}  

You can declare and use generic method same way as you declare and use generic class. When you call the generic method that time you need to pass your type arguments.  

3.6.4. Generic Collection: 

There are many generic collections are defined for you in .NET. If you want you can write your own generic collection too. The following will show some generic collection list which is in .NET framework.

  • IList<T>
  • List<T>
  • ICollection<T>
  • Dictionary<K, T> 
  • IEnumerable<T> 
  • Stack<T>
  • Queue<T> 

3.6.5. Generic Delegate: 

We can use generics type parameters for delegate. In that case methods that will bind with this delegate must match. 

private delegate T MyFirstGenericDelegagte<T>(T item) where T : struct; 
[TestMethod]
public  void Generic_Delegate_Test()
{
    MyFirstGenericDelegagte<int> delObject = GetDouble;
    int returnValue = delObject(5);
    Assert.IsTrue(returnValue == 10);
}
private int GetDouble(int x)
{
    return x*2;
} 

3.6.6. Generic Repository Code Sample: 

The following I show generic repository pattern implementation using generics: 

public abstract class EntityBase
{
    public long Id { get; set; }
    protected EntityBase()
    {
    }
    public abstract void Validate();
}
public class Customer : EntityBase
{
    public string CustomerName { get; set; }
    public override void Validate()
    {
 
    }
}
public interface IRepository<T> where T : EntityBase
{
    T GetById(long id);
    void SaveOrUpdate(T entity);
}
public abstract class RepositoryBase<T> : IRepository<T> where T : EntityBase
{
    protected readonly string _conntectionString;
    protected RepositoryBase()
    {
        _conntectionString = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
    }
    protected RepositoryBase(string connectionString)
    {
        _conntectionString = connectionString;
    }
    public abstract T GetById(long id);
    public abstract void SaveOrUpdate(T entity);
}
internal class CustomerRepository : RepositoryBase<Customer>
{
    public override Customer GetById(long id)
    {
        var prmId = new SqlParameter("@Id", id);
        //return base.GetByIdInternal(SP_CUSTOMER_GET_BY_ID, prmId);
        return new Customer();
    }
    public override void SaveOrUpdate(Customer entity)
    {
        var prmId = new SqlParameter("@Id", entity.Id);
        var prmCustomerName = new SqlParameter("@CustomerName", entity.CustomerName);
        var paramList = new List<SqlParameter> {prmId, prmCustomerName};
        //base.SaveOrUpdateInternal(SP_CUSTOMER_SAVE_UPDATE, paramList);
    }
}   

4. Conclusion 

 

It is very difficult to choose set of features from many well defined features from C# and claims that these features are convened me . It is obvious that not all people agree with me only for those few features I can claim C# is a sexy language. But again I repeat it is my personal preference and some one might be agree and dis-agree. Every one should equal rights for this.  

Many people may think that word sexy may not feet with programming language. But I think the word sexy can use any things that are more attractive, high appealing, more interesting. That's why I use this word. Every one has right to agree or disagree with me. 

Source Code 

I attached a unit test project where Visual Studio 2012 and .NET framework 4.5 version is used.

References 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

S. M. Ahasan Habib
Software Developer (Senior) The Jaxara IT Ltd.
Bangladesh Bangladesh
Mostly I work with MS technologies (ASP.NET MVC, WPF, C#, SQL Server, SSRS, SharePoint, Entity Framework, MSTest, Enterprise Library, MEF, WCF, WebAPI, MS Excel, IIS).
Non MS technologies which I love and use (Resharper, NHiberNet, JQuery, AngularJS, KnockoutJS, NodeJS, Python, MSpec, RihnoMock, Crystal Report, Subversion, Crome)

Comments and Discussions

 
QuestionGreat tips but not ideal code examples PinmemberMember 1085901822-Oct-14 23:13 
QuestionMy Vote Pinmemberscud.corsair21-Jul-14 21:29 
GeneralMy vote of 5 Pinprofessionalridoy17-Jul-14 11:31 
GeneralMy vote of 5 PinmemberAlexandra Christina16-Jul-14 12:38 
QuestionExcellent Article PinmemberKP Lee31-Jan-14 21:27 
AnswerRe: Excellent Article PinmemberS. M. Ahasan Habib2-Feb-14 1:36 
QuestionMy vote of 5 PinmemberMember 1052531728-Jan-14 9:44 
AnswerRe: My vote of 5 PinmemberS. M. Ahasan Habib28-Jan-14 16:44 
QuestionNice one PinmemberLotusShiv21-Jan-14 8:03 
AnswerRe: Nice one PinprofessionalS. M. Ahasan Habib21-Jan-14 15:27 
Questiontypo like awair/Asyc and more... PinmemberHuisheng Chen21-Jan-14 0:41 
AnswerRe: typo like awair/Asyc and more... PinprofessionalS. M. Ahasan Habib21-Jan-14 1:13 
QuestionNice Job PinmemberMember 986660820-Jan-14 14:13 
AnswerRe: Nice Job PinprofessionalS. M. Ahasan Habib20-Jan-14 15:33 
GeneralVote 5 Pinmemberyuzaihuan20-Jan-14 2:45 
GeneralRe: Vote 5 PinprofessionalS. M. Ahasan Habib20-Jan-14 4:34 
GeneralVery Nice PinmvpAbhishek Sur19-Jan-14 13:48 
GeneralRe: Very Nice PinprofessionalS. M. Ahasan Habib19-Jan-14 15:55 
QuestionAngularJS PinmemberAhsan Kabir19-Jan-14 8:52 
AnswerRe: AngularJS PinprofessionalS. M. Ahasan Habib19-Jan-14 15:56 
Questionmy vote 10 PinmemberRenuka Ruke15-Jan-14 21:24 
AnswerRe: my vote 10 PinprofessionalS. M. Ahasan Habib15-Jan-14 21:54 
GeneralMy vote of 5 Pinmember Gun Gun Febrianza15-Jan-14 18:32 
GeneralRe: My vote of 5 PinprofessionalS. M. Ahasan Habib15-Jan-14 18:41 
GeneralMy vote of 5 PinmemberProgramm3r13-Jan-14 20:33 
GeneralRe: My vote of 5 PinprofessionalS. M. Ahasan Habib14-Jan-14 5:05 
GeneralMy vote of 5 PinprofessionalRenju Vinod12-Jan-14 18:00 
GeneralRe: My vote of 5 PinprofessionalS. M. Ahasan Habib12-Jan-14 22:43 
QuestionReally Sexy [modified] PinmemberRahul VB11-Jan-14 8:05 
AnswerRe: Really Sexy PinprofessionalS. M. Ahasan Habib11-Jan-14 8:08 
GeneralMy Vote of 5 PinprofessionalRaviRanjankr9-Jan-14 1:57 
GeneralRe: My Vote of 5 PinprofessionalS. M. Ahasan Habib9-Jan-14 4:11 
GeneralMy vote of 5 PinmemberUday P.Singh6-Jan-14 21:12 
GeneralRe: My vote of 5 PinprofessionalS. M. Ahasan Habib6-Jan-14 21:56 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun5-Jan-14 23:19 
GeneralRe: My vote of 5 PinprofessionalS. M. Ahasan Habib5-Jan-14 23:48 
GeneralMy vote of 4 PinmemberDaniel de Q Miranda4-Jan-14 5:07 
GeneralRe: My vote of 4 PinprofessionalS. M. Ahasan Habib4-Jan-14 15:56 
QuestionThanks PinmemberAn2dSingh30-Dec-13 23:30 
AnswerRe: Thanks PinprofessionalS. M. Ahasan Habib30-Dec-13 23:37 
GeneralMy vote of 5 PinmemberValery Possoz27-Dec-13 3:09 
GeneralRe: My vote of 5 PinprofessionalS. M. Ahasan Habib27-Dec-13 3:16 
GeneralGot my 5 PinmemberAndre Pieterse26-Dec-13 23:21 
GeneralRe: Got my 5 PinprofessionalS. M. Ahasan Habib27-Dec-13 1:37 
GeneralMy vote of 5 PinmemberslhCoding24-Dec-13 4:39 
GeneralRe: My vote of 5 PinprofessionalS. M. Ahasan Habib24-Dec-13 6:46 
QuestionTerminology PinmvpRichard MacCutchan23-Dec-13 2:28 
AnswerRe: Terminology PinprofessionalS. M. Ahasan Habib23-Dec-13 3:29 
GeneralRe: Terminology PinmvpRichard MacCutchan23-Dec-13 3:54 
Yes, you say: C# has many interesting features that seems so hot and sexy. For that reason we can say it is a sexy language too..
And gives the impression that you are not to be taken seriously. If you expect to be treated as a professional then you need to write like one.
Veni, vidi, abiit domum

GeneralRe: Terminology PinprofessionalS. M. Ahasan Habib23-Dec-13 4:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141216.1 | Last Updated 18 Dec 2013
Article Copyright 2013 by S. M. Ahasan Habib
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid