Archive

Archive for August, 2009

Using DebuggerDisplayAttribute

In .Net, we can view variables contents in different ways like local window, quick watch, etc. In System.Diagnostics namespace, we can see a DebuggerDisplayAttribute class that is used to view variables’ contents in debugger window. This attribute can be applied to class, field, property, enum, delegate, struct, etc.  Using this attribute, we can easily view variable contents in debug mode, and those contents are easily visible as data tip when we move mouse pointer over that variable. This attribute becomes quite useful when we have to view inner contents of custom type object variable when it has collection of values.

For example, we will apply this attribute to a class and watch the collection values in debug window.

[DebuggerDisplay("Client Name = {CustomerName} Client Type = {CustomerType, nq}")]
class Customer
{
private string _CustomerName;
private string _CustomerType;
public Customer(string strCustomerName, string strCustomerType)
{
_CustomerName = strCustomerName;
_CustomerType = strCustomerType;
}
public string CustomerName
{
get { return _CustomerName; }
}
public string CustomerType
{
get { return _CustomerType; }
}
}
Now after loading a Customer type collection, we see following view in data tip:
DebuggerDisplayAttribute

Fig 1: DebuggerDisplayAttribute changing the data view.
Had not we used DebuggerDisplayAttribute on Customer class type, we would have to traverse a long hierarchy of tree view of each index value of collection object to view data contents.

Programmers often override ToString() method in the custom class type method to view data. But still DebuggerDisplayAttribute wins the heart!

When ToString() method is overridden inside Customer class, then ToString() method of Customer object will result as:

public new string ToString()
{
return (“Customer Name: ” + _CustomerName + “\n” + “Customer Type: ” + _CustomerType);
}
ToString Method
Fig 2: Result of overridden ToString() method.

DebuggerDisplayAttribute constructor has only one parameter as string. The {} braces contain field or property or method name. In the example above, we have used this way.

[DebuggerDisplay("Client Name = {CustomerName} Client Type = {CustomerType, nq}")]

One can also quickly see {CustomerType, nq}. Due to this “nq” specifier, Client Type value is shown without double quotes, whereas Client Name value is still in double quote (see Fig 1). The “nq” specifier is used for string type properties.

Happy debugging for next time!

Using Statement and Dispose Method in C# and VB.Net

Since .Net 2.0, we are aware of using statement to perform resource intensive operations like database operations, file IO operations, etc. Using statement basically marks a boundary for the objects specified inside using () braces. So when code block using (){} (in C#) or Using – End Using (in VB.Net) is exited either after normal execution or some exception cause, the framework invokes the Dispose method of these objects automatically. Before creating or using any object inside using block, one must make sure that the object type implements the IDisposable interface.
We can specify multiple objects inside using-block, and also write using-blocks in stack as shown in example below.
public class DotNetTips
{
private void DoSomeOperation()
{
using (SqlConnection con1 = new SqlConnection("First Connection String"), con2 = new SqlConnection(("Second Connection String"))
{
//Rest of the code goes here
}
}

private void DoSomeOtherOperation()
{
using (SqlConnection con = new SqlConnection("Connection String"))
using (SqlCommand cmd = new SqlCommand())
{
//Rest of the code goes here
}
}
}
Using statement is useful when we have to call dispose method multiple times on different objects. Otherwise, we will have to call Dispose method on each object as:
if (con != null) con.Dispose();
if (cmd != null) cmd.Dispose();
When the using block code compiles to intermediate language, it translates the using statements into equivalent try/finally block.

I hope this tip can be useful for all.

Rethrow exception and InnerException property in .Net

Most of the time when we re-throw exception from our code block, we supply some meaningful and friendly message if any error condition occurs. This message is supplied in the constructor method of that exception type. But in this re-throwing process, we often forget to preserve Inner Exception property. And when we log the exception message (ex.Message), we lose the details of original exception.

In the example below, we have re-thrown exception with only friendly message in the constructor method.

private void DivideOperation()
{
try
{
int x = 5;
int y = 0;
int result = x/y;
}
catch (Exception ex)
{
throw new DivideByZeroException(“Invalid operands were given.”);
}
}

Null InnerException
Fig 1: InnerException property is null.

This is of course not a good practice to do exception handling. So to preserve the details of original exception, we have to pass the exception object as second parameter in additional to friendly message as:

private void DivideOperation()
{
try
{
int x = 5;
int y = 0;
int result = x/y;
}
catch (Exception ex)
{
throw new DivideByZeroException(“Invalid operands were given.”, ex);
}
}

Valid inner exception
Fig 2: InnerException property detail is preserved.

One can see the difference of InnerException property value in these two cases.

Follow

Get every new post delivered to your Inbox.