简体   繁体   中英

Class initialization - Property vs Field

I was wondering what's the best practice for class initialization .

One can write:

private myClass mc = new myClass();

Or:

private myClass mc { get; set; }

public Foo()
{
    mc = new myClass();
}

I always tend to use it as a field . Are there any downsides for using a class as a property ? I did some searching on google but none of the results gave me a good answer for this specific question.

If it's private, there's no significant benefit in making it a property. I'd just keep it as a field. I use properties as a way of communicating an API with other classes.

Your use of a property in the second example is unnecessary. You could write it as:

private myClass mc;

public Foo()
{
    mc = new myClass();
}

Properties are meant to be getters/setters, which means they provide a part of the mechanism for information hiding. Making them private doesn't do much, as all methods from the class can see private members.

I perefer the first way:

private myClass mc = new myClass();

because:

  • private properties has no benefit.
  • If you create another constructor, you duplicate the initialization code unless you create some Init method or call this(), which is not as clear as simply initialization the field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM