Saturday, September 25, 2010

C# Programming Tips and Tricks

Introduction
C# is a great language. It is relatively easy to learn with its simpler syntax over C++ programming and Java. Ten years down the line it still is a strong competitor. It has had improvement year after year, with new features added with its every release. It has not disappointed the C# developer community.
No time to read prologue, right? I know. Let's jump straight in. 
1.   Environment.Newline
Did you know that this property is platform independent and allows you to output the new line characters as per the platform?
  Console.WriteLine("My Tips On ,{0}C#", Environment.NewLine);
Namespace Alias
Did you know that you can substitute your big namespaces with shorter aliases? Or have you faced a situation where you had to qualify the object with its complete namespace to avoid ambiguity.
Look at the sample below where there is a generic library created with extended .NET Framework controls.
                using System.Web.UI.WebControls;
                using MyGenericLibrary.UserControls;
         
           /* Assuming that you had a Text Box control in both the namespace, you would have to fully qualify  the class object with the complete namespace. To avoid that, you can use namespace alias. Change as below */
               
                using System.Web.UI.WebControls;
                using mc = MyGenericLibrary.UserControls;
         
          /*and then use, /*
                mc.TextBox textbox = new mc.TextBox();
  DebuggerBrowsable Attribute
Every C# developer does debugging at some point or the other. This attribute is very powerful in controlling the behavior of an object during the debugging process. The debugging process involves the display of the object being debugging in a small tooltip window.
It can be used to hide the private members, or other members that are considered to be useless in the debugging window, e.g. when you debug any class object you would see the private variables in the debugger window. You can hide it using the [DebuggerBrowsable(DebuggerBrowsableState.Never)] attribute.
  public class MyClass
  {
      private string _id;
       
      public string InternalID
      {
            get { return _id; }
            set { _id = value; }
      }
  }
VISIBLE

  [DebuggerBrowsable(DebuggerBrowsableState.Never)]
  public class MyClass
  {
      private string _id;
       
      public string InternalID
      {
            get { return _id; }
            set { _id = value; }
      }
  }
 
HIDDEN
  DebuggerDisplay Attribute
This attribute makes the display of the variable object with a readable description. It helps users who work on your projects in the future.
/It's simple to use. The following code shows the value of the variable.
                public class MyClass
                {
             [DebuggerDisplay("Value = {myVariable}")]
                    public string myVariable = "mydisplay";
                }
       
  Create Virtual Directory for the Project
You can force every developer in your team to create virtual directories with the same name for the project. This trick from the Microsoft Visual Studio IDE is extremely helpful in keeping code sync'd over several C# developer machines.
Right-Click on the project and choose "Properties" from the options. Under the web tab, choose the "Use Local IIS Web Server" option and provide the virtual path.

Figure 1
Make these changes and check in your project file. All developers who use the project file will be asked to create a virtual directory with the same name in their machines.
  Change the Project Platform
You can change the platform of the application that you are building and target all or specific platforms. The platforms here refer to the 32-bit and the 64-bit environments.
Right-Click on the project and choose "Properties" from the options. Under the "Build" tab, choose the appropriate "Platform".


Figure 2
Make these changes and check in your project file. All developers who use the project file will be asked to create a virtual directory with the same name in their machines.
  Code Definition Window
This window lets you navigate to the Definition of an object. You can press the F12 key to quickly navigate to the definition of an object. Try it on any object in your editor right now and you shall not be disappointed.
There is also the "CODE DEFINITION WINDOW". The key combination CTRL + W,D will bring up the code definition window for you.
                 if (e.Item.ItemType == ListItemType.Item )
                {
                    //Your code here.
                }
       
If you place the cursor on ListItemType word, and press the key combination you will see a window like the one below.


Figure 3
  Null Coalescing Operator
The null coalescing operator lets you compare against null in a short manner. It is represented using the double question mark notation.
For example, the myfunction whose return value may be a nullable int. In such cases, you can use the coalescing operator to quickly check if it is null and return an alternate value.
                int myExpectedValueIfNull = 10;
                int expectedValue = myfunction() ??   myExpectedValueIfNull
  Shortcut for Using Statement
Ctrl and "." brings up the window with the list of probable using statements. Use the arrow keys to select. Press enter. Voila! A using statement is added.


Figure 4
10·  Dreadful Dataset Merge Errors
Have you been unable to figure out why the dataset merges failed? There is a way out.
Yes, you have to wrap your code in try-catch. But watch out for the specific code in the exception handling block that captures the exact reason for the merge to fail.
        StringBuilder error Messages = new StringBuilder();
        try
   {
                       DataSet dataSet1 = populateDataSet(1);
               DataSet dataSet2 = populateDataSet(2);
  
               dataset1.Merge(dataset2);
                       }
                       catch (System.Data.DataException de)
                       {
      foreach (DataTable myTable in dataSet1.Tables)
      {
         foreach (DataRow myRow in myTable.GetErrors())
         {
            foreach (DataColumn myColumn in myRow.GetColumnsInError())
            {
                //loop through each column in the row that has caused the error
                //during the bind and show it.
                 error Messages .Append(string.Format(
                  "Merge failed due to  : {0}", myColumn.GetColumnError(myColumn)));
            }
         }
      }
                      }

Conclusion
If you have some tips and tricks you'd like to share please leave them in the comments or email them to me directly. Thanks for reading.

No comments:

Post a Comment