Archive for May, 2007

Use String.Format (C# and VB.NET) instead of Chopping Strings

May 25th, 2007 by Sameer | 2 Comments | Filed in .NET articles

String.Format is just so cool.  It makes your code less spaghetti like and makes it easier to replace string values or add new values.  It also allows you to see from a quick glance what your code does.  It also makes it MUCH easier to update your string and add more parameters to it.  It works similarly to the printf function in C++ that takes a string, and then is followed by parameters that specify what to plug into the string.

Here is a String.Format example (C#):

text1.Text = string.Format("<a href=\"Mylink.aspx?abc=0&Color={0}\">my Link text</a>", myColor);

Isn’t that much nicer than our not so clean string concatenation (C#):


text1.Text = "<a href=\"Mylink.aspx?abc=0&Color=" + myColor + "\">my Link text</a>";

Now if we want to add one more parameter, it’s still so clean!  Note that it is the same syntax for C# and VB.NET

text1.Text = string.Format("<a href=\"Mylink.aspx?abc=0&ID={0}&wl={1}\">my Link text</a>", myColor, myWeight);

However, there are some performance considerations to think about.  In most cases, the minor performance gain is negligible compared to the clarity of code benefits.

Use TryParse instead of Throwing Exceptions (Try {} Catch {})

May 25th, 2007 by Sameer | 2 Comments | Filed in .NET articles
How to use TryParse with examples (Int32.TryParse, Double.TryParse, etc)

Exceptions should be left for exceptional circumstances.  We should not be using exceptions to control the flow and logic of our application. 

Exceptions are much more expensive to handle ,and are not meant to control the flow of your application.  If you are using a try catch block in order to convert a string to an int, you can completely avoid the exception by using TryParse.

TryParse was was added to .NET 2.0 specifically so that we could avoid this situation. If you have some .NET 1.0 code, you might not be taking advantage of .NET 2.0 new TryParse functions, which avoid exception handling and are much faster.

 

For example:

try
{
    iEditMode = Convert.ToInt32(strEditMode);
}

catch
{
    iEditMode = 0;
}

In this case, we have TryParse functions which were added in .NET 2.0
Better to instead do:

if (!Int32.TryParse(strEditMode, out iEditMode))
{
    iEditMode = 0;
}

Much better performance, no need to handle clunky exceptions :) Thank you to Brendan for correcting my error above. (missing out keyword)

MSDN in regards to exception handling states, "Do not use exception handling for flow of control, only for failure situations."

Resources 

Do NOT eat exceptions (C# .NET)

May 25th, 2007 by Sameer | No Comments | Filed in .NET articles

Proper exception handling is part of writing good code.  Here’s a quick tip – if you don’t want to handle an exception, fine, just leave it., don’t put any try/catch and just let the exception propogate up to it’s caller. 

If you are not sure why you are using try/catch, maybe you shouldn’t be using it.  It should not be used to control execution flow of the program, rather it should be used for ‘exceptional’ circumstances.

However, if you decide you don’t want to handle the exceptions and rather you do the following, that is very bad:

try
{
    //do something that will throw an exception, like try to execute an invalid SQL statement
}
catch
{
    //sweep the dirt under the rug ;
}

Consequences of swallowing exceptions blindly  - Your boss will not see any exceptions or code crashes, but it might come back to bite you in the butt when the code doesn’t do what it was supposed to!  You have no idea what you just swallowed, except it didn’t taste too good and looked kinda funny.

Additional Sources

Here’s an article by Steven Swafford discussing eating exceptions (among other things) – http://aspadvice.com/blogs/sswafford/archive/2007/05/10/Skills-versus-Passion_2C00_-are-they-the-same_3F00_.aspx

As a follow up, read Use TryParse Instead of Try/Catch

How To Properly Use ?? With Default Values

May 25th, 2007 by Sameer | No Comments | Filed in .NET articles

Let’s define a nullable.  You can declare a variable as nullable, for example

int
? x;

You are saying that the int might have a value, or it might have a null value.  This is convenient

Now in your code you might want to check and see if its actually null and if it is, give it some default Value.  There is a shortcut for this in C# which is ??.  The ?? shortcut does not apply only to nullable values.  You can use it with anything that may be null.

Here is an example of how to use it.  In the following case, our ViewState for the key "readonly" might be null (i.e. we did not put anything in there yet), and we want to get a default value of true if it is null.  Here is how we can cast it

myName.Visible = (

However, this will give you:

CS0019: Operator '??' cannot be applied to operands of type 'bool' and 'bool'

bool)(ViewState["readonly"]) ?? true;

 

So what can we do?

myName.Visible = (

 

With VB.NET, you would have to do something like

myName.Visible = IsNothing(ViewState("readonly"))

Or if you needed more than just a boolean,

myString = IIf(IsNothing(ViewState("isAdude")), "dude!" , "not a dude!")

Read more about nullables and the ?? operator

bool)(ViewState["readonly"] ?? true); This way you have said if its null, it will be true, then casted the whole thing.  That way you use this as 1 value on a single line rather than having a complicated if null then do this otherwise set it to this, yada yada..

Creating SqlParameters Best Practices

May 25th, 2007 by Sameer | 10 Comments | Filed in .NET articles

This article summarizes some nice ways to create SqlParameter arrays.  When we use SqlHelper, or even without SqlHelper when we use SqlCommands directly, and we want to pass an array of SqlParameters to the function.  The method I will discuss does not require you to hard-code the number of elements, nor does it require you to create a temporary list of some sort, but it requires you to have all the values up front that you want to insert into the list.

There are several ways to create this array.

  1. One is to hardcode the number of parameters as follows:
    SqlParameter array SqlParameter[] sqlParams = new SqlParameter[5];
  2. An evolution of this is to use an ArrayList
    ArrayList sqlParams = new ArrayList();

    Then add the parameters using sqlParams.Add(…) to add them
    Then the final step is to use sqlParams.ToArray() and pass that to your SqlHelper.

  3. Another evolution would be to use a Generic list of SqlParameters
    System.Collections.Generic.List<SqlParameter> sqlParams = new  System.Collections.Generic.List<SqlParameter>();

  4. But in my opinion the BEST way of creating your SqlParameter array is as follows:

    C# Example:

    Vb.Net Example:

     

     

     You can even use conditionals such as if your questionCode is null you want to insert a null (C# example):

    4.

    
          SqlParameter[] sqlParams = new SqlParameter[] {
             new SqlParameter("@username", strUserName) ,
             new SqlParameter("@password", strPassword)
          };
    
          Dim params As SqlParameter() = { _
             New SqlParameter("@CenterID", centerID), _
             New SqlParameter("@TypeID", typeID) _
          }
    
        SqlParameter[] sqlParams = new SqlParameter[] {
          new SqlParameter("@Required", required),
          questionCode == null ? new SqlParameter("@Code", DBNull.Value) : new SqlParameter("@Code", questionCode)
        };
    

Update Aug7’09 – Not specifying the DB type of the parameter will actually be slower than manually specifying the parameter sql types (ie int, varchar, etc). However, I find the tradeoff for convenience to be worth a slight loss of speed. This also allows you to change the parameter type in the stored procedure (say from datetime to string), without having to also update it here.

 

Update: Here is some example code using SqlParameters and DataAdapters