Aliasing Data Types in C#

dotnetlogo
One of the secret coding feature in C# is data type aliasing. If you want to use a data type, but think you may need to change to a different data type at some time in the future, define an alias for the data type and use the alias throughout the rest of your code.

Say, for example, that you want to use Int16, but think you may want to change to Int32 later. You could define an alias for Int16.

using ChangeableType = System.Int16;

Anywhere in the code that you want to use that data type, use the alias instead.

ChangeableType m_iSomething=1;
Debug.WriteLine(m_iSomething.GetTypeCode());

If you want to later change to System.Int32, simply change the alias, and then all of the other code will recognize the new type.

using ChangeableType = System.Int32;

A more common use of this technique is in cases where you don’t know the name of the class that you need because another developer is developing that class. You can create a stub for the class, define an alias for the class name, and your application will run. When you get the new class, all you need to do is substitute it in for your stub and change the class name in the alias.

Improving String Management with StringBuilder

dotnetlogo
Strings are immutable. In other words, a string cannot be changed once it is assigned. When you append a string to an existing string, the .NET Framework actually creates a new string containing the original string and the appended string. If you are thinking that this takes extra processing time, you are correct.

String concatenation has been optimized, so minimal amounts of concatenation won’t have a noticeable impact on performance. The impact is noticeable if you are appending a lot of strings; for example, if you are appending many strings to build ASP.NET page contents or to build message text.

string sMessage = “This is a message”;
sMessage += ” for user ”
sMessage += sUserName;

In this example, it appears that an sMessage string is created, and then additional strings are appended to sMessage, modifying the original string. But that is not what is actually happening. In the first line of the example, the string is created and assigned the default value (“This is a message”). In both the second and third lines of the example, the sMessage string is destroyed (marked for deletion by the garbage collector), and a new sMessage string is created to contain the original string plus the appended string.

If the string concatenation is all done as one assignment, the string is not destroyed between concatenations, and there is no performance impact.

string sMessage = “This is a message” + ” for user ” + sUserName;

However, when concatenating many long strings or building entire ASP.NET page contents using concatenation, appending all of the strings with one assignment may not be practical (or easily readable).

To minimize the impact of string concatenation on performance when you are concatenating many strings, consider using the StringBuilder class. The StringBuilder class creates a string-like object that can be changed. When you have made all of the necessary changes to the string, you can convert the StringBuilder class value to an actual string.

using System.Text;
StringBuilder sbMessage = new StringBuilder(“This is a message”);
sbMessage.Append(” for user “);
sbMessage.Append(sUserName);
string sMessage = sbMessage.ToString();

This sample code creates an instance of the StringBuilder class. It then uses the Append method of the StringBuilder class to append text to the StringBuilder. When all of the concatenations are done, the ToString method converts the StringBuilder to a String type. The StringBuilder class has other methods, such as Insert and Replace, to perform various operations on the string.

StringBuilder provides more efficient string concatenation because it creates a buffer that is large enough to contain the original string plus additional space to provide room for the string to grow. However, if the concatenations fill the extra space in the buffer, the buffer size must be extended, causing another performance hit.

Use the EnsureCapacity method of the StringBuilder class to further improve performance. EnsureCapacity allows you to set the size of the StringBuilder buffer to the expected size of the final string length. Then StringBuilder won’t need to expand the size of the buffer, so you’ll avoid a performance hit.

Initializing a StringBuilder object has more of a performance impact than using a string, so you don’t want to use StringBuilder if you are appending only a few strings. The generally recommended cutoff number is five. If you have more than five separate string concatenations, StringBuilder is generally more efficient than appending the strings.

If your string handling needs to perform as efficiently as possible, the only way to know for certain whether using string concatenation or StringBuilder is faster in your situation is to conduct your own performance testing.

Any time you see a lot of string concatenation in your code, consider using the StringBuilder class for better performance.

Creating a New Xml Document from Scratch in C#

dotnetlogo
To create a new XmlDocument, start by creating an XmlDocument object. The XmlDocument object contains CreateElement and CreateAttribute methods that are used to add nodes to the XmlDocument object. The XmlElement contains the Attributes property, which is an XmlAttribute-Collection. The XmlAttributeCollection inherits from the XmlNamedNodeMap class, which is a collection of names with corresponding values.
The following code shows how an XmlDocument can be created from scratch and saved to a file:

protected void Button1_Click(object sender, EventArgs e)
{ //Declare and create new XmlDocument XmlDocument xmlDoc = new XmlDocument();
XmlElement el;
int childCounter;
int grandChildCounter;
//Create the xml declaration first
xmlDoc.AppendChild(
xmlDoc.CreateXmlDeclaration(“1.0”, “utf-8”, null));
//Create the root node and append into doc
el = xmlDoc.CreateElement(“myRoot”);
xmlDoc.AppendChild(el);
//Child Loop
for (childCounter = 1; childCounter <= 4; childCounter++)
{
XmlElement childelmt;
XmlAttribute childattr;
//Create child with ID attribute
childelmt = xmlDoc.CreateElement(“myChild”);
childattr = xmlDoc.CreateAttribute(“ID”);
childattr.Value = childCounter.ToString();
childelmt.Attributes.Append(childattr);
//Append element into the root element
el.AppendChild(childelmt);
for (grandChildCounter = 1; grandChildCounter <= 3; grandChildCounter++)
{
//Create grandchildren childelmt.AppendChild(xmlDoc.CreateElement(“GrandChild”));}}
//Save to file
xmlDoc.Save(MapPath(“XmlDocumentTest.xml”));
}

This code started by creating an instance of an XmlDocument. Next, the XML declaration is created and placed inside the child collection. An exception is thrown if this is not the first child of the XmlDocument. The following is the XML file that was produced by running the code sample:

<?xml version="1.0" encoding="utf-8"?>
<myRoot>
<myChild ID="1">
<GrandChild />
<GrandChild />
<GrandChild />
</myChild>
<myChild ID="2">
<GrandChild />
<GrandChild />
<GrandChild />
</myChild>
<myChild ID="3">
<GrandChild />
<GrandChild />
<GrandChild />
</myChild>
<myChild ID="4">
<GrandChild />
<GrandChild /> <GrandChild /> </myChild></myRoot>

kick it on DotNetKicks.com