RSS

Back to Basics: System.String

For such a simple concept, the string class is, in my opinion, one of the most complex classes in the System namespace. The MSDN page for String Class is 53 printed pages excluding the 2 additional pages of comments.

What is System.String?

In the .NET framework, the string type is a reference type. It is not a value type as is often the belief. It is an object that consists of a collection of System.Char values in sequential order. Characters within the string can be referenced as follows:

string foo = "bar";
char r = foo[2];

Immutable

The string type is also immutable. You cannot change the contents of a string without reflection or unsafe code. The methods, operators, etc. that appear to modify a string actually return a new string with the modified contents. The Replace function of the string object is a great example of this. You cannot simply call the Replace method. You have to return the results of the method to a string variable.

string foo = "abc";
foo = foo.Replace("abc", "xyz");

Concatenation and the Compiler

The compiler does some interesting things when working with strings. For example, when concatenating with variables in a single statement:

string foobar = foo + " " + bar;

// compiler sees the above as:
string foobar = string.Concat(foo, " ", bar);

When you use constants such as literals and const string members, the compiler knows that all the parts are constant and it does all the concatenation at compile time, storing the full string in the compiled code.

string foobar = "foo" + " " + "bar";

// compiler sees the above as:
string foobar = "foo bar";

const string foo = "foo";
string foobar = foo + " " + "bar";

// compiler sees the above as:
string foobar = "foo bar";

String.Empty versus “”

And finally, there is a difference between string.Empty and “”. When you use “”, .NET creates an object but when you use string.Empty it does not. The difference may be small, but its a difference that can make a performance impact.

string foo = ""; // creates an object
string bar = string.Empty; // doesn't create an object

 
Leave a comment

Posted by on October 28, 2011 in .NET Development

 

Tags:

Null Coalescing Operator

In C# 2.0, Microsoft introduced the null coalescing operator (??). The ?? operator is a shorthand notation for returning a default value if a reference or Nullable<T> type is null.

The examples below show how the null coalescing operator achieves the same result as traditional conditional statements but with less lines of code. Both sets of examples use property getter methods with assumed fields.

Reference Examples with Conditional Statements

public MyObject MyObjectProperty
{
    get
    {
        if (this.myObject == null)
        {
            return new MyObject();
        }

        return this.myObject;
    }
}

Reference Examples with Null Coalescing Operator

public MyObject MyObjectProperty
{
    get
    {
        return this.myObject ?? new MyObject();
    }
}

Nullable<T> Example with Conditional Statements

public int Number
{
    get
    {
        if (this.nullableNumber.HasValue)
        {
            return this.nullableNumber.Value;
        }

        return 0;
    }
}

Nullable<T> Example with Null Coalescing Operator

public int Number
{
    get { return this.nullableNumber ?? 0; }
}

The main argument against the ?? operator is that developers don’t understand it so it makes the code less readable and maintainable. This is a poor argument in my opinion. As developers, we should never stop trying to improve both ourselves and our teams. This is something that can be taught over lunch one day.

More reading: ?? Operator (C# Reference) – MSDN

 
Leave a comment

Posted by on October 27, 2011 in .NET Development

 

Tags: , , ,

Default Style Sheet v1.0

I’ve been using a reset style sheet for years to smooth out browser inconsistencies but at the start of every project there was always a period of rework. A reset style sheet basically zeros out the styles set by a browser and gives you a blank slate to work with. But what if I don’t want a blank slate over and over again?

That’s where the default style sheet comes in. A default style sheet is zeroes out the styles of a browser but then defines default styles for common HTML elements. There are a few default style sheets out there but I’ve always found they didn’t default enough elements. The following link will take you to a zip file download containing my version of a default style sheet.

Default CSS v1.0 (.zip)

My thanks go out to the following:

 
1 Comment

Posted by on October 19, 2011 in Web Development

 

Tags: , ,

Another Reason to Use Google+

Unlimited free storage unless you take pictures at a really, really high resolution. There are 2 articles on the picasa web albums support section that are of interest.

The first is entitled How It Works and states:

Picasa Web provides 1 GB for photos and videos. Files under certain sizes don’t count towards this limit.

The second is entitled Free Storage Limits and it states the following:

If you’ve signed up for Google+

Free storage limits

Photos up to 2048 x 2048 pixels and videos up to 15 minutes won’t count towards your free storage.

Automatic resizing

All photos uploaded in Google+ will be automatically resized to 2048 pixels (on their longest edge) and won’t count towards your free storage quota.

All photos uploaded to Picasa Web Albums over the free size limit will count towards your 1 GB of free storage. When you reach your storage limit, any new photos you upload to Picasa Web larger than the free size limit will be automatically resized to 2048 pixels (on their longest edge).

If you haven’t signed up for Google+

Free storage limits

Photos up to 800 x 800 pixels and videos up to 15 minutes won’t count towards your free storage.

Automatic resizing

All photos uploaded over the free size limit will count towards your 1 GB of free storage. When you reach your storage limit, any new photos you upload to Picasa Web larger than the free size limit will be automatically resized to 800 pixels (on their longest edge).

That’s right you read that right. If you’re a Google+ member, you get over double the resolution free.

 
Leave a comment

Posted by on October 7, 2011 in Personal Computing

 

Tags: ,

HTML5 and target=”_blank”

I posted a jQuery solution to the XHTML Strict Target=”_blank” problem a while back. Well I finally had some free time to start delving deep into HTML5. Low and behold the W3C has removed the deprecated status from the “_blank” value for the target attribute. What does that mean?

That means that target=”_blank” is 100% valid in HTML5!

 
2 Comments

Posted by on September 24, 2011 in Web Development

 

Tags: ,

Get a String from a MemoryStream

The MSDN article for MemoryStream has this example of outputting a string to the console.

private static void Main(string[] args)
{
    int count;
    byte[] byteArray;
    char[] charArray;
    UnicodeEncoding uniEncoding = new UnicodeEncoding();

    // Create the data to write to the stream.
    byte[] firstString = uniEncoding.GetBytes("Invalid file path characters are: ");
    byte[] secondString = uniEncoding.GetBytes(Path.GetInvalidPathChars());

    using(MemoryStream memStream = new MemoryStream(100))
    {
        // Write the first string to the stream.
        memStream.Write(firstString, 0 , firstString.Length);

        // Write the second string to the stream, byte by byte.
        count = 0;
        while(count < secondString.Length)
        {
            memStream.WriteByte(secondString[count++]);
        }

        // Write the stream properties to the console.
        Console.WriteLine(
            "Capacity = {0}, Length = {1}, Position = {2}\n",
            memStream.Capacity.ToString(),
            memStream.Length.ToString(),
            memStream.Position.ToString());

        // Set the position to the beginning of the stream.
        memStream.Seek(0, SeekOrigin.Begin);

        // Read the first 20 bytes from the stream.
        byteArray = new byte[memStream.Length];
        count = memStream.Read(byteArray, 0, 20);

        // Read the remaining bytes, byte by byte.
        while(count < memStream.Length)
        {
            byteArray[count++] = Convert.ToByte(memStream.ReadByte());
        }

        // Decode the byte array into a char array
        // and write it to the console.
        charArray = new char[uniEncoding.GetCharCount(byteArray, 0, count)];
        uniEncoding.GetDecoder().GetChars(byteArray, 0, count, charArray, 0);
        Console.WriteLine(charArray);
    }
}

I have a problem with code examples that try and do too much. Here is a much less complex example of writing a string to the console from a MemoryStream.

private static void Main(string[] args)
{
    using (var memoryStream = new MemoryStream(100))
    using (var streamWriter = new StreamWriter(memoryStream))
    using (var streamReader = new StreamReader(memoryStream))
    {
        var invalidPath = new string(Path.GetInvalidPathChars());
        streamWriter.WriteLine("Invalid file path characters are:");
        streamWriter.WriteLine(invalidPath);

        streamWriter.Flush();
        memoryStream.Position = 0;

        var stringToOutput = streamReader.ReadToEnd();
        Console.WriteLine(stringToOutput);
    }
}

 
Leave a comment

Posted by on September 9, 2011 in .NET Development

 

Tags: ,

Visual Studio Add-ons

I’ve been getting the same question a lot lately. What plugins, enhancements, extensions, etc. do you use in Visual Studio? So here’s the surprisingly short list:

ReSharper

The ReSharper website says:

ReSharper is a renowned productivity tool that makes Microsoft Visual Studio a much better IDE. Thousands of .NET developers worldwide wonder how they’ve ever lived without ReSharper’s code inspections, automated refactorings, blazing fast navigation, and coding assistance.

I can tell you the “.NET developers worldwide wonder how they’ve ever lived without ReSharper” is completely true. Once you learn to use it, you’ll never want to code without it. I remember the first week I used it I was angry at myself for waiting so long to get my hands on it.

Links:

StyleCop

The official product description reads:

StyleCop analyzes C# source code to enforce a set of style and consistency rules. It can be run from inside of Visual Studio or integrated into an MSBuild project. StyleCop has also been integrated into many third-party development tools.

The ability to run a tool and have it tell you where to fix your styling is invaluable. Create a custom configuration file (agreed upon by the team of course) and then share it with your team or even better integrate it into you build server. This will ensure that a field is formatted like a field should be consistently in every file. No more style switches per file.

Oh and by the way, the latest release works with ReSharper to allow for quick cleanup of any errors found.

Links:

Search References

How and why the functionality of this gallery extension isn’t built into Visual Studio completely baffles me. This simple extension adds a search box to the top of the .Net tab on the Add References dialog.

Links:

Snippet Designer

If you write code that is structurally the same over and over again, you should learn to build snippets. If you want to build snippets, you want to take a look at this extension. Snippet Designer allows you to highlight code and export as snippet. It has a great GUI for adding in replacement sections, setting the properties of your snippet, etc.

Here is a screenshot of Snippet Designer being used to edit my null coalescing operator snippet.

Links:

 
Leave a comment

Posted by on August 26, 2011 in .NET Development

 

Tags: , , , ,

Calculate Elapsed Time in .NET

I came across this while preparing an upcoming blog entry and felt the need to share. I was looking for a way to calculate the time of an operation. I searched over and over again only to find the following pattern:

DateTime startTime = DateTime.Now;
// do operation
DateTime endTime = DateTime.Now;
TimeSpan runTime = endTime - startTime;

Unfortunately, this pattern isn’t very accurate and rarely outputs anything other than zero on simple operations. I needed to output elapsed time for even these simple operation so I kept searching until finally I came across the System.Diagnostics.Stopwatch class. The code is more readable and (after a bit of testing) is capable of tracking the elapsed time of simple operations.

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// do operations
stopwatch.Stop();
TimeSpan runTime = stopwatch.Elapsed;
long runTimeMilliseconds = stopwatch.ElapsedMilliseconds;
long runTimeTicks = stopwatch.ElapsedTicks;

Hopefully, putting this out there will help people find this method much quicker than I did. And as my mother used to tell me: just because everyone else does it, it doesn’t make it right.

 
Leave a comment

Posted by on June 23, 2011 in .NET Development

 

Tags:

SP 2010 Site Collection PowerShell Script

The following script is what we’ve been using to create site collections with their own database in SharePoint 2010.

Add-PSSnapin Microsoft.SharePoint.PowerShell –ErrorAction SilentlyContinue

## Configure the script
$databaseName = "SP_Content_Database_Name"
$webApplicationUrl = "http://localhost"
$siteCollectionUrl = "http://localhost/sites/its"
$siteCollectionName = "Site Collection Name"
$siteCollectionOwner1 = "DOMAIN\user1"
$siteCollectionOwner2 = "DOMAIN\user2"
$siteCollectionTemplate = "STS#1"

## Create the database
New-SPContentDatabase -Name $databaseName -WebApplication $webApplicationUrl

## Create the site collection
New-SPSite -URL $siteCollectionUrl -OwnerAlias $siteCollectionOwner1 -SecondaryOwnerAlias $siteCollectionOwner2 -ContentDatabase $databaseName -Name $siteCollectionName -Template $siteCollectionTemplate

If you need a list of site templates available on the machine you can run:

Get-SPWebTemplate | Sort-Object "Title"

 
Leave a comment

Posted by on June 9, 2011 in Microsoft SharePoint

 

Tags: ,

Video: Code Monkey

Oldie but goodie for my coding friends.

 
Leave a comment

Posted by on June 7, 2011 in Uncategorized

 

Tags:

 
Follow

Get every new post delivered to your Inbox.