10 More C# Programming and Microsoft Visual Studio Tips and Tricks


If you hit this page through a search engine, I would recommend the first article of this series, 10 C# Programming and Microsoft Visual Studio Tips and Tricks. Volume 2 of this series brings another bunch of useful recommendations for C# developers.

  1. DataTable.HasRows? – No. This is not part of any framework yet. But it is easy to imitate such a method through extension methods.

    This does not eliminate the primitive code that checks for the data table object being null or the Rows count, but simply simplifies the code in the applications. Below is the code snippet:

                          public static bool HasRows(this DataTable dataTable)
                   		return dataTable.IsNull() ? false : (dataTable.Rows.Count > 0);
       	public static bool IsNull(this object o)
                   		return (o == null);
       	    To use:

    Other rules pertaining the Extension methods remain same.

  2. ToTitleCase – The Titlecase is a casing behavior that converts the first character of a word to uppercase and the rest of the characters in the word to lowercase.

    For e.g. “look below for a sample” in titlecase becomes “Look Below For A Sample”.

    Yes, the TextInfo class that is part of the System.Globalization namespace does this but it has the following problems of its own.

    1. The current culture
    2. If the input string is in complete uppercase.

    The following extension method takes both this pitfalls into consideration.

                   public static string ToTitleCase(this string inputString)
                      return Thread.CurrentThread.CurrentCulture.TextInfo.
       	ToTitleCase((inputString ?? string.Empty).ToLower());

  3. Explicit and Implicit Interface Implementation – Does it matter?

    Yes, very much. Did you know other than the syntax difference between the two, there existed a fundamental difference.

    Implicit interface implementation on a class would be a public method by default and is accessible on the class’s object or the interface.

    Explicit interface implementation on a class would be a private method by default and is only accessible through the interface and not through the class object unlike the implicit implementation. Yes, through this you can force you clients to use the Interface and not the objects that implement it.

    Examine the code sample below:

      public interface IMyInterface
         void MyMethod(string myString);
      public MyImplicitClass: IMyInterface
         public void MyMethod(string myString)
      public MyExplicitClass: IMyInterface
         void IMyInterface.MyMethod(string myString)
      MyImplicitClass instance would work with either the class or the Interface:
      MyImplicitClass myObject = new MyImplicitClass();
      IMyInterface myObject  = new MyImplicitClass();
      MyExplicitClass would work only with the interface:
      //The following line would not work.
      MyExplicitClass myObject = new MyExplicitClass();
      //This will work
      IMyInterface myObject = new MyExplicitClass();

  4. Auto Properties – This is a favorite replacement for the property creation that involved a public and two private members.

    Type prop – and press the tab key twice (You need to have code snippets enabled). Voila! An Auto property is created for you. Press tab and give a name for the Auto property.

      private double _total;
      public double Total
      	get { return _total; }
         	set { _total = value; }

    Now becomes,

      public double Total { get; set; }

    Note that you can still apply the access specifiers as per your design. The compiler , would take care of the creation of private member varaibles for you.

  5. The Mighty Path.Combine

    Yes, the Path.Combine feature is so powerful that it removes the hassle of trailing slashes and the mixed up path problem. It is simple to use, and does the path string concatenations without much of a hassle.

    It takes a param of string paths and combines it for you.

    C#: Path.Combine Sample
    Figure 1

    Note that you do not have to worry about the valid separator character in the paths or whitespace. You do not have to deal with the less reliable string concatenation methods for path combinations.

  6. Quick way to write “Override” methods in a class

    Type “override” and press the space key. You will be listed with the list of overridable methods in the base class.

    C# Override methods in a class
    Figure 2

  7. Use External Configuration Files

    Thanks to the application (app.config) and web configuration (web.config) files, we are able to deal with the intricate application level settings. However, we still deal with problems of dealing with these settings for different environments. Yes, I am talking about the development, testing and production environment settings.

    We would have to revert to a particular environment and carry out an analysis, test or even have a need to debug some parts of the code. It becomes tedious to change each and every setting in this process.

    One such setting section that every application would have is the ConnectionStrings collection. You can now use the “ConfigSource” property to handle this through external file references.

    Look at the markup below that references a configuration file named “deveploment.config“:

      <connectionStrings configSource="configs\ development.config" />

    Yes, you can use this useful attribute with AppSettings sections too.

  8. Overcoming the limitations of String.Split method

    So much of delimited data around, who does not have the need to split them? String.Split is the ideal candidate for splitting a delimiting string.

    However, as we know, it has a limitation on the character used to delimit the string. Characters such as “||”, or “::” cannot be used. We have to look at the keyboard for unique single character to use as a delimiter.

    This problem can be overcome by using the Split method provided by the RegEx library. The following sample uses the RegEx Split to split a “||” delimited string.

      	string delimitedString = "String.Split || RegEx.Split");
      	string[] ouputString   = System.Text.RegularExpressions.Regex.Split(
      			, System.Text.RegularExpressions.Regex.Escape("||"));

  9. Quickly Navigate to and Element’s HTML source to Design View and vice-versa

    We spend a good amount of time on the IDE designing our applications. And the time spent on viewing the HTML content and on the design view accounts for a good part of it. There is a quickly way to navigate between the views and locate the HTML elements.

    If you are in HTML view, locate the element that you want to see in the design view, and then switch to design view. The element would be selected. Moreover, properties window would now show the properties of the selected elements.

    Similarly, when you are in design view, select the element and then switch to source view; the source of the HTML element will be highlighted for you.

  10. Quickly search for data in a datatable

    Although the data table supports the Find and the Select method for selecting rows, there are not a good choice against a DataView‘s similar method.

    The DataView provides us the FindRows method which would internally use the index created on the sorted column.


    Hope these help you save some precious programming time. I’ll be back very soon with some more tricks.

    Related Articles

More by Author

Must Read