Click here to Skip to main content
15,867,568 members
Articles / Web Development / ASP.NET

Simple but Interesting Features of VS2010 and C# 4.0

Rate me:
Please Sign up or sign in to vote.
4.74/5 (136 votes)
10 Sep 2012CPOL7 min read 260.8K   1K   155   172
Some very simple, yet interesting features of VS2010 and C# 4.0

Introduction

VS 2010 and C# 4.0 introduced so many new features. Here in this article, I try to cover some very simple, yet very useful features of both.

1. Hiding the Selected Part of Code

Many a times, a situation arises when we want to hide a specified piece of code rather that hiding the entire region. This has become easier in VS 2010. Just select the part of the code that you want to hide and right click select Outlining -> Hide Selection.

Same way like a region code also gets collapsible and expandable area. Anytime you wish to remove this hiding of text again, select right click, select Outlining -> Stop Hiding Current.

Image 1

2. DataTips

This option provides us with a simpler way by which we can communicate with any variable at debugging time. In 2010, a DataTip can be pinned at a location or it can even float. This gives us an easier way to monitor our variable and its value during debugging. We can add as many DataTips and will remain there even after the session is closed.

In order to add Pin to DataTip, just place the mouse pointer over any variable you can see the pin icon click on it.

Image 2

You can move your pin to any location. Pin provides you three buttons close, Unpin (to remove pin), Expand (to add any comment).

Image 3

Once code has been debugged and still we want to see what value the variable/expression was holding at the time of debugging, then this feature is very helpful.

Image 4

You can even Export/Import your DataTips. Click on Debug ->Export DataTips -> Specify the location where you want the XML file to be saved.

You can access your XML file anytime by selecting Import option on the Debug -> Import DataTips.

3. String.IsNullOrWhiteSpace

It checks whether the specified string is empty, null, or contains only white-space characters. If the string contains any of this, only then the method will return true.

  • \n” for new lines
  • \r” for carriage returns
  • \v” for vertical spaces
  • Normal spaces
  • \t” for tab characters

Image 5

4. Named and Optional Parameters

VS2010 parameters become optional when default value is assigned to it.

Image 6

In the above method, we can omit Val1 and Val2 as they have a default value and can be treated as optional. The moment we start tying the method, the intelligence indicates which parameters are optional.

Image 7

Named arguments allow user not to remember the order of parameters. If you know the name of the parameter, then you can call them in any order. Intelligence supports named argument by parameter name followed by colon (Smile | :) .

Image 9

Here is a complete example showing optional and named argument:

Image 10

Image 11

5. Highlighting

Select an identifier anywhere in the code and all the places where that identifier is used gets highlighted.

In the below example, I have selected identifier Val2 and all its usages are highlighted automatically.

Image 12

6. Intelligence Generated as Per Usage

This feature is quite interesting. I experienced it when I created a class with the name test and while declaring the object, by mistake I wrote tset and it allowed me to create the object with a red line.

When I saw a red line, I just right clicked my mouse and saw an option called generate having two choices Class and New type. The intelligence is improved so much that any method missing in the class can be used first and created later.

Image 13

7. URL Routing

URL mapping was possible to a certain extent in ASP.NET 2.0. We can define the URL which we want to show but the problem was in the case of postback, the actual URL in the browser is shown.

URL routing was introduced in ASP.NET 3.5. In this problem of PostBack was solved but we had to create different handler classes depending on the number of URL routings.

In ASP.NET 4.0, the need for defining separate handler classes for each routing has been removed and there is a built in helper function named MapPageRoute which helps to implement routing more quickly. These routes are registered onApplication_Start.

Let's do routing using a simple example. I have two pages default and default2. And a button on each page to take you to the next. Along with that, moving from one page to another, I need to pass a parameter too. First thing in the global.asax file under the Application_Start, we have to assign the URL that we want them to appear on the browser window.

C#
void Application_Start(object sender, EventArgs e)
{
   // Code that runs on application startup

   System.Web.Routing.RouteTable.Routes.MapPageRoute
	("StoreRoute","MyFirstPage/{Name}","~/Default.aspx");
   System.Web.Routing.RouteTable.Routes.MapPageRoute
	("Route1", "MySecondPage/{Name}", "~/Default2.aspx");
}

default will have the URL MyfirstPage/Value of the parameter name and default2 will have the URL MySecongPage/value of the parameter name.

On the button click of default page, I have added the following code to call default2 page:

C#
protected void btnBack_Click(object sender, EventArgs e)
{
    Response.Redirect(ResolveUrl("~/MySecondPage/") + "An");
}

Here "An" is the value of the parameter Name, and a similar code is added on default2 page to take you back to default page.

C#
protected void btnMove_Click(object sender, EventArgs e)
{
    Response.Redirect(ResolveUrl("~/MyFirstPage/") + "Test");
}

Routing has become much easier and simpler. We can pass more than one parameter too.

8. Dynamic Language Support

Dynamic languages are the ones which don't perform compile-time type checks, rather they identify the type of objects at run time only. It is faster and easier to write but we are not able to see compile time errors. So, we have to make sure that the application is behaving in the manner as depicted.

If we see previous versions of C# then it was fully static language, but 4.0 has added a new dynamic element to support dynamic feature. Using dynamic keyword means telling the compiler to turn off compile-time checking.

Image 14

Now comes a very obvious question, what is the difference between Object, Var and Dynamic types. Let's see:

ObjectDynamicVar
Compiler has a little information about the type of the variableNo information with the compilerCompiler has complete information
The variable requires casting before being usedNo casting requiredNo casting required, as the compiler already has complete information
If we don't have more information of the data type, it is usefulWhen we need to write less code and using Dynamic language Usually used with Linq

9. ClientID Generation using ClientIDMode

In ASP.NET, if we look at the client side, it is very hard to predict what ClientId the page will be rendering. ASP.NET uses a unique naming system for ClientId generation.

But now with ASP.NET 4.0, handling ClientId has become very easy. So far, we have seen if we add any control to aspx page and view its source, we can see id of the control something like this “ctl00_MainContent_txtName”. Now by the property ClientIDMode we can set the ID the way we wish it should be generated.

ASP.NET 4.0 provides four mode types for ClientIDMode property.

Auto

The ID so far ASP.NET 2.0/3.0/3.5 was generating.

Example

ASP.NET
<asp:TextBox ID="txtData" runat="server" ClientIDMode="AutoID"></asp:TextBox>

when we view its source, the ClientId generated is "ctl00_MainContent_txtData" :

HTML
<input name="ctl00$MainContent$txtData"
   type="text" value="Test" id="ctl00_MainContent_txtData" />

Static

This mode makes the client side ID static, meaning that what ID is assigned to the control on the server side same will be used for the client side ID. But if a mode is set static for a repetitive control, then it is the developer’s responsibility for ensuring client side ID uniqueness.

Example

HTML
<div id="divVal3" runat="server" clientidmode="Static"></div>

when we view its source, the Client Id generated is "divVal3"

HTML
<div id="divVal3">a= 3</div>

Predictable

Predictable depends on the parent naming control’s ClientID to build its own client ID value. It takes the parent name underscore control’s name, excludes ctxxx. This is mostly useful for DataBound controls.

Example

ASP.NET
<asp:GridView ID="grdTest" 
runat="server" AutoGenerateColumns="false"
ClientIDMode="Predictable" >
    <Columns>
        <asp:TemplateField HeaderText="ID">
            <ItemTemplate>
                <asp:Label ID="ID" 
                runat="server" Text='
                <%# Eval("ID") %>' />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Name">
            <ItemTemplate>
                <asp:Label ID="Name" 
                runat="server" Text='
                <%# Eval("Name") %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

When we view its source:

HTML
<table id="grdTest" 
style="border-collapse: collapse" 
cellspacing="0" rules="all" 
border="1">
    <tbody>
        <tr>
            <th scope="col">ID</th>
            <th scope="col">Name</th>
        </tr>
        <tr>
            <td><span id="
            grdTest_ID_0">1</span></td>
            <td><span id="
            grdTest_Name_0">ABC</span></td>
        </tr>
        ...
        <tr>
            <td><span id="
            grdTest_ID_1">2</span></td>
            <td><span id="
            grdTest_Name_1">XYZ</span></td>
        </tr>
    </tbody>
</table>

Inherit

This is the default behavior for every control. It looks to its parent controls to get its value for ClientIDModel.

Example

HTML
<div id="divVal1" runat="server"></div>

It we don't mention any mode, then the default is Inherit.

HTML
<div id="MainContent_divVal1">a= 1, Val1= Named Val 1, Val2= Named Val 2</div>

We can set these properties in 3 ways:

  1. Control Level
    HTML
    <div id="divVal3" runat="server" clientidmode="Static"> </div>
  2. Page Level
    C#
    <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" 
    AutoEventWireup="true"
        CodeFile="Default.aspx.cs" Inherits="_Default" ClientIDMode="Inherit"    %>
  3. Application Level

    In your web.config file, under system.web we can set. It is useful when we upgrade an application from 2.0/3.0/3.5 to 4, at that time default mode was auto so all control ids will be rendered in auto, but the moment you upgrade to 4.0, it will be Predictable. So to make the code work, we can set in web.config clientIDMode="Auto":

    XML
    <system.web >
    <pages clientIDMode="Predictable"> </pages>
    </system.web>

Conclusion

I have created a sample application using all the above mentioned features. This is not the end, just the beginning of my exploration of the VS2010 features. It has become really very interesting when trying to go deep in these features and there are many more to explore.

History

  • 9th November, 2011: Initial version
  • 15th November, 2011: Modified the title and added one more feature
  • 17th November, 2011: Added a new feature "ClientIdMode"

License

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


Written By
Program Manager Infobeans
India India
I have keen interest in learning new things, exploring more on a topic and being more versatile

Comments and Discussions

 
GeneralMy vote of 5 Pin
Simon Gulliver2-Jul-15 21:50
professionalSimon Gulliver2-Jul-15 21:50 
GeneralRe: My vote of 5 Pin
Anuja Pawar Indore3-Jul-15 4:17
Anuja Pawar Indore3-Jul-15 4:17 
GeneralMy vote of 5 Pin
Santosh K. Tripathi9-Jun-15 19:57
professionalSantosh K. Tripathi9-Jun-15 19:57 
GeneralRe: My vote of 5 Pin
Anuja Pawar Indore9-Jun-15 20:41
Anuja Pawar Indore9-Jun-15 20:41 
QuestionMy vote of 5 Pin
Alex Tucker21-Jun-14 21:38
Alex Tucker21-Jun-14 21:38 
AnswerRe: My vote of 5 Pin
Anuja Pawar Indore22-Jun-14 20:26
Anuja Pawar Indore22-Jun-14 20:26 
GeneralNice Article Pin
OPees6-Mar-14 1:59
OPees6-Mar-14 1:59 
GeneralRe: Nice Article Pin
Anuja Pawar Indore6-Mar-14 2:38
Anuja Pawar Indore6-Mar-14 2:38 
GeneralMy vote of 5 Pin
Renju Vinod3-Sep-13 23:41
professionalRenju Vinod3-Sep-13 23:41 
GeneralRe: My vote of 5 Pin
Anuja Pawar Indore3-Sep-13 23:46
Anuja Pawar Indore3-Sep-13 23:46 
GeneralMy vote of 4 Pin
Dholakiya Ankit21-Aug-13 17:35
Dholakiya Ankit21-Aug-13 17:35 
GeneralRe: My vote of 4 Pin
Anuja Pawar Indore21-Aug-13 20:54
Anuja Pawar Indore21-Aug-13 20:54 
GeneralMy vote of 4 Pin
Mohammed Hameed29-Jul-13 22:56
professionalMohammed Hameed29-Jul-13 22:56 
GeneralRe: My vote of 4 Pin
Anuja Pawar Indore30-Jul-13 0:41
Anuja Pawar Indore30-Jul-13 0:41 
GeneralRe: My vote of 4 Pin
Mohammed Hameed30-Jul-13 1:05
professionalMohammed Hameed30-Jul-13 1:05 
GeneralMy vote of 5 Pin
Amol_B9-May-13 0:36
professionalAmol_B9-May-13 0:36 
GeneralRe: My vote of 5 Pin
Anuja Pawar Indore9-May-13 1:22
Anuja Pawar Indore9-May-13 1:22 
GeneralMy vote of 5 Pin
santosh kundkar2-Feb-13 1:37
santosh kundkar2-Feb-13 1:37 
GeneralRe: My vote of 5 Pin
Anuja Pawar Indore23-Feb-13 4:41
Anuja Pawar Indore23-Feb-13 4:41 
GeneralMy vote of 5+ Pin
Sheikh Muhammad Haris7-Jan-13 6:38
Sheikh Muhammad Haris7-Jan-13 6:38 
GeneralRe: My vote of 5+ Pin
Anuja Pawar Indore23-Feb-13 4:42
Anuja Pawar Indore23-Feb-13 4:42 
GeneralMy 5+ Pin
MaulikDusara17-Dec-12 1:21
MaulikDusara17-Dec-12 1:21 
GeneralRe: My 5+ Pin
Anuja Pawar Indore17-Dec-12 1:23
Anuja Pawar Indore17-Dec-12 1:23 
GeneralThanks Pin
Shreyash Gajbhiye8-Nov-12 9:56
professionalShreyash Gajbhiye8-Nov-12 9:56 
GeneralRe: Thanks Pin
Anuja Pawar Indore8-Nov-12 17:57
Anuja Pawar Indore8-Nov-12 17:57 

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

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