Click here to Skip to main content
15,893,508 members
Articles / Programming Languages / C#

Default Extension Methods

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
10 Aug 2011CPOL1 min read 17.7K   2  
Discussion about default extension method

In this post, I am going to discuss about Default extension method(s) which are useful when we query the data form the collection, array or when performing operation while coding using linq to SQL.

In the .NET Framework, there are number of extension methods which allows perform function on the collection. But the problem arises when we don't know the collection or array empty or there is no element after we apply filter.

Methods like .First<t>(), .Last<t>(), .Single<t>() always throws exception InvalidOperationException when object collection is empty or if there is no element available after applying filter condition.

C#
List<int> lstInt = new List<int>(new int[] {15,11,20,30});
var data = lstInt.Single(i => i < 10);

Default Methods

To avoid the exception, .NET Framework has default methods like .FirstOrDefault<t>(), .LastOrDefault<t>(), .SingleOrDefault<t>(), which return the default value if there is no element in the collection or array is empty.

C#
List<int> lstInt = new List<int>(new int[] {15,11,20,30});
var data = lstInt.SingleOrDefualt(i => i < 10);
if (data == 0)
{
   Console.WriteLine("No element found");
}

What if I have collection which is empty and apply the default method, it will return Null value.

C#
class Employee
{
        public string Name { get; set; }
        public int Age { get; set; }

        public static void GetEmployee()
        {
            List<Employee> lstEmp = new List<Employee>();
            var lst = lstEmp.SingleOrDefault();
            if (lst == null)
              Console.WriteLine("list is empty");
        }
}

But I want to display the default value if collection is empty. So for the solution .NET Framework provided method DefaultIfEmpty() which allows to do so.

C#
class Employee
{
        public string Name { get; set; }
        public int Age { get; set; }

        public static void GetEmployee()
        {
            List<Employee> lstEmp = new List<Employee();
            Employee defualtEmp = new Employee() { Name = "defualt", Age = 0 };
            var lst = lstEmp.DefaultIfEmpty(defualtEmp).Single();
            
            Console.WriteLine("Employee :" + lst.Name);
        }
}

The above method is also helpful when I am apply filter on the collection and collection is empty.

C#
public static void GetEmployee()
{
            List<Employee> lstEmp = new List<Employee>{
                                new Employee(){Name = "Pranay",  Age =25 },
                                new Employee(){Name = "Krunal", Age = 26},
                                new Employee(){Name = "Hanika", Age = 26} 
            };

            Employee defualtEmp = new Employee() { Name = "defualt", Age = 0 };

            var emp = lstEmp.Where(e=>e.Age<20).DefaultIfEmpty(defualtEmp);
            foreach(Employee e in emp)
            Console.WriteLine("Fond Employee: " + e.Name);
}

The above code is the example but it's very helpful when I am binding collection with the list controls.

Summary

The default methods play an important role when we code with the collection or with the linq to SQL or linq to XML and we don't know whether the collection is empty or not. You can get detailed information about the methods on MSDN.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India

Microsoft C# MVP (12-13)



Hey, I am Pranay Rana, working as a Team Leadin MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.

For me def. of programming is : Programming is something that you do once and that get used by multiple for many years

You can visit my blog


StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr

Awards:



Comments and Discussions

 
-- There are no messages in this forum --