开发者

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 c开发者_C百科ollection property in a class. Is there a way to do it automatically without using construtor.


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.


One way:

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


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

    // details elided
}

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


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


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>()); } }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜