Showing posts with label C#.NET. Show all posts
Showing posts with label C#.NET. Show all posts
Friday, October 18, 2013

throw vs. throw(ex) best practice and difference- c#

Recently I was looking into someone’s code found that they are using the throw(ex) to log exception so I told that person that why you are not using only throw he said there is no difference.. Wait this is not true there is a difference. So, this post is all about throw Vs. throw(ex) best practice and what is difference.

We all know that C# provides facility to handle exception with try and catch block and some times we use throw statement in catch block to throw the exception to log the exception. Here there two options either you could use throw(ex) or simple throw just like following.

try
{

}
catch (Exception ex)
{
    throw;
}

And
try
{

}
catch (Exception ex)
{
    throw(ex);
}

So which one is good and best practice let’s study that.

Similarities:

Let’s first see what is similar in both.
  1. Both are used to throw exception in catch block to log message
  2. Both contains same message of exception

Difference:

Now let’s see what is difference.
  1. throw is used to throw current exception while throw(ex) mostly used to create a wrapper of exception.
  2. throw(ex) will reset your stack trace so error will appear from the line where throw(ex) written while throw does not reset stack trace and you will get information about original exception.
  3. In MSIL code when you use throw(ex) it will generate code as throw and if you use throw it will create rethrow.
Let’s understand by example. Following is example where you use throw.

using System;

namespace Oops
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                DevideByZero(10);
            }
            catch (Exception exception)
            {
                throw;
            }
        }

        public  static void DevideByZero(int i)
        {
           int j = 0;
           int k = i/j;
           Console.WriteLine(k);
          
        }
    }
}

Here in the above code I have created function DevideByZero where it will create a problem as it try to devide a integer by zero. and in try catch block I am use throw to again throw exception. Now let’s run this application.

throw vs throws(ex) diffrence

Now I have just replace throw with throw(exception) and see it will have following output.

throw vs throw(ex)

So you can see in first image we have got full stack trace information where the actual exception called at line 22 and again rethrow at line 15 While in the another screenshot you can see there is only information about line 15. It does not show full stack trace.So when you use throw(ex) it will reset stack trace.

So it’s always best practice to use throw instead of throw(ex). That’s it. Hope you like it..Stay tuned for more Smile
Share:
Thursday, June 27, 2013

Deferred vs Immediate execution in Linq

In this post, We are going to learn about Deferred vs Immediate execution in Linq.  There an interesting variations how Linq operators executes and in this post we are going to learn both Deferred execution and immediate execution.

What is Deferred Execution?


In the Deferred execution query will be executed and evaluated at the time of query variables usage. Let’s take an example to understand Deferred Execution better.
Share:
Tuesday, June 25, 2013

Static vs Singleton in C# (Difference between Singleton and Static)

Recently I have came across a question what is the difference between Static and Singleton classes. So I thought it will be a good idea to share blog post about it.

Difference between Static and Singleton classes:

  1. A singleton classes allowed to create a only single instance or particular class. That instance can be treated as normal object. You can pass that object to a method as parameter or you can call the class method with that Singleton object. While static class can have only static methods and you can not pass static class as parameter.
  2. We can implement the interfaces with the Singleton class while we can not implement the interfaces with static classes.
  3. We can clone the object of Singleton classes we can not clone the object of static classes.
  4. Singleton objects stored on heap while static class stored in stack.
Share:
Thursday, May 23, 2013

How to sort a data table in C# with LINQ

One of friend today ask how we can sort data table based on particular column? So I thought it’s a good idea to write a blog post about it. In this blog post we learn how we can learn how we can sort database with LINQ queries without writing much more long code. So let’s write a code for that.

using System;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dataTable = CreateDataTalble();
            AddRowToDataTable(dataTable);
            Console.WriteLine("Before sorting");
            PrintDatable(dataTable);
            var Rows = (from row in dataTable.AsEnumerable()
                        orderby row["FirstName"] descending
                        select row);
            dataTable = Rows.AsDataView().ToTable();
            Console.WriteLine("==============================");
            Console.WriteLine("After sorting");
            PrintDatable(dataTable);
        }

        public static DataTable CreateDataTalble()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("FirstName", typeof(string));
            dt.Columns.Add("LastName", typeof(string));
            return dt;
        }
        public static void AddRowToDataTable(DataTable dt)
        {
            dt.Rows.Add("Jalpesh", "Vadgama");
            dt.Rows.Add("Vishal", "Vadgama");
            dt.Rows.Add("Teerth", "Vadgama");
            dt.Rows.Add("Pravin", "Vadgama");
        }

        public static void PrintDatable(DataTable dt)
        {
            foreach (DataRow row in dt.Rows)
            {
                Console.WriteLine(string.Format("{0} {1}",
                    row[0], row[1]));
            }
        }
    }
}

Share:
Wednesday, May 22, 2013

Replace line breaks in C#

In recent days I was working on a project want to replace \r\n to a new character but it was giving very strange behaviour. It was not replacing proper. Let’s create that scenario. I have written following code.
using System;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string sample = @"This is string for replacing new
                                 line \r\n This may not work";
            Response.Write(sample.Replace(@"\r\n",@"<br />"));
        }
    }
}

If you see the above code looks like it should work fine. But when you run this in browser in some environment it working fine and in some environment it was not working fine. Just like below.

Share:
Wednesday, April 10, 2013

Why sometimes it’s not a good idea to use session variables in class library project.

As we all know web pages are stateless pages and we need to use session variables in web application to maintain some session over page. Some time we divide our application into multiple layers for example business logic layer,database layer etc. This all layers will be a class library projects.

So when you have your applications divided into the multiple layers at that time you might need to use session variables in the class library projects. For that we are adding System.Web namespace as a reference to a class library project and then we can use session with HttpContext object. That’s works fine if your layers are going to be used in web application projects. But for example if you have service oriented architecture and your services also access your class libraries via non standard protocol i.e. WCF Service hosted on TCP/IP bindings. At that time sessions will not work.

Instead of that you should always use the parameters in method and avoid direct use of session variables. That parameters will passed either from the web application or from the services which is calling the class libraries.

Hope you liked it. Stay tuned for more..
Share:
Thursday, February 14, 2013

Default keyword in c#

In this post, I am going to explain about default keyword in c#.

Introduction:

As per MSDN default keyword in C# used to assign the default value of the type. In some situation its comes very handy where we don’t want to create object and directly assign the default value of it.

The basic syntax of default is default(T) where t is any reference type of value type and If T is a value type, whether it will be  a numeric value or struct.

Default Keyword usage:

We can use Default keyword in variety of cases.

Assigning value to nullable Type:


We can use it to assign default value to nullable types like below.
using System;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main() {
            int? i = default(int);
            Console.WriteLine(i);
        }
    }
}

Here output will be.
Share:
Saturday, February 2, 2013

How to create overload methods in WCF service with C#

Before some days I have posted an blog about How to create overloaded web methods in asp.net web service? In this post I am going to explain how we can create overload methods in WCF(Windows Communication Foundation) service with C# language.

So let’s consider same Hello world example which we have used web service overload method. Let’s create two methods HelloWorld one is with name and another is without parameter. For WCF service we have to first create interface following is a code for that.
Share:
Friday, February 1, 2013

SelectMany operator in Linq C#

SelectMany is an important operator in Linq. It takes each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence. You can find out more information about different overload list from the below link.

http://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany.aspx

In this post I am going to explain How it can be really useful when you want to find list related to two entities. Practical example will be like a person can have multiple address and if you want to find list of addresses that are used with person then this SelectMany operator can be really useful.

So for this example First, I have create Address class with Street and Postalvcode property
public class Address
{
    public string Street { get; set; }
    public string PostalCode { get; set; }
}

Share:
Sunday, January 27, 2013

C# null-coalescing operator ??

C# language provides many features and null-coalescing operator(??) is one of them. It’s a great operator to check whether object is null and if it is null then it will provide a default value. I have seen most of the people are not using while it’s a great feature. So I decided to write a blog about this.

You can find more information about null-coalescing operator from the below link.
http://msdn.microsoft.com/en-us/library/ms173224.aspx

Share:

Tip-Convert array to Comma delimited string

I was needed to convert an string array into the comma delimited string and the old way to do that is too with for loop. But I was sure that there should be some ready made function that will do this very easily.

After doing some research I have found string.Join. With the help of this we can easily an array into the comma delimited string.

String.join have two arguments one is separator and other one is either array or enumerable.

Following is a code for that.
namespace ConsoleApplication3
{
    class Program
    {
        static void Main() {
            string[] name = {"Jalpesh", "Vishal", "Tushar", "Gaurang"};
            string commnaDelmietedName = string.Join(",", name);
            System.Console.WriteLine(commnaDelmietedName);
        }
    }
}


Share:
Friday, January 18, 2013

How to get N row from datatable in C#

Problem:


Recently one of my friend was needed only first three rows of data table and so he asked me and I have multiple solutions for that. So thought it would be great idea to share with you guys.

Possible Solutions to problem:


There are two ways to solve this problem.
  1. With normal for loop
  2. With lamda expression and linq

1. With normal for loop:

Following is code from where we can get 3 rows of data table.
Share:
Friday, January 4, 2013

Lazy<T> in C# 4.0

Before C# 4.0 there was no on demand initialization by default. So at the time of declaration we need to create a value or object will be null or we have to create on demand initialization via coding.. But with C# 4.0 we now have lazy class. As per MSDN it support lazy initialization so it means if we use lazy class then it will initialize the object at the time of demand.

It is very useful for UI responsiveness and other scenario's.  Lazy initialization delays certain initialization and  it’s improve the start-up time of a application. In the earlier framework if we need this kind of functionality we have to do it manually via coding but from C# 4.0 onwards it have Lazy<T> class. With the Help of this we can improve the responsiveness of C# application. Following is a simple example.
Share:
Sunday, December 30, 2012

Lock keyword in C#

As we have written earlier we have now multi-core CPU for our computers and laptops and to utilize that we need to use threading in code. Now if we create thread and access same resource at same time then it will create a problem at that time locking become quite essential in any programming language.

Let’s consider a scenario. We are having a small firm of computers and each computer is shared by two employees and they need to use computer for putting their sales data in excel sheet. So they can not work together at same time and one has to work and other has to wait till first one complete the work. Same situation can be occurred in programming in where we are using same resource for multiple thread.

C# provides locking mechanism via lock keyword. It restricts code from being executed by more then one thread at a time. That is the most reliable way of doing multi threading programming.
Share:
Friday, December 21, 2012

Where I can find SQL generated by Linq-To-SQL

Yesterday I have written a blog post about Where I can find SQL Generated by Entity Framework? and same day I got request from one of the our reader Ramesh that how I can find SQL generated by Linq-To-SQL?. I thought its a good idea to write a blog post to share amongst all who need this instead of reply in comments.  In this post I am going to explain how we can get SQL generated by Linq-To-SQL.

For this post I am going to use same table like following. A customer table with two columns CustomerId and CustomerName.

How to get SQL staement generated by Linq-To-SQL
Share:
Tuesday, December 18, 2012

Caller Info Attributes in C# 5.0

In c# 5.0 Microsoft has introduced a Caller information attribute. It’s a new feature that is introduced in C# 5.0 and very useful if you want to log your code activities. With the help of this you can implement the log functionality very easily. It can help any programmer in tracing, debugging and diagnostic of any application.
With the help of Caller Information we can get following information over there.

  1. CallerFilePathAttribute: With help of  this attribute we can get full path of source file that contains caller. This will be file path from which contains caller at compile time.
  2. CallerLineNumberAttribute:  With the help of this attribute we can get line number of source file which the method is called.
  3. CallerMemberNameAttribute: With the help of this attribute we can get the method or property name of the caller.

Let’s write a simple example for that to see how its works. Following is a code for that.
Share:
Sunday, December 16, 2012

Parallel task in C# 4.0

In today’s computing world  is all about Parallel processing. You have multicore CPU where you have different core doing different work parallel or its doing same task parallel. For example I am having 4-core CPU as follows. So the code that I write should take care of this. C# does provide that kind of facility to write code for multi core CPU with task parallel library. We will explore that in this post.

Parrallel Task in C# 


Share:
Saturday, September 8, 2012

Predicate delegate in C#

I am writing few post on different type of delegates and this post also will be part of it. In this post I am going to write about Predicate delegate which is available from C# 2.0. Following is list of post that I have written about delegates.

  1. Delegates in C#.
  2. Multicast delegates in C#.
  3. Func delegate in C#.
  4. Action delegate in C#.

Predicate delegate in C#:

As per MSDN predicate delegate is a pointer to a function that returns true or false and takes generics types as argument. It contains following signature.

Predicate<T> – where T is any generic type and this delegate will always return Boolean value. The most common use of a predicate delegate is to searching items in array or list. So let’s take a simple example. Following is code for that.
Share:
Thursday, September 6, 2012

Action delegates in C#

In last few posts about I have written lots of things about delegates and this post is also part of that series. In this post we are going to learn about Action delegates in C#.  Following is a list of post related to delegates.

  1. Delegates in C#.
  2. Multicast Delegates in C#.
  3. Func Delegates in C#.

Action Delegates in c#:

As per MSDN action delegates used to pass a method as parameter without explicitly declaring custom delegates. Action Delegates are used to encapsulate method that does not have return value. C# 4.0 Action delegates have following different variants like following. It can take up to 16 parameters.

  • Action – It will be no parameter and does not return any value.
  • Action(T)
  • Action(T1,T2)
  • Action(T1,T2,T3)
  • Action(T1,T2,T3,T4)
  • Action(T1,T2,T3,T4,T5)
  • Action(T1,T2,T3,T4,T5,T6)
  • Action(T1,T2,T3,T4,T5,T6,T7)
  • Action(T1,T2,T3,T4,T5,T6,T7,T8)
  • Action(T1,T2,T3,T4,T5,T6,T7,T8,T9)
  • Action(T1,T2,T3,T4,T5,T6,T7,T8,T9,T10)
  • Action(T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11)
  • Action(T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12)
  • Action(T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13)
  • Action(T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14)
  • Action(T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15)
  • Action(T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16)
Share:
Saturday, August 25, 2012

Func Delegate in C#

We already know about delegates in C# and I have previously posted about basics of delegates in C#. Following are posts about basic of delegates I have written.

Delegates in C#
Multicast Delegates in C#

In this post we are going to learn about Func Delegates in C#. As per MSDN following is a definition.

“Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.”

Func can handle multiple arguments. The Func delegates is parameterized type. It takes any valid C# type as parameter and you have can multiple parameters as well you have to specify the return type as last parameters.

Followings are some examples of parameters.
Func<int T,out TResult>
Func<int T,int T, out Tresult>

Now let’s take a string concatenation example for that. I am going to create two func delegate which will going to concate two strings and three string. Following is a code for that.

using System;
using System.Collections.Generic;

namespace FuncExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string, string, string> concatTwo = (x, y) => string.Format("{0} {1}",x,y);
            Func<string, string, string, string> concatThree = (x, y, z) => string.Format("{0} {1} {2}", x, y,z);

            Console.WriteLine(concatTwo("Hello", "Jalpesh"));
            Console.WriteLine(concatThree("Hello","Jalpesh","Vadgama"));
            Console.ReadLine();
        }
    }
}

Share:

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews