Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Simple but Interesting Features of VS2010 and C# 4.0

0.00/5 (No votes)
10 Sep 2012 8  
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.

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.

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

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.

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

4. Named and Optional Parameters

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

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.

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 | :) .

Here is a complete example showing optional and named argument:

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.

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.

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.

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:

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.

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.

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

Object Dynamic Var
Compiler has a little information about the type of the variable No information with the compiler Compiler has complete information
The variable requires casting before being used No casting required No casting required, as the compiler already has complete information
If we don't have more information of the data type, it is useful When 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:TextBox ID="txtData" runat="server" ClientIDMode="AutoID"></asp:TextBox>

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

 <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

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

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

<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: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:

<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

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

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

 <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
    <div id="divVal3" runat="server" clientidmode="Static"> </div>
  2. Page Level
    <%@ 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":

    <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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here