user496949
user496949

Reputation: 86135

can we initlize the collection property when we declare it in a class

Normally I found I have null reference error caused by I forgot to initialize the collection property in a class. Is there a way to do it automatically without using construtor.

Upvotes: 1

Views: 104

Answers (5)

Marc Gravell
Marc Gravell

Reputation: 1063338

A subtle variation that defers the lists construction - useful for some scenarios involving WCF (which skips both the constructor and field initializers) without needing deserialization callbacks:

public class MyType
{
    private List<string> items;
    public List<string> Items { get {
        return items ?? (items = new List<string>()); } }
}

Upvotes: 1

Doug Moscrop
Doug Moscrop

Reputation: 4544

He's asked without a constructor, so I think the answer is no - I'm imaginging that he's maybe looking for the way you (inaccurately) perceive a C++ class declared on the stack vs heap - the way you delcare a variable on the stack gives the illusion that a constructor is not being called when you look at it syntatically to languages that do not have pointers vs. object references.

I am new to dependency injection and so I am uncertain, but perhaps something could be done that way, effectively autowiring all your collections?

Edit: but really - why? Write a few unit tests to assert no nulls or something. Forgetting to construct member variables strikes me as being very low on the "things I need to be done for me and just the way I want" totem

Upvotes: 1

Jason Li
Jason Li

Reputation: 1585

private List<string> _names = new List<string>();

public List<string> Names
{
    get {return _names;}
    set {_names = value;}
}

If you want to use

public List<string> Names { get; set; }

directly, I have no idea except using constructor.

Upvotes: 4

jason
jason

Reputation: 241701

public class Foo {
    List<int> list = new List<int>();

    // details elided
}

Now list is never null when any of your instance methods are executing.

Upvotes: 1

Gabe
Gabe

Reputation: 50503

One way:

List<string> myList = new List<string>();

Upvotes: 1

Related Questions