.Net 4.0 Code Level Enhancements

Lot of new enhancements has been added as the part of .net 4.0. So I decided to collect various such items and explain them with the help of simple examples. This will help developers to make an easy start rather than send time for searching. In this part I am covering the enhancements applied to TimeSpan, String and Enum classes. You can download and run the attached solution to get a more clear idea. I will try to publish more features like this later which is mainly meant to get a quick start for developers.

Once you downloaded and ran the application, the screen would be like below.

1.gif

Each button click will produce the corresponding example output. You won't get any idea from outputs without looking the code written under them. Let me start explaining each of these examples.

TimeSpan class enhancements in .NET 4.0

1. ToString() of TimeSpan included with additional overrides to pass your preferred format. So now you can use ToString() with TimeSpan for making the output a formatted one. Below is the example 

TimeSpan ts = new TimeSpan(2, 30, 25);
MessageBox.Show(ts.ToString("c"), "'c' Format");
MessageBox.Show(ts.ToString("g"), "'g' Format");
MessageBox.Show(ts.ToString("G"), "'G' Format");

Just created a TimeSpan with 2 hours,30 minutes and 25 seconds. Then used the .NET4.0 ToString() to make it a formatted one. Now click on button which is saying "ToString() OverLoads" and you will see below formatted outputs one by one.

2.gif

2. Parse() of TimeSpan can now be used with a format i.e. you can pass a cultureinfo. This overload is newly introduced in .net 4.0. Below is the sample code.

MessageBox.Show(TimeSpan.Parse("2:30:25", new CultureInfo("en-US").DateTimeFormat).ToString("G"));

As you can see, I assed US cultureinfo during Parse() call and output will be like below.

3.gif

String class enhancements in .NET 4.0

1. IsNullOrWhiteSpace() can be used to check that whether the string contains only white spaces rather than a valid item. Based on the checking, method will return a bool. This method is new in .net 4.0. Below is the example I used for demo.

string[] values = { null, String.Empty, "ABCDE",
                      new String(' ', 20), "  \t   ",
                      new String('\u2000', 10) };
foreach (string value in values)
{
    MessageBox.Show(String.IsNullOrWhiteSpace(value).ToString());
}

I declared a string array which contains both mere spaces and valid entries. Then running a loop to fire IsNullOrWhiteSpace() against each items. One interesting thing found is that for Empty item too method returns "True". Below are the outputs.

4.gif

2. Concat() now supports IEnumerable collections through new overloads. So you can concatenate string items from various collections which implements IEnumerable. Below is the code for example

List<string> list = new List<string>();
list.Add("Jaish");
list.Add(" Mathews ");
list.Add(",Author");
string concat = String.Concat(list);
MessageBox.Show(concat, "Concat the List items");
concat = String.Concat(list.Where<string>(section => !section.Equals(",Author")));
MessageBox.Show(concat, "Concat the List items after lambda exression filter");

Here you will get 2 outputs as I coded for 2 scenarios. First scenario is that I directly added items to a List<string> generic type. Then calling the String.Concat() for concatenating all string items inside the specific List<string>. Output will be like below.

5.gif

Second scenario is based on lambda expressionwhich is used to filter the string array and then called Concat(). You will get below output

6.gif
 
3. Join() also now supporting IEnumerable. Below is the code and output from Join() example.

List<string> list = new List<string>();
list.Add("Jaish Mathews");
list.Add("Sandeep Mehtha");
list.Add("Yadhu Nandan");
string join = String.Join(" *** ", list);
MessageBox.Show(join, "Join the List items");
join = String.Join(" *** ", list.Where<string>(section => section.Equals("Jaish Mathews")));
MessageBox.Show(join, "Join the List items after lambda exression filter");

I will publish a separate BLOG with detailed String enhancements in .NET 4.0. It may contain some new methods introduced under StringBuilder class too.

7.gif

8.gif

Enum class enhancements in .NET 4.0

1. HasFlag() is introduced to check the mutual items existence inside 2 objects of the same Enum class. MSDN saying The HasFlag method is designed to be used with enumeration types that are marked with the FlagsAttribute attribute. But for me It's worked without [Flags] even though I used [Flags] in my examples. Below is the example code. 

[Flags]
public enum Products
{
    Product1 = 0,
    Product2 = 1,
    Product3 = 2,
    Product4 = 4,
    Product5 = 8,
    Product6 = 16,
    Product7 = 32
}
Products damaged = Products.Product1 | Products.Product5 | Products.Product7;
Products latestPurchased = Products.Product7;
Products oldestStock = Products.Product6;
MessageBox.Show(damaged.HasFlag(latestPurchased).ToString(), "Has flag True");
MessageBox.Show(damaged.HasFlag(oldestStock).ToString(), "Has flag False");

I am checking the damaged products items inside various other items categories. Below will be the output.

9.gif

2. TryParse() is introduced to check whether a Parse operation was success rather than throwing run time error. 

[Flags]
enum Numbers { One = 1, Two = 2, Three = 3, Four = 4 };
Numbers nbrs;
Enum.TryParse("2",out nbrs);       
MessageBox.Show(nbrs.ToString());

Here parsing the Enum value to get the corresponding name

10.gif

Summary 

I may have missed to cover some enhancements in this article. But those will be considered in another session.

Up Next
    Ebook Download
    View all
    Learn
    View all