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
ksd123Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Éric MoreauSenior .Net ConsultantCommented:
not sure abut Enum but everything else seems OK. Enum is normally an integer value.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ste5anSenior DeveloperCommented:
Use Contracts.
ksd123Author Commented:
Eric,

Apart from Enum , can I use IList of ids (int)  and  IEnumerable of dates as well ?
Exploring SQL Server 2016: Fundamentals

Learn the fundamentals of Microsoft SQL Server, a relational database management system that stores and retrieves data when requested by other software applications.

käµfm³d 👽Commented:
Since you used Object as the parameter type, then your method should work with everything, Personally, I'd opt for a generic method, but I think for this task Object is probably fine.
käµfm³d 👽Commented:
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.
Vikram Singh SainiSoftware Engineer cum AD DeveloperCommented:
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. :)
ste5anSenior DeveloperCommented:
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

ksd123Author Commented:
Thank you all
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.