Link to home
Start Free TrialLog in
Avatar of ksd123
ksd123

asked on

Checking object null in c#

Hi Experts,

We have so many instances in our code to check if object is null

public void MethodA(FooA foo)
{

if(foo==null)
{
	throw new ArgumentNullException("foo");

}

Open in new window


I was told to write extension method to check if object is null and call this method everywhere and have written following code for this with parameters object and string

public static class ExtesnionObjectHelper
        { 
           public static void VerifyNotNull(this Object targetObject,string message)
          {
              if (targetObject == null)
              {
                  throw new ArgumentNullException(message);
              }
          }
        } 

Open in new window


In the above MethodA now I can simply call like this  foo.VerifyNotNull("foo").

I am little bit confused and have following scenarios and could anyone correct me if I can call the extension method like above for all below scenarios .

1)[b]IEnumerable dates[/b]
public void MethodB(IEnumerable<DateTime> dates)
{
if(dates==null)
{
	throw new ArgumentNullException("dates");
}
dates.VerifyNotNull("dates");  // correct or  wrong
}

2)[b] IList of ids[/b]
public void MethodC(IList<int64> ids
{

if(ids==null)
{
	throw new ArgumentNullException(ids);
}

ids.VerifyNotNull("ids");  // correct or  wrong
}

3)[b]string[/b]
public void MethodD(string username)
{
if(string.IsNullOrEmpty(username)
{
	throw new ArgumentNullException("username");
}
username.VerifyNotNull("username"); // correct or  wrong

4)[b]Enum value[/b]

public void MethodE(this Enum value)
{
if(value==null)
{
	throw new ArgumentNullException("value");
}
value.VerifyNotNull("value");  // correct or  wrong
 }

5)[b]Generic IList<T>[/b]
public void MethodF(IList<TEntity>> action)
{
if(action==null)
{
	throw new ArgumentNullException("action");
}
action.VerifyNotNull("action"); // correct or  wrong
}

6)I[b]Enumerable validationResult[/b]

public void MethodG(IEnumerable<validationResult> results)
{
if(results==null)
{
	throw new ArgumentNullException("results");
}
results.VerifyNotNull("results");  // correct or  wrong
}

Open in new window


Thanks in Advance
ASKER CERTIFIED SOLUTION
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ksd123
ksd123

ASKER

Eric,

Apart from Enum , can I use IList of ids (int)  and  IEnumerable of dates as well ?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
P.S.

Just be careful with this approach. I tried the same exact thing a couple of years back, and when I showed it to my boss, he claimed it made the code less readable. His point was that, prior to the introduction of extension methods, it would never make sense that an object would be able to call a method that verifies that same object is not null--the object doesn't even exist if it's null, so how could it have methods? Functionally speaking, the approach works, but if your teammates don't understand how it works, then you've introduced ambiguity into your code.
I had to agree with käµfm³d.

Someone don't want you to use advance stuff for interest of developers not knowing about that. Because in your absence it might worry them as it will be hard for them to get to root. :)
As I said, use contracts.

When this is too advanced, simply create your own Contract class with you static method and signature. Then it is transparent what it does.

btw, this would also allow that you add simple parameter checks to this class with the same behaviour (raising exceptions). Even you can use more complex tests when you pass lambda expressions to it.

E.g.

namespace ConsoleCS
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    class Contract
    {
        public static void EnsureArgumentIsNotNull(object argument, string message)
        {
            if (argument == null)
            {
                throw new ArgumentNullException(message);
            }
        }

        public static void EnsureArgumentListIsNotEmpty<T>(IEnumerable<T> argumentList, string message)
        {
            Contract.EnsureArgumentIsNotNull(argumentList, message);
            bool result = (argumentList.Count() == 0);
            if (!result)
            {
                foreach (T value in argumentList)
                {
                    if (value == null)
                    {
                        result = true;
                        break;
                    }
                }
            }

            if (result)
            {
                throw new ArgumentException(message);
            }
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            List<int> intList = new List<int>();
            List<object> objectList = new List<object>();

            Console.WriteLine("MethodB(null)");
            try { MethodB(null); } 
            catch (Exception ex) { Console.WriteLine(ex.Message); }

            Console.WriteLine("\nMethodC(null)"); 
            try { MethodC(null); }
            catch (Exception ex) { Console.WriteLine(ex.Message); }

            Console.WriteLine("\nMethodD(null)"); 
            try { MethodD(null); }
            catch (Exception ex) { Console.WriteLine(ex.Message); }

            Console.WriteLine("\nMethodF(intList)");
            try { MethodF(intList); }
            catch (Exception ex) { Console.WriteLine(ex.Message); }

            intList.Add(1);
            Console.WriteLine("\nMethodF(intList)");
            try { MethodF(intList); }
            catch (Exception ex) { Console.WriteLine(ex.Message); }

            Console.WriteLine("\nMethodG(objectList)");
            try { MethodG(objectList); }
            catch (Exception ex) { Console.WriteLine(ex.Message); }

            objectList.Add(null);
            Console.WriteLine("\nMethodG(objectList)");
            try { MethodG(objectList); }
            catch (Exception ex) { Console.WriteLine(ex.Message); }

            Console.WriteLine("\nDone.");
            Console.ReadLine();
        }

        static void MethodB(IEnumerable<DateTime> dates)
        {
            Contract.EnsureArgumentIsNotNull(dates, "Argument dates must not be null."); 
        }

        static void MethodC(IList<int> ids)
        {         
            Contract.EnsureArgumentIsNotNull(ids, "Argument ids must not be null."); 
        }

        static void MethodD(string username)
        {            
            Contract.EnsureArgumentIsNotNull(username, "Argument username must not be null."); 
        }

        static void MethodF(IList<int> ids)
        {
            Contract.EnsureArgumentListIsNotEmpty(ids, "Argument ids must not be null or empty.");
        }

        static void MethodG(IList<object> ids)
        {
            Contract.EnsureArgumentListIsNotEmpty(ids, "Argument ids must not be null or empty.");
        }
    }
}

Open in new window

Avatar of ksd123

ASKER

Thank you all