开发者

can we access properties from constructor

开发者 https://www.devze.com 2023-03-24 12:11 出处:网络
I am working on a CSharp code where in constructor i need to access properties of that开发者_开发知识库 class. Logically it looks troublesome to me since i will be accessing properties of the object t

I am working on a CSharp code where in constructor i need to access properties of that开发者_开发知识库 class. Logically it looks troublesome to me since i will be accessing properties of the object that hasn't is still under construction.

Its an old code using c# version 4.0 and i am kind of refactoring it so that's why can't redesign everything from scratch.

Thanks

class employee
{
  employee()
  {
    int square = count * count;
  }
  private int count {get;set;}
} 


There is nothing wrong with that, except that count will always be 0.

There is (almost) no such thing as a "partially-constructed" object in .Net, except for an object that hasn't set all of its state in the constructor.


If you're constructing the class, and none of the properties have been set previously in the constructor and none of the properties are static and set elsewhere, the values will be default or null, so there's no point getting what they contain. Otherwise, the constructor is the perfect place to set your properties to something.


At construction time you may set a property, but unless it has a static member backing the getting or is a value type, you will get a null value until you set it.

public class WhatClass
{
    public WhatClass()
    {
        int theCount = Count; // This will set theCount to 0 because int is a value type
        AProperty = new SomeOtherClass; // This is fine because the setter is totally usable
        SomeOtherClass thisProperty = AProperty; // This is completely acceptable because you just gave AProperty a value;
        thisProperty = AnotherProperty; // Sets thisProperty to null because you didn't first set the "AnotherProperty" to have a value
    }

    public int Count { get; set; }
    public SomeOtherClass AProperty { get; set; }
    public SomeOtherClass AnotherProperty { get; set; }
}


Yes, C# allow this, but sometime better to have private field which is wrapped by public property and in class method work only with field. In your case I would recommend to remove private property and use class field variable instead. If consumers of your class potentially may want to access a property - make it public with a private setter, this kind of autmatic property is an other alternative for privatr field wrapped by a property.

0

精彩评论

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