Good practice for initializing properties?

I have a class property that is a list of strings, List. Sometimes this property is null, or if it is set, but the list is empty, then count is 0. However, in another place in my code I need to check if this property is set, so currently my code checks if it is null and it is considered 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 initialize the property so that it is never null?

+3
source share
9 answers

When I have List as a property, I usually have something similar to the following (this is not a safe stream of code):

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

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

null, , . .

+5

Null Pointer, Null null - , .

+4

, , , , , , , .

, .

+1

, . count.

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

ICollection, ,

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;
}
+1

( , ):

  • NullOrNoElement. Pro: , . Con: , .
  • . Pro: . : , ( , )
  • Lazy initialize Pro: , . : .
private List<string> lp = null;
public List<string> ListProp 
{ 
    get 
    { 
        if(lp == null) 
            lp = new List<string>(); 
        return lp; 
    } 
}
+1

IF

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

,

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

, , .

0

, . . . , , .

0

Good question. I would add the objectA FoldersNullOrEmpty () method, which can be used, for example,

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

I almost always initialize lists and even make sure they cannot be set to null if they are available to any setters. This greatly simplifies their use.

0
source

Source: https://habr.com/ru/post/1742321/


All Articles