Tuesday, 9 April 2013

C# New Modifier: How to hide a base class method in derived class?

C# New Modifier: How to hide a base class method in derived class?

The new modifier specifies that a method is supposed to hide a base method. It eliminates a warning issued by the compiler. No functionality is changed. But an annoying warning is silenced.

Example of New Modifier

This program introduces two classes, A and B. The B class derives from the A class. Class A has a public method Y, while class B has a public method Y that uses the new keyword to hide the base method Y.

using System;
class A
{
    public void Y()
    {
       Console.WriteLine("A.Y");
    }
}

class B : A
{
    public new void Y()
    {
       // This method HIDES A.Y.
       // It is only called through the B type reference.
       Console.WriteLine("B.Y");
    }
}

class Program
{
    static void Main()
    {
      A ref1 = new A();
      A ref2 = new B();
      B ref3 = new B();
      ref1.Y();
      ref2.Y();
      ref3.Y();
    }
}

Output
A.Y
A.Y
B.Y

Explanation:

In this example, we use the A and B types. With ref1, the base class is used directly. This results in the A.Y method being used. With ref2, the base class is used with a derived class. This results in the A.Y method being used again. For ref2, the A.Y method is used because the override keyword is not used on B.Y. With ref3, the derived class is used directly. The "new" method B.Y is thus used.

Precautions while using Clustered and Non-Clustered Indexes on a Table

Precautions while using Clustered and Non-Clustered Indexes on a Table
 
Without an index SQL Server / Oracle has to scan entire tables to return requested data. It is like the index page in a book. You check for the keyword you want to read about in the index and you jump directly to the page where the content belongs, instead of scanning page by page for the material you want to read.
 
Similarly a table index allows you to locate data without the need to scan the entire table. You create indexes on one or more columns in a table to help SQL Server / Oracle find the data quickly in a query.
 
Types of Index
 
1. Clustered Index
 
A clustered index alters the way that the rows are stored. When you create a clustered index on a column (or a number of columns), SQL Server / Oracle sorts the table’s rows by that column(s). It is like a dictionary, where all words are sorted in alphabetical order in the entire book. Since it alters the physical storage of the table, only one clustered index can be created per table.
 
Oracle automatically creates clustered index on primary key column.
 
A clustered index should be used on a column that will be used for sorting. A clustered index is used to sort the rows on disk, so you can only have one per table.
 
2. Non Clustered Index
 
Non-clustered index, on the other hand, does not alter the way the rows are stored in the table. It creates a completely different object within the table that contains the column(s) selected for indexing and a pointer back to the table’s rows containing the data. It is like an index in the last pages of a book, where keywords are sorted and contain the page number to the material of the book for faster reference.
 
Indexes help in Performance Optimization
 
SQL server sorts the indexes efficiently by using a B-tree, which is a tree data structure that allows SQL Server to keep data sorted, to allow searches, sequential access, insertions and deletions in logarithmic amortized time. This methodology minimizes the number of pages accessed to locate the desired index key, therefore resulting an improved performance.
 
Precaution while using Indexes on Table
 
You will not notice performance issues until you have quite a bit of data in your tables. But as your data increases, you must take care of indexes.
 
1. Index should be used on a column that's going to be used (a lot) to search the table. Most important consideration is how much time your queries are taking. If a query doesn't take much time or isn't used very often, it may not be worth adding indexes. The best option is to set your clustered index on the most used unique column, usually the primary key.
 
You should always have a well selected clustered index in your tables, unless a very compelling reason.
 
2. Indexes should not be used for columns or tables that are often updated. Clustered indexes makes SQL Server / Oracle order the rows on disk according to the index order. This implies that if you access data in the order of a clustered index, then the data will be present on disk in the correct order. However if the column(s) that have a clustered index is frequently changed, then the row(s) will move around on disk, causing overhead - which generally is not a good idea.
 
This side effect of indexes is related to the cost of INSERT, UPDATE, MERGE and DELETE statements. Such statements can take longer to execute in the presence of indexes since they alter the data on the table resulting the update of the indexes too. Imagine the situation of an INSERT statement that has to add rows to a table with a clustered index. Table rows may need to be repositioned since clustered index needs to order the data pages themselves thus creating more overhead. So, it is crucial to take into account the overhead of INSERT, UPDATE and DELETE statements before designing your indexing strategy. Although there is an overhead in the above statements, you have to take into account that many times an UPDATE or DELETE statement will have to execute in a subset of data, defined by a WHERE clause, where indexing may outweigh the additional cost of index updates since SQL server has to find the data before updating them.
 
3. Having many indexes is not good either. They cost to maintain. So start out with the obvious ones, and then profile to see which ones you miss and would benefit from. You do not need them from start, they can be added later on.
 
4. Big column datatypes can be used when indexing, but it is better to have small columns indexed than large. Also it is common to create indexes on groups of columns.
 
5. There are also storage considerations. When inserting rows into a table with no clustered index, the rows are stored back to back on the page and updating a row may result in the row being moved to the end of table, leaving empty space and fragmenting the table and indexes.
 
Scan and Seek
 
A table without a clustered-index is called a “heap table”. A heap table has no sorted data thus SQL server has to scan the entire table in order to locate the data in a process called a “scan”.
 
In the case of a clustered index the data are sorted on the key values (columns) of the index. SQL server is now able to locate the data by navigating down from the root node, to the branch and finally to the leaf nodes of the B-tree structure of the index, in a process called a “seek”. The later approach is much faster when you want to filter or sort the data you want to retrieve.
 
Difference between Clustered and Non Clustered Index
 
1. A clustered index actually describes the order in which records are physically stored on the disk, hence the reason you can only have one. A Non-Clustered Index defines a logical order that does not match the physical order on disk.
 
2. There can be only one clustered index on a table while there can be up to 249 non clustered indexes on a table.
 
3. Faster to read than non clustered as data is physically stored in clustered index.

Monday, 8 April 2013

Main Features of Windows Workflow Foundation 4.0

Main Features of Windows Workflow Foundation 4.0
 
In this article on WF 4.0, I will describe main features of Workflow Foundation 4.0. Some of the features of WF are new and some are enhanced. Various features of WF 4.0 (Workflow Foundation) are new Activity Designer, Custom Activity, Bookmarks, WorkflowDataContext, Extension, Persistence, WCF Integration, PropertyValueEditor, PersistenceParticipant, Type Converters and Validators. Lets discuss above Workflow Foundation features in detail.
 
1. Activity Designer
 
One of the major changes in Windows Workflow Foundation 4.0 is the Activity Designer. The new Activity Designer is based on WPF which gives lot of flexibility to the developer.  Creation of a custom look and feel using the new Activity Designer is very easy.
 
2. Custom Activity
 
WF4.0 supports the custom activity development. Custom Activity development involves two parts- designer development and execution logic implementation.
 
3. BookMark
 
In WF4.0, we use different ways of communication between Host application and workflow. There are different approaches like Bookmark, Extension methods, WCF Workflow services, workflow level arguments, etc. Here, we will discuss about the simple way of communication between host application and workflow using Bookmarks.
 
Bookmark is a pointer we create in the workflow execution. Bookmarks can be used for handling various events from Host application and also as data communication between Host and workflow. Bookmarks can be Non-blocking, None or Multi-Resume. Type of the Bookmark can be set using the BookmarkOptions enumerator. 
 
None: By default the bookmark will be of blocking type. When a bookmark encountered, the execution of the
workflow will go to the idle state. Workflow execution will wait for the resumption of one of the bookmarks.
 
Non-blocking: Here, the execution of the workflow continues.
 
Multi-Resume: This bookmark is of blocking type. We can resume the bookmark multiple times. 
 
4. WorkflowDataContext
 
If you want to pass some common data to all the activities defined in the workflow, we can use the workflowDataContext associated with the workflow. 
 
5. Extension
 
Extension is a normal class with public methods and properties. Once we add the extension class to the workflow application, we can use the same in any child activities. For each instance of the workflow application will have one instance of its extension class. Using the context associated with the custom activity, we can access the extensions.
 
6. Persistence
 
Persistence means storing the current state of a workflow. For better understanding, we will consider a document processing scenario.
 
In document processing, one user uploads the document and the workflow gets started. Then the document will go to the reviewer.  Reviewer will review the document, either accepts it or reject with comments. In this scenario, reviewing of the document can happen in a different application or can be done after many months.
 
When we deal with this kind of scenario, we will go for persistence. After uploading the document, the corresponding workflow state is stored in an InstanceStore. When the review starts, we can reload and continue execution of the workflow from the last executed state. In our scenario, the reviewer can use another application, which can reload the workflow from the InstanceStore and continue execution. Also, as we are storing the workflow to InstanceStore, we can manage the long running workflow effectively.
 
7. WCF Integration
 
When we create a new project, under the workflow project templates, we have the option to select the WCF Workflow Service Application.
 
Once, we create a WCF Workflow Service application, it will create a default WCF integrated workflow. The extension of our new workflow file is not .xaml, it is .xamlx.
 
8. PropertyValueEditor
 
We can either use the TypeConverter or PropertyValueEditor for managing the properties and associated editors in PropertyGrid. TypeConverters are same as those in WPF. PropertyValueEditors are similar to the PropertyEditors in WPF, which provides custom editor for our property.
 
9. PersistenceParticipant
 
We already discussed about Persistence and Extensions in workflow foundation 4.0. Persistence is the way of storing the current state of a workflow into an instance store. Extensions are special classes for sharing data among child activities, workflow and Host application. In case of normal Extension, the data shared using the Extension won’t be stored to the instance store as part of the Persistence.
 
In real business scenario, we may need to store the Extension data as part of the workflow state. For this purpose, workflow foundation 4.0 is providing a special kind of Extension called PersistenceParticipant.
 
10. Type Converter
 
Type Converters are used to pre-populate the expected values of a Property. We can either allow the user to edit new values or can restrict the user to only select from the given values using Type Converter.
 
11. Validation
 
Workflow Foundation 4.0 Argument Validation and Propery Validation.

Basics of Windows Workflow Foundation (WF)

Basics of Windows Workflow Foundation (WF)
 
In this tutorial on windows workflow foundation, we will learn some basic concepts of WF like why to use window workflow foundation, what is workflow and activity, types of workflow like sequential workflow and state machine workflow and their uses. These are the basic concepts of WF which are asked in any .net technical interview. Lets have a look upon them. 
 
1. Why do we need Windows Workflow Foundation (WF)?
 
WF can be used in following two scenarios:
 
1. When business logic changes frequently
 
When the business requirements are changing frequently, you can use WF. Suppose you have developed an application for many end users. But each end user needs little bit customization on his end, then instead of changing code for each customer, you can simply use WF to change the logic.
 
WF allows a scenario where business logic inplemented as a workflow model or as a set of rules can be changed while the application is executing. No redeployment of .NET assemblies or recompilation is required. This leads to a software design where a central repository of business logic is possible that can be edited as part of normal work processes.
 
2. WF provides visibility into the workflow model
 
You can view a workflow model in the workflow designer, and you can print it out or take a copy of the image for inclusion in a functional specification. This can be valuable in explaining the software to non-developers or it could be useful documentation for when a software design needs to be learned by others and modified later.
 
2. What is Workflow and Activity?
 
A Workflow is a set of activities. Workflow model can be written in pure .NET code, pure XAML or Mix of XAML and .NET code.
 
3. What are different types of Workflow in Windows Workflow foundation?
 
There are two basics type of workflow: Sequential Workflow and State machines workflow
 
A sequential workflow has clear start and finish boundaries. In sequential execution, one task is executed after other. Sequential workflow has a determistic nature.
 
A State machine workflow is more dynamic in nature. Workflow has states and the state waits for events to help it move to next state. In State machine execution path is undetermestic nature.
 
4. When should we use a sequential workflow and when should we use state machines?
 
If the workflow is very rigid then you go for sequential workflow and if the workflow is dynamic then go for State machine workflow.
 
For instance you have placed an order and the order will not pass until your supervisor approves is a rigid flow. Because your order has to be approved by, a supervisor or else it will not be approved.
 
But what if your order moves from one place to other place. For instance, it moves from approval to waiting and then clarification a state machine workflow model is more appropriate.

Saturday, 6 April 2013

Website Traffic Analytics Softwares: Alternatives and Competitors of Google Analytics

Website Traffic Analytics Softwares: Alternatives and Competitors of Google Analytics

Google Analytics is the best online analytics tool and software to track your website traffic and stats. Almost every website or blog owner uses Google Analytics to monitor their website traffic and statistics. Google Analytics provides loads of great information on how your website is performing. Google Analytics lets you know whether your traffic is going up or down, how people are finding you, what search terms they are using, what your conversion rate is, and so on.

But Google Analytics has a problem. Google Analytics cannot truly measure how long a visitor stays on your site, unless they perform another action like a new page load. Many visitors will show up as having stayed on your site for zero seconds, even though they might have spent minutes or more, reading a page or watching a video.

How to choose best Analytics Tool for your website or blog?

Keep following things in mind before choosing analytics tool for monitoring traffic and stats of your website:

1. Does it do real-time tracking, so that you can see what’s going on on your site right now?

2. Does it properly measure time on site, even if only one page is viewed?

3. Does it make a distinction between a “bad bounce” (short, one-page visit) and a “good bounce” (long, one-page visit)?

4. Does it allow useful sorting and filtering of the stats, so you can make intelligent decisions based on your analytics?

5. Does it allow easy goal/conversion tracking?
 
There are a lot of alternative analytics solutions available online beside Google Analytics. These analytics tool are giving tough competition to google analytics and proving themselves an alternative of google analytics. Some of these analytics tools are listed below:

1. Mint

Mint is a very stylish “less is more” kind of analysis software. Where many others pile on feature after feature, Mint strives to show you the most relevant data about your website in a simple “at a glance” kind of way.

The “less is more” principle is take a tad too far, sadly. The standard view shows you the visitor count (total and unique), the top referring websites, your most popular pages and the most popular search terms people are using to find your site. You can edit each view for a certain date-range or to show you recent terms/referrers rather than popular ones.

Interestingly, there’s also a separate view for traffic coming through image searches, which could be a very interesting feature for certain types of websites like portfolio sites, sites about design or any other image-heavy sites.

Data digging is almost non-existent with Mint. It also doesn’t show bounce rates, time on site or any other useful user engagement metrics. My impression is that Mint shows you mainly “vanity stats”, but fails to give you the tools necessary to sort your data in such a way that it can lead to intelligent changes on your website, that improve your business.

The basic functionality of Mint can be expanded with so-called “Peppers”. These are plugins for Mint, which are provided by the developers themselves as well as third-party providers.

2. Clicky

I’ve been using Clicky for quite a long time now. In the beginning, I had mixed feelings about the user interface, but once I got used to it, I recognized it’s merits. The standard dashboard gives a very comprehensive overview over all of the core data: visitors (today vs. yesterday or any other date-range you set), visitor actions and bounce rate, top content, top search terms and traffic sources.

One thing Clicky does reall well is allow you to dig down and segment/filter your data in many ways. It doesn’t just show you some fancy graphs, it let’s you get right down to the stuff that matters the most: you can find where your best converting traffic is coming from, you can see which pages are grabbing your visitors’ attention and which aren’t and much more.

Clicky also offers a simple way to set up campaigns and track earnings. An interesting feature is that it allows you to set up custom twitter searches, so that you can monitor mentions of your site or brand on twitter, from within the Clicky dashboard. The service also integrate with a service called SheerSEO as well as Visual Website Optimizer for rank tracking and split testing respectively. Plus, it comes with a very well-made WordPress plugin.

Clicky calculate bouce rate differently from most analytics solutions and they’re proud of it. Clicky considers every visitor who spends more than 30 seconds looking at a page as an “engaged” visitor and doesn’t count them as a bounce, even if they don’t view a second page on your site. This makes a lot of sense, since you can’t really say that someone who visits your site, reads a whole post and then leaves was “bouncing”. They just found what they were looking for. With this, Clicky has more relevant bounce stats, especially for blog-style sites where the goal is not necessarily to get every visitor deeper into a sales-funnel.

3. Chartbeat

Chartbeat has a very strong focus on what’s happening right now, as opposed to the emphasis on historical data analysis that most tools have. On a second-by-second basis, it shows you how many visitors are on your site, how many of them are reading or writing (e.g. comments), the geographic location of the visitors, an action stream and much more.

Like Clicky, it also comes with twitter monitoring, so you can see who’s talking about your site or brand, at any given moment.

One very interesting and potentially useful user engagement metric is that Chartbeat shows you a graph of the average scroll-depth for your visitors (i.e. how far down a page they are scrolling).

4. Statcounter

StatCounter is one of the better-known free Google Analytics alternatives and it’s been around for a while.

Compared to the other solutions listed here, StatCounter is ugly. But, just because you don’t get the “oooh, shiny!” effect when you log into StatCounter, doesn’t mean it’s a bad product. The basic data is all there and you can get insights into visits, visitor paths, popular pages, entrance- and exit-pages, incoming keywords etc.

In terms of segmentation, goals, campaign/funnel tracking and fancy stuff like that, StatCounter lags behind the competition. As with Mint, StatCounter fails to deliver the kinds of insights that will actually help you make meaningful changes to your site.

5. Piwik

Piwik is advertised as an open-source alternative to Google Analytics and this seems an accurate description. It’s completely free to use and fairly easy to install. Currently only available as a self-hosted script (which has it’s advantages), there’s also the possibility of a hosted version of the service in discussion.

While the Piwik dashboard is nowhere near as fancy looking as some of the competitors’, I immediately took a liking to it. It’s a bit reminiscent of the WordPress admin interface and it just seems to have all the data and all the buttons in the right places. I found it very easy to navigate the data and set up some basic goals for performance tracking. It’s also a breeze to add as many websites as you like to one and the same Piwik installation. Much like with Mint, the Piwik dashboard is very customizable and additional plugins are available to add to the system.

One of the best features is that you can very easily set up and track goals. Beyond the basic stats, I would have liked options for deeper and more detailed segmentation, which is often lacking.

6. Open Web Analytics

Open Web Analytics (or OWA) is another free, open source web stats solution, like Piwik. It’s also self-hosted and it’s available as a WordPress plugin, which creates one instance of OWA to track the specific WP site it’s installed on. Installed separately and independently from WordPress, you can use OWA to track multiple websites.

The user interface is reminiscent of one of the older Google Analytics interfaces in the choice of colors as well as the general navigation. It’s not a carbon copy of GA by any means, but it offers the same general navigation options and if you’ve used GA for a while, it won’t take long until you feel right at home with this new interface.

Open Web Analytics is very feature-rich, especially considering that it’s free to use. It can track goals along several steps of a conversion funnel, it offers separate stats filtered by pretty much any factor you can think of and it even offers heatmaps and mouse-tracking. However, be warned: with those last two options active, OWA will gobble up server resources like nobody’s business. A shared hosting account will not find this agreeable.

7. GoSquared

GoSquared is all about live analytics, much like Chartbeat. And while I do feel a little bad about saying mean things about nice apps, I can’t help it: the “pretty but useless” syndrome is present here, as well.

Like Chartbeat, GoSquared shows you a second-by-second view of what’s happening on your website. This includes traffic sources, top visited content, referral sources and social media monitoring.

Historical data is almost completely absent from the GoSquared dashboard. As I said, it’s all about live analytics. That means you’ll only get useful data on high-traffic sites to begin with. It also begs the question of how one is supposed to make use of all the data presented.

8. Woopra

Woopra has been around for a long time and has undergone several transformations since the early days.

In the latest version, Woopra is moving away from “standard” analytics solutions and into the stomping grounds of Kissmetrics and Mixpanel. Woopra’s defining feature is an integration of on-site analytics and customer relation management: the goal is to track individual visitors as they use your site and services, even across multiple devices.

Woopra is extremely attractive and highly customizable. You can either use it online or download a desktop client or mobile app to track what’s going on on your site.

The customization options are this service’s strongest point: to any set of data you’re looking at, you can add any kind of filters you can think of. Do you want to look specifically at the conversion rates from people who discovered your site through twitter and viewed at least two pages? No problem. Do you want to attach a specific label to anyone who leaves a comment on your site and also pass their name and email address to Woopra? With a bit of custom coding, it can be done.

To top it off, Woopra also comes with a live chat feature, which lets you display a “chat with us” widget on your site, or lets you automatically invite visitors to chat when a certain set of criteria are met. For example, you could set the chat window to pop up when a visitor is spending a certain amount of time on the checkout page, to help them with any last questions or objections they might have. As I’m sure you can see, Woopra is powerful, if it’s used right.

The biggest disadvantage to Woopra is the per-site pricing model. If you want to monitor several websites, you need to purchase a separate subscription plan for each one.

9. Reinvigorate

Reinvigorate looked very promising, back when I was using the beta version. It still looks exactly the same, now. And that’s a bad thing.

Reinvigorate still feels like a beta product, even thought it’s been on the market for a while now. It has a very attractive looking user interface and it comes with a built-in heatmapping feature which can be very useful.

Unfortunately, in terms of actual traffic analysis, reinvigorate is mostly frustrating. It offers a great overview of the basic stats such as number of visitors, visit lengths and so on, but it doesn’t let you go any deeper than that.

10. Clearwebstats

ClearWebStats.com is a free service for webmasters to track and display web data from most websites. How much is your website worth? Find how many unique visitors are
visiting your site daily. See how your competitor web page is. Check your competitor site daily ads revenue from Google Adsense. This service allows you to see website data like never before!

11. Mouseflow.com

Mouseflow is a new online tool for performing advanced web analytics and realtime user studies on websites. It is a hosted service that can be used on any public face website.

Mouseflow records whole visitor sessions including mouse movements, clicks, scroll events and key strokes. Website administrators can play back the visitor sessions directly in the browser, just as if they were looking the user over the shoulder.

12. Leadlander

LeadLander provides you with the ability to view which companies are visiting and viewing your web site. Your can identify and monitor prospects in real time using LeadLander's
unique customer analysis engine.

13. Clicktale

In-Page Web Analytics: Reveal the mystery of what visitors are doing inside your webpage. Advanced capabilities such as watching movies of your visitors' browsing sessions to
analyze their behavior, scrolling Heatmaps show where visitors look and how far down they scroll, linking analytics shows every interaction, hover, hesitation time, and much more, and forming analytics reveals problem fields in online forms that cause visitors to leave.

14. Crazy Egg

CrazyEgg helps you visualize your visitors. What that means is that it gives you a clear understanding of where people are clicking on a web page with visual heatmap and visual
overlay. It is mainly a testing platform that helps you improve your web site.

Friday, 5 April 2013

How to Store an Array in a List in C#?

How to Store an Array in a List in C#?
 
Lists in C# are very easy and efficient way to store data as these can be resized dynamically. With List, you do not need to manage the size on your own. Lists are generics and constructed types. You need to use < and > in the List declaration. Lists can handle any kind of element type. You can perform variety of operations on list with ease.
 
In this article we will see how can we store an array into a list and access it.
 
Lets have a look at very simple example of List
 
using System.Collections.Generic;
class Program
{
    static void Main()
    {
       List<int> list = new List<int>();
       list.Add(1);
       list.Add(2);
       list.Add(3);
       list.Add(4);
    }
}
 
Now lets see how can we store an entire array into the list? I wll use AddRange function to copy an array into the list.
 
using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
        List<int> a = new List<int>();
        a.Add(1);
        a.Add(2);
        a.Add(3);
        a.Add(4);
        int[] b = new int[3];
        b[0] = 5;
        b[1] = 6;
        b[2] = 7;
        a.AddRange(b);
        foreach (int i in a)
        {
           Console.WriteLine(i);
        }
    }
}
 
Output
1
2
3
4
5
6
7
 
Now, 2nd way to copy an entire array into the list. I will not use AddRange function here. I will just directly pass array while declaring the list.
 
using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
       int[] arr = new int[3];
       arr[0] = 1;
       arr[1] = 2;
       arr[2] = 3;
       List<int> list = new List<int>(arr);
       Console.WriteLine(list.Count);      
    }
}
 
Output
3
 
C# Program to convert a list into an array. I will use Join function to join all the elements which are converted into array with comma.
 
using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
       List<string> cities = new List<string>();
       cities.Add("New York");
       cities.Add("Paris");
       cities.Add("London");
       cities.Add("Berlin");
       // Join strings into one CSV line
       string line = string.Join(",", cities.ToArray());
      Console.WriteLine(line);
    }
}
 
Output
New York,Paris,London,Berlin
 
C# Program to access elements of the list. There are two ways to access the elements of the list

1. By using foreach
2. By using Count property of the list
 
using System;
using System.Collections.Generic;
class Program
{
    static void Main()
    {
      List<int> list = new List<int>();
      list.Add(1);
      list.Add(2);
      list.Add(3);
      foreach (int prime in list)
      {
         Console.WriteLine(prime);
      }
      for (int i = 0; i < list.Count; i++)
      {
         Console.WriteLine(list[i]);
      }
    }
}

Wednesday, 3 April 2013

Difference between System.String and System.Text.StringBuilder in C# (C Sharp)?

Difference between System.String and System.Text.StringBuilder in C# (C Sharp)?

If you know C#, you must know the difference between String and StringBuilder Class. When to use what and why? There is a basic difference of performance and speed in String and StringBuilder class which I will try to highlight here with the help of a simple example.

Suggestion: If you are going for interview on ASP.NET with C#, you must prepare this basic question of difference between String and StringBuilder in C#.

Now, lets starting exploring the difference between String and SringBuilder:

1. Performance of StringBuilder is high

Lets take an example to illustrate this concept. StringBuilder will deliver high performance as compared to String when you are concatenating the strings like following:

String s= "";
s+= "abc ";
s+= "pqr ";
s+= "xyz";

Same can be done using StringBuilder class

StringBuilder sb = new StringBuilder("");
sb.Append("abc");
sb.Append("pqr ");
sb.Append("xyz");
String s = sb.ToString();

Now in both case when I used String and StringBuilder, the end result is same, but performance issues are there with String class. String always create new object of string type in memory when the concatenation happens while when you use string builder class, it updates string at one place in memory and does not create new space in memory. So in this way StringBuilder consumes less memory and delivers high speed. So we can say that StringBuilder is more efficient for operations that manipulate strings.

2. StringBuilder is a Mutable Class while String is Immutable

This point is the extension of the point 1. Let me explain the meaning of mutable and immutable class.

StringBuilder is mutable means that you can insert, append, replace etc. without creating a new StringBuilder each time.

String is immutable means that each time you perform an operation like insert, append, replace etc. that "changes" it, you are creating a new string to replace the old one. You create a string you can never change it, rather it will create a new string to store the new value, this can be inefficient if you need to change the value of a string variable a lot.

Like in the above example, we are concating many values to the String s which in turn is creating new instances of String s and the destroying it and we are ending up with only the final String which looks like s= "abc pqr xyz ". But StringBuilder will not create multiple instances of StringBuilder sb while concatenating.

3. String class belongs to the namespace System while StringBuilder class belongs to the namespace System.Text.