Blog

Categorised by 'C#'.

  • Debugging a page that uses many methods from other classes can become a right pain in the neck. I find myself accidentally stepping into a method that I don’t need to debug or wanting to output specific values from my methods straight away. Being the cowboy (correction, agile) developer that I am, one of my code boffins at work showed me a two cool ways to meet my debugging needs:

    1) DubuggerHidden Attribute

    Using the DubuggerHidden attribute tells the Visual Studio debugger that the method is hidden from the debugging process. The simple example below, shows the DebuggerHidden attribute in use:

    protected void btnDoSomething_Click(object sender, EventArgs e)
    {    
        //Output random number to Textbox
        txtOutput.Text = GetNumber(1, 10).ToString();
    } 
     
    [DebuggerHidden]
    int GetNumber(int min, int max)
    {    
        System.Random random = new Random();
        return random.Next(min, max);
    }
    

    2) DebuggerDisplay Attrubute

    The DebuggerDisplay attribute allows us to output variable values from a class or method to be displayed in our Visual Studio debugger. The attribute includes a single argument that is supplied as a string. The string can contain references to fields, properties and methods in the class so that the actual values from an object may be included in its description.

    [DebuggerDisplay("a={a}, b={b}, ValueTotal={CalculateValues()}")]
    public class AddValues
    {    
        public int a { get; set; }
        public int b { get; set; }
        
        public int CalculateValues()
        {
            return a + b;
        }
    }
    

    You also have the ability to include simple expressions, like so:

    [DebuggerDisplay("a={a}, b={b}, ValueTotal={CalculateValues() * 2}")]
    

    In addition to the “DebuggerHidden” and DebuggerDisplay attributes, .NET contains some very useful attributes that modify the behaviour of a debugger. For me, they weren’t as interesting as the two debugger attributes I listed above. :-)

  • A little while back I needed to create a comma-delimited string to parse into my SQL Query. My first attempt in creating my comma-delimited string involved using a StringBuilder class and appending a comma at the end of each of my values via a loop. However, I found that my application would error when parsing my comma-delimited string into my SQL query due to the fact a comma was added to the end of my string.

    After some research on the MSDN website to solve my problem I found a solution and it was simpler than I thought. The .NET Framework already has a class called CommaDelimitedStringCollection and it is pretty simple to use as the following example shows:

    using System.Configuration;
    public partial class CommaPage : System.Web.UI.Page 
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Create a collection to parse to CommaDelimitedStringCollection class
            List<string> cars = new List<string>();
            cars.Add("Volvo");
            cars.Add("VW");
            cars.Add("BMW");
            cars.Add("Ford");
            
            //Create instance of CommaDelimitedStringCollection
            CommaDelimitedStringCollection commaCollection 
            = new CommaDelimitedStringCollection() ;
            
            //Iterate through cars collection and add to commaCollection
            foreach (string item in cars)
            {
                commaCollection.Add(item);
            }
            
            //Read out list of values
            Response.Write(commaCollection.ToString());     
        }
    }
    

    The output of the example above would be: "Volvo, VW, BMW, Ford".

    So pretty much the .NET Framework's CommaDelimitedStringCollection class did all the work for me.

    Nice one!

  • Published on
    -
    1 min read

    Is an Arraylist still in use?

    When I first started using ASP.NET 1.1, I always used an Arraylist to iterate through most of my collections. However, when I started using ASP.NET 2.0 I was introduced to Generic Lists. The List<T> class is the generic equivalent of the ArrayList class. It implements the IList<T> generic interface using an array whose size is dynamically increased as required. This means the List class performs much better in most cases and more importantly it is "type" safe.

    So I am not too sure why you would ever need to use an Arraylist since a Generic List class is able to do exactly the same thing with the added benefit of extra perfomance. So is the Arraylist still widely used in todays standards? I guess it still must be in use if Microsoft has not omitted it from their Framework. Maybe Microsoft has something in store for the Arraylist in their grand plan.

    Here are a few useful links:

    C# Corner - C# Generics Josh Williams MSDN Blog - Arraylist vs. Generic List MSDN Network - List (T) Generic Class

  • Published on
    -
    1 min read

    Inline If Statement

    Standard IF statements are great. But I found that when I am using very simple conditions within my IF Statement I waste a lot of space in my code.

    Example 1:

    public int IfExample(bool bolFlag)
    {
    int result = 0;
    if (bolFlag)
    {
    result = 1;
    }
    else
    {
    result = 2;
    }
    return result;
    } 
    

    There is no problem using Example 1. But there is a much quicker and less tedius way of using a simple conditional IF statement.

    Example 2:

    public int IfExample(bool bolFlag)
    {
    return (bolFlag) ? 1 : 2;
    }
    

    This example is basically saying: "return if (bolFlag) 1 else 2". So you are in theory assigning the IF condition to the variable.

    I know it takes a little while to understand the syntax. But it is really good for those less complex IF conditions.

  • Published on
    -
    1 min read

    C# NULL Coalescing Operator

    Here is a really neat trick that a mate showed me at work. It is a way to assign one variable to another, but only if the variable is not null. If it is null, you want to populate the target variable with perhaps another value.

    For example, lets assume we have an integer variable "intCounter". We could check if the integer contents was null, and if not return another value:

    int intCounter = 5;
    int intResult = intCounter ?? 0;
    // Output: intResult == 5 
    

    We got the following output because intCounter did not contain a null.

    The C# NULL coalescing operator also works with string variables as well:

    string strMessage = "Hello World";
    string strResult = strMessage ?? "No message";
    // Output: strResult == "Hello World" 
    


    So we can see from the two examples above that this NULL Coalescing operator is quite useful. Here is an example of what would have happened if a variable was null:

    string strMessage = null;
    string strResult = strMessage ?? "No message";
    // Output: strResult == "No message" 
    

    Scott Guthrie talks more about this in his own blog and how to use this feature in LINQ: http://weblogs.asp.net/scottgu/archive/2007/09/20/the-new-c-null-coalescing-operator-and-using-it-with-linq.aspx