Sunday, October 27, 2013

All about Virtual,Override and New in C#


I have seen that lots of people get confused with Virtual, Override and new keyword in C#. So I thought it will be a good idea to write a blog post about it. In this blog post we will learn what is virtual, override and new keyword in C# and what’s difference between override and new in C#.

Virtual and Override in C#:


Virtual keyword allows class member to override in derived class. Let’s take simple example. I have class A which contains Print Method method as virtual method and I have another class B which is derived from class A which overrides Print method. Following is a code for that.

public class A
{
    public virtual void Print()
    {
        System.Console.WriteLine("Virtual Print method from a");
    }
}

public class B:A
{
    public override void Print()
    {
        System.Console.WriteLine("Override Print method from b");
    }
}
Now If I create a object of class A like following and run the code Print method run as normal method. Following is code for for that.
class Program
   {
       static void Main(string[] args)
       {
          A a=new A();
          a.Print();
       }
   }

Once you run this it will have following output.

VirutalAsNormalMethodinCsharp

But when you create a object of class B like following it will completely override the functionality of class A. That is called method Method Overriding. Following is a code for that.

class Program
{
    static void Main(string[] args)
    {
       B b=new B();
       b.Print();
    }
}

Now, if you run this code it will completely override the code and following will be output as expected.

OverrideMethodinCsharp

How to call base class method with override:


In some scenario, we need base class functionality also while overriding the method of that class. C# provides that functionality with ‘base’ keyword. For that I have changed code of class B like following.
public class B:A
{
public override void Print()
{
    System.Console.WriteLine("Override Print method from b");
    base.Print();
}
}

class Program
{
    static void Main(string[] args)
    {
       B b=new B();
       b.Print();
    }
}

Now if you run the code you will see output of both method as expected.

BaseKeywordwithoverridecsharp

What is difference between new and override in C#:


After looking into above example some people will argue that this functionality will be achieved by new keyword also. This is call Method Hiding where with new keyword you can hide functionality of base class.  But wait there is a difference. Both are slightly different let’s take some simple example to show difference following is a code for that.
namespace Oops
{
    class Program
    {
        static void Main(string[] args)
        {
           A a=new B();
           B b=new B();

           a.Print();
           b.Print();
        }
    }

    public class A
    {
        public virtual void Print()
        {
            System.Console.WriteLine("Virtual Print method from a");
        }
    }

    public class B:A
    {
        public override void Print()
        {
            System.Console.WriteLine("Override Print method from b");
        }
    }
}

In this code, same A class Print method is override by B class Print method and I have created two object of class B. One with reference to base class A and another B itself. Now let’s run this example and following is a output.

OverridewithInheritancedifferencebetweenoverideandnew

Here you see both time it will override class A’s Print Method. Now let’s change above code with new keyword like following.
namespace Oops
{
    class Program
    {
        static void Main(string[] args)
        {
           A a=new B();
           B b=new B();

           a.Print();
           b.Print();
        }
    }

    public class A
    {
        public virtual void Print()
        {
            System.Console.WriteLine("Virtual Print method from a");
        }
    }

    public class B:A
    {
        public new void Print()
        {
            System.Console.WriteLine("Override Print method from b");
        }
    }
}

Now you run this code. Following is output.

OverridewithInheritanceDifferenceBetweenoverrideandnew

If you see both output carefully then you will notice a difference. With override keyword it will override Print method in both scenarios. While with new keyword it will only hide print method and both method exist as separate method so if you create a class A object with B then it will class A’s Print method without hiding it and If you create class B object with B then it will hide the base class method and print from class B’s method. So that was the difference.

That’s it. Hope you like it. Stay tuned for more..
Share:
Tuesday, October 22, 2013

Linq- AddRange Method in C#

In this post I’m going to explain you about Linq AddRange method. This method is quite useful when you want to add multiple elements to a end of list. Following is a method signature for this.
public void AddRange(
    IEnumerable<T> collection
)
To Understand let’s take simple example like following.

using System.Collections.Generic;
using System;
namespace Linq
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names=new List<string> {"Jalpesh"};
            string[] newnames=new string[]{"Vishal","Tushar","Vikas","Himanshu"};
            foreach (var newname in newnames)
            {
                names.Add(newname);
            }
            foreach (var n in names)
            {
                Console.WriteLine(n);
            }
        }
    }
}

Here in the above code I am adding content of array to a already created list via foreach loop. You can use AddRange method instead of for loop like following.It will same output as above.
using System;
using System.Collections.Generic;

namespace Linq
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names=new List<string> {"Jalpesh"};
            string[] newnames=new string[]{"Vishal","Tushar","Vikas","Himanshu"};
            names.AddRange(newnames);
            foreach (var n in names)
            {
                Console.WriteLine(n);
            }
        }
    }
}

Now when you run that example output is like following.

AddRangeLinqCsharp

Add Range in more complex scenario:

You can also use add range to more complex scenarios also like following.You can use other operator with add range as following.
using System;
using System.Collections.Generic;
using System.Linq;

namespace Linq
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> names=new List<string> {"Jalpesh"};
            string[] newnames=new string[]{"Vishal","Tushar","Vikas","Himanshu"};
            names.AddRange(newnames.Where(nn=>nn.StartsWith("Vi")));
            foreach (var n in names)
            {
                Console.WriteLine(n);
            }
        }
    }
}

Here in the above code I have created array with string and filter it with where operator while adding it to an existing list. Following is output as expected.

AddRangeLinqCsharpAdvanceScneario

That’s it. Hope you like it. Stay tuned for more..
Share:
Monday, October 21, 2013

throw new exception- C#

This post will be in response to my older post about throw exception best practice. where one of user asked that I should include throw new exception.So I thought it will be good idea to write a whole blog post for it. This blog post explains what's wrong with throw new exception.

What’s wrong with throw new exception:


Throw new exception is even worse, It will create a new exception and will erase all the earlier exception data. So it will erase stack trace also.Please go through following code. It’s same earlier post the only difference is throw new exception.

using System;

namespace Oops
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                DevideByZero(10);
            }
            catch (Exception exception)
            {
                throw new Exception
                (string.Format(
                    "Brand new Exception-Old Message:{0}",
                     exception.Message));
            }
        }

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

Now once you run this example. You will get following output as expected.

Throw new exception C#

Hope you like it. Stay tuned for more..
Share:
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, October 17, 2013

Cool Resharper Features Part-2

This post will be part-2 of first post Cool Resharper Features Part-1. In this post we are also going to learn some other cool features that resharper is providing. Following are some of features that resharper is providing.

1) Move to another file to match type name:

This feature makes you very productive when you need to create a new class. Suppose with normal visual studio you need to create a new class with new file then you need to do via file menu –> Add new item and then select class. Here you can do very easily without having all this stuff. Just write you class after class in any .cs file like below.


Movetoanother filetomatchtypename

In above image you can see that I have created a employee class. Now when you put a cursor on employee class name resharper will open a popup or you can press ALT + R and it will open a popup like this.

Movetoanother filetomatchtypename2

And once you click on this it will create a file name with Employee.cs and move class code to that file.

Movetoanother filetomatchtypename3

2) Extract Interface(Refactor Menu):

This features comes quite handy when you are working with interfaces. Here you can have interface extracted from class. Let’s take same example of employee class. Now I am pressing Ctrl-Shift-R to open refactor menu.

ExtractInterface

Now once you click on this.It will open a popup with some options like following.

ExtractInterface2

Here it will ask for Interface name, Where we want to move and what member we need to create once you click. There also button given to select all public or dependent member.Once you select print click on next it will extract a interface in new file like following.

ExtractInterface3

Here for demo purpose I have not selected move to another file so that I can show both class and interface implementation but you could create a new file also with the same class.

3) Go To Implementation:

If we are using interfaces and we want to find a interface is implemented in how many class or we want to find the class which implement this interface this feature becomes quite handy. There are some other use of this feature also here it’s very productive.

For example, I want to find which class has implementation of IEmployee interface as above example then I need right click and select “Go To Implementation” or I can directly do with shortcut Ctrl + Shift + Alt + B.
Once you right click a menu appears like following.

GoToImplementation

Once you click on this. It will navigate to Employee class which implements this interface.

GoToImplementation2

That’s it. Hope you like I will post some other features of resharper in my future posts.Stay tuned for more.. Smile
Share:
Saturday, October 12, 2013

Cool Resharper features part -1

I have been using Jetbrain’s resharper since last four years and it’s been my default Visual Studio plugin for visual studio. After this much of experience of resharper I must say if resharper is not there I would not have that much productive with visual studio. Working with it is a pleasure. I this post I am going to explain some cool resharper features.

Resharper uses two keyboard schemes Visual Studio or Intelli IDEA scheme. In this post I am going to use Intelli IDEA scheme. The only difference between two key map scheme is keyboard shortcut. Some Visual Studio short cut will be override by Resharper.

1) ALT + Enter:

It’s a magic key for resharper you can have any feature with ALT+ Enter whether its refactoring, code completion or anything. You can use ALT + Enter for anything. For example you have some name space un used and you want to remove namespace just press ALT + Enter and it will have popup like following.

ALTEnter

Once you click on this and it will remove unused namespace. Same way I have a class called Student Repository and I have one private variable which I want to initialize with constructor then I just need to press ALT+ Enter on that line and it will open a popup like following.

ALTEnter2


Once you click on Initialize field from constructor(s) parameter and it will create a code like following.

ALTEnter3

2) GO to Type:

This is an awesome feature of navigation. You can have either from resharper menu->Navigation GO to Type or you can have Ctrl + N short cut for intelli IDEA scheme. Once you click it will open a popup and whatever you type it find matching list of type and once you click on type you will be there.

GoToType

3) Find Usage:

This is also an awesome feature for finding usage of particular type or variable. You can right click any type and click on find usage or you have short cut key ALT + f7.

FindUsage

Once you click on Find Usage it will list all load all the find result and you click on any one and you can go to there file.

FindUsage2

3) Smart symbol completion:

When you use Ctrl + Space it will suggest you the option to complete symbol and save lots of keyboard stroke.

SmartCodeCompletion

4) Smart code selection:

With Ctrl + W you can select current type and again you press Ctrl + W it will select line and again you press Ctrl + W you can select method.

SmartCodeSelection
That’s it. This are some feature that I am using I will have more feature list in forth coming posts. Hope you like it. Stay tuned for more.Smile
Share:
Wednesday, October 9, 2013

Database diagram support objects cannot be installed because this database does not have a valid owner- SQL server error solution

Before some days, I have copied one database from the one of server and restored it on my machine. The server was not having ‘sa’ user login and I was having the ‘sa’ user in my local machine. The database was restored perfectly with no problem but when I tried to create a database diagram I got following error.
Database diagram support objects cannot be installed because this database does not have a valid owner. To continue, first use the Files page of the Database Properties dialog box or the ALTER AUTHORIZATION statement to set the database owner to a valid login, then add the database diagram support objects.
After digging into that I found that the database does not have any valid owner and that’s why its generating errors. To resolve this error following is a step to change or add owner of database.

Step-1:


Right click on your database and click properties it will open a dialog like following. Goto-> Fiile Tab.

DatabasePropertiesDatabaseOwner

Step-2:


Click on .. button it will open a dialog box like following.

BrowseDatabasePropertiesDatabaseOwner

Step-3:


Click on browse button. It will open a list of user available for SQL Server.You need to select user whom you want to make database owner. In my case I want to make ‘sa’ user database owner so that I have selected like following.

SaDatabaseOwner

After selecting user you need to close all dialog via pressing ‘OK’ buttons. That’s it your database is now having proper owner and error for database diagram is gone now.  Hope you like it. Stay tune for more..
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