Friday, April 4, 2014

Default if Empty...

In this tutorial, will go over using DefaultIfEmpty() in Linq to Objects to handle values when none found.

For this example, I created a sample windows application and wrote the following line of code to test.

In the above code, I had declared a List of type string without adding any values. When I try to access the first value, it is going to throw exception and say none found. Before handling them with try / catch there is another way to add one more step of validation before accessing it.


Above image captures an exception thrown when accessing data in an empty object. In this scenario, there is always an option to use a default value, when no items found. For example, see the image below...

To handle this situation, I had introduced the option to provide Empty string as substitute when list contains no items. Now, when I run the sample code, the output message box will be....


Here, the messagebox displays the default value i.e. empty string. Now lets add some values and try to run the same.


In the above scenario, I added two values to the list item and invoking it will give me the result as User1 (first item in the list). Also, you can use any string value to replace empty string to validate null situations.

Happy coding...

No comments:

Post a Comment