Search code examples
c#listdeclarationdefinition

Is defining a must or not?


public List<ItemData> itemBase; When i declare this list i can use it without definition is there benefit in defining while declaring variable?

public List<ItemData> itemBase = new List<ItemData>();

I'd be very grateful if someone could explain.

EDIT:

public List<ItemData> itemBase;
    
    
        ItemData i = new ItemData();
        i.itemName = "dsadsad";
        i.itemSprite = "lolo";
        ItemData i2 = new ItemData();
        i2.itemName = "dsadsad2";
        i2.itemSprite = "lolo2";
        itemBase.Add(i);
        itemBase.Add(i2);

You guys said i can't use .add function but i can use. Yes i define at ItemData i2 but i didn't instantiate list i just instantiate list member.


Solution

  • public List<ItemData> itemBase;
    

    declares a variable of type List<ItemData>. Because List<ItemData> is a reference type, its initial value is null. This is perfectly valid C# code, but if you try to execute a method on it, such as

    itemBase.Add(myItemData);
    

    you will get a null reference exception, because the variable isn't referencing any object on which you can execute the Add method.

    When you then write

    itemBase = new List<ItemData>();
    

    You instantiate an object of type List<ItemData> and assign it to itemBase, and then your call to the Add method will work.

    In C#, the initial (first) assignment of a value to a variable is called initialization.