Rubans
Rubans

Reputation: 4478

Good practices for initialising properties?

I have a class property that is a list of strings, List. Sometimes this property is null or if it has been set but the list is empty then count is 0. However elsewhere in my code I need to check whether this property is set, so currently my code check whether it's null and count is 0 which seems messy.

if(objectA.folders is null)
{
    if(objectA.folders.count == 0)
    {
      // do something
    }
}

Any recommendation on how this should be handled? Maybe I should always initialise the property so that it's never null?

Upvotes: 3

Views: 301

Answers (9)

sidney.andrews
sidney.andrews

Reputation: 5256

You could always initialize the property so it's an empty List. Then you can just check the count property.

List<String> Folder = Enumerable.Empty<String>();

I once wrote an extension method for ICollection objects that checked if they were null or empty

public static Boolean IsNullOrEmpty<T>(this ICollection<T> collection)
{
    return collection == null ? true : collection.Count() == 0;
}

public static Boolean IsPopulated<T>(this ICollection<T> collection)
{
    return collection != null ? collection.Count() > 0 : false;
}

Upvotes: 1

Foxfire
Foxfire

Reputation: 5755

You have three options (and you need to decide based on your project):

  1. Create a method to check for NullOrNoElements. Pro: Allows both null and no entries. Con: You have to call it everywhere you want to use the property.
  2. Preinitialize with a list. Pro: Thread-save and very easy. Con: will use memory even when not used (depending on how many instances you have this may be a problem)
  3. Lazy initialize Pro: Does only use memory when really used. Con: NOT thread save.
private List<string> lp = null;
public List<string> ListProp 
{ 
    get 
    { 
        if(lp == null) 
            lp = new List<string>(); 
        return lp; 
    } 
}

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245429

When I have List as a property, I usually have something that looks like the following (this is not a thread safe piece of code):

public class SomeObject
{
    private List<string> _myList = null;

    public List<string> MyList
    {
        get
        {
            if(_myList == null)
                _myList = new List<string>();
            return _myList;
        }
    }
}

Your code would then never have to check for null because the Property would be initialized if used. You would then only have to check for the Count.

Upvotes: 5

Nick Gotch
Nick Gotch

Reputation: 9407

I almost always initialize lists and even make sure they can't be set to null if exposed by any setters. This makes using them much easier.

Upvotes: 0

James Westgate
James Westgate

Reputation: 11444

Its a good question. I would add a method to objectA FoldersNullOrEmpty() that you can use eg

public virtual FoldersNullOrEmpty()
{
   return (folders == null || folders.count == 0)
}

Upvotes: 0

Alex Khvatov
Alex Khvatov

Reputation: 1485

Right now your code will Always throw a Null Pointer exception, you are checking for Null and if it IS null - you're trying to access an object which does not exist.

Upvotes: 4

Kibbee
Kibbee

Reputation: 66122

You could handle this by initializing the object in the constructor. This is usually where this type of thing is done. Although I see nothing wrong with your current code. No point in initializing stuff that doesn't exist yet, it just wastes memory.

Upvotes: 0

Adriaan Stander
Adriaan Stander

Reputation: 166396

You could do this in a single IF

if(objectA.folders is null || objectA.folders.count == 0)

Or you could create a boolean property in the class which checks this status for you and returns a result

public bool objectA.FolderIsNullOrEmpty
{
    get { return objectA.folders is null || objectA.folders.count == 0;}
}

If it does not make a difference to your application, I would rather recomend initializing the List to start with.

Upvotes: 0

Jo&#227;o Angelo
Jo&#227;o Angelo

Reputation: 57688

If for your application the collection being a null reference never has a different meaning than the collection being empty, then yes, I would say you should always initialize it and this way remove the null checks from the remaining code.

This approach only makes sense if the property setter does not allow to change it to a null reference after initialization.

Upvotes: 1

Related Questions