.NET Type Of The Day

.NTOD StringBuilder()

Namespace : System.Text

Called the StringBuffer in Java, this type is a great way to dynamically build up a string without the need to use the + operator which concatenates strings together.  Breaking this down, a String is the in memory name for some text, upto 2,147,483,647 characters to be precise.  Adding strings together with the + operator is perfectly do-able in .NET but is not advised as its bad on performance.  Because strings are immutable (meaning they cannot be changed once created), a new string object has to be created for each concatenation that occurs to represent the resulting string.

String myfirstString = “my name is”;  //This creates a string object on the heap and points to it from the stack

String mySecondString = myfirstString + ” Scott”; //A new string object is created

One of the most common uses of string concatenation for me is the dynamic building of a SQL string that uses both literal text (the SQL query) and references to variables being used in the query.  The best way to build such a string is to use the StringBuilder class.  Ensure you are ‘using’ the System.Text namespace in your project.

The reason the string builder class is so useful is because it dynamically creates and destroys a char array on the fly as you append string values to the object. The object has a property called .Capacity which represents the max size of the objects current char array and by default this is 16 characters.  As you create your StringBuilder object and if you have a rough idea of how long your string is going to be,  you can set this property using the constructor.  When you append additional string values onto the StringBuilder object, internally the object checks what capacity is currently set, if the appended string does not exceed the current capacity of the array, then the current array is updated.  If the appended string does exceed the current array capacity, then the StringBuilder object creates a new array, with a higher capacity (well double the current length), copies your current char array into the new one and then destroys the old.  As with standard arrays, you can use the StringBuilders .Length property to check the current char array length.

String tableFQN = “Database.dbo.Customers”;

StringBuilder sb = new StringBuilder(“SELECT * FROM”); //Creates sb object with 16 character array

sb.Append(tableFQN); //Exceeds the default 16 chars and so a new 32 character array is created and the old destroyed

return sb.ToString()//returns SELECT * FROM Database.dbo.Customers as a System.String object

When you are ready to use the value of the object, you must then call the .ToString() method to convert the char array into a string object.  Just remember that strings are immutable where as the StringBuilder is mutable (can be changed).


.NTOD System.Exception

System.Exception is the base class for any other Exception classes in the .NET Framework.  The Exception class is normally thrown automatically by the CLR during code execution and use of the try and catch constructs in the coding promotes good exception handling.  You can also create and throw your own Exception class (it must derive from System.Exception). The below shows how you throw and catch an Exception class in a try and catch block:

The above example throws a basic Exception object (note the new keyword creates one on the heap) and the catch block creates a stack reference (the ex variable) to the object to allow us to access the Exception object members.  The most commonly used member, Exception.Message is a text message that explains what issue has occurred.

You may of be aware of the term, ‘Unhandled Exception’.  These are essentially exceptions that the CLR has raised that have not been caught, or handed in the application that is executing.  The message normally describes the issue and informs you of the Exception type being thrown, for example a ViewStateException, CmdLineException or an ApplicationException, all of which are derived types from the base type System.Exception.

As described above when an Exception object (or any derived Exception object) is caught, we create a variable and access the members of the Exception object.  The most commonly used members include:

There are hundreds of Exceptions in the .Net BCL so trying to attempt to learn them all is a no go.  If you understand the basic members of this base class however and the additional members added with the all important SystemException and ApplicationException classes, you will be in a good place to start handling exceptions in your applications.

.NTOD System.Object

System.Object is the base type in the .NET class library.  All types in .NET inherit from the Object class and so inherit all of its members or what we normally call ‘offering low level services’ to all Types.  By understanding the basic methods offered by the Object you can access these methods in any other type in your code; That said, types will ‘override’ certain members of Object so that they operate slightly differently, I’ve pointed out which of these object members are virtual (can be overridden).  The Object() method is the constructor for this Class.

Important to note is that inheritance of this object in .NET is implied, so you don’t have to worry about writing ‘: Object’ when creating your own types.  The most commonly used members of the Object class are as follows:

myObject.Equals(object) //For reference types, this method checks reference equality (i.e. whether the object heap address is the same) for the object passed.  For value types, a bitwise equality check is carried out (which is just the binary bits of each object being the same).  Response = bool.  As this is a virtual method, it can be overridden in derived classes.

myObject.GetHashCode() //This method generates a number that relates to the value of the object.  So if you have a string and run this method you will generate a numeric value, but if you change the string, running this method will generate a different hash code.  This method is virtual so you can generate your own hashing algorhythm, but its usually best to use values of the object to create the code with.  You should note also that these hash codes do not create globally unique numbers by default unless you override the virtual method and use a GUID in your logic.

myObject.Finalize() // This method is called by the CLR when the object is garbage collected (provided the object has not been marked as ‘exempt’ from finalizing).  Any code you wish to run that cleans up the object code when the object is to be destroyed should be written into this method.   It is a protection method so is only accessible via the type or its derived types (so you can’t call it from another assembly).  By default, this method does nothing, so you have to create implementation code in your derived types yourself.  Is more commonly known as the objects ‘destructor’ as it performs the opposite actions to the objects default/custom constructor method.

myObject.GetType() //This method gets the ‘Type’ of the object instance.  It returns the System.Type object (which is used by the reflection process all of the time) which contains a bunch of members that describe the type, or more specifically provides the meta data about the type. This includes info like name, namespace, whether the type is an array etc.  The type name will be returned by default e.g. BaseClass myBaseClass = new BaseClass();  Console.WriteLine(“MyBaseClass is of type {0} : “, myBaseClass.GetType()) will return “MyBaseClass is of type BaseClass”.

myObject.ToString() //Returns a string object representation of the object value. Note that by default, the fully qualified name of the object is returned. Probably the most frequently used method of the object, well for me anyway.

Getting to know the Object class will help you out in a big way with all other types, e.g. you know you can return any object as a string object.  More tomorrow….

.NTOD (.NET type of the day)

Ok, so I’ve looked for a while for sites or RSS feeds that offer a .NET type of the day.  When learning the basic types in the .NET base class library I would of paid to have an RSS feed that offered some daily blurb on a type in the framework allowing a daily dose of understanding which would build up to a good knowledge of the most important types that could be used to solve programming problems.  Practice when coding is of course the most important part of learning a language on a programming framework like .NET, but knowing which types can solve a particular problem you are working on will make you far more efficient as a developer and make your code more efficient too.

I’m about to be all bold and commit to publishing a .NET type of the day.  The Microsoft MSDN reference for .NET types is of course a good reference point for types and I’ve used it hundreds of times during coding to ensure I’m calling the right method and to check method signatures etc, but it’s not great for demonstrating the practical scenarios where you might use a particular type.  I’ll start with the very basics and build on the previous each day.  I will continue to write more complete articles to this blog and to differentiate between the ‘type of the day’ and standard articles, I will prefix type of the day posts with .NTOD.

Here goes nothing…