1

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.

DeMama
  • 1,080
  • 3
  • 11
  • 30
  • possible duplicate of [Difference between Property and Field in C# 3.0+](http://stackoverflow.com/questions/653536/difference-between-property-and-field-in-c-sharp-3-0) – Kami Nov 01 '13 at 11:13
  • A third option is that you can write `private myClass mc; public Foo() { mc = new myClass(); }` – dav_i Nov 01 '13 at 11:23
  • 1
    This is not a duplicate. – David Arno Nov 01 '13 at 11:23

4 Answers4

3

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.

Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
  • I missed the fact that the property was private as I've never seen anyone do that before. There is definitely no benefits to private properties. – David Arno Nov 01 '13 at 11:16
  • @DavidArno I deliberately set them to private, because I wanted to know how `class initialization` should be done in a class itself. According to the answers, i'll just stick around with the `field way` :) – DeMama Nov 01 '13 at 11:24
  • @DeMama Good for you :) – David Arno Nov 01 '13 at 11:26
  • I'd make it a property if there was some logic, even internal to the class, which should be isolated to the property. For auto-implemented properties, however, I agree that there's really no tangible benefit. – David Nov 01 '13 at 12:11
0

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

private myClass mc;

public Foo()
{
    mc = new myClass();
}
David Arno
  • 41,717
  • 15
  • 81
  • 129
0

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.

Igor Ševo
  • 5,339
  • 3
  • 31
  • 73
0

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.
Tomas Kubes
  • 21,982
  • 14
  • 105
  • 142