c# - Override property or calculate property in constructor -
for example have base class , need property calculated in derived classes.i have 2 variant (someproperty1 , someproperty2):
public class baseclass { public int someproperty1{get;set;} public override int someproperty2{get;set;} } public class derivedclass : baseclass { public derivedclass() { someproperty1 = 100; } public override int someproperty2 { { return 100; } } } the questions best way, someproperty1 or someproperty2?
add base class protected abstract method called calcsomeproperty().
then implement property in terms of calcsomeproperty(). force derived classes implement it.
for example:
public abstract class baseclass { public int someproperty { { return calcsomeproperty(); } } protected abstract int calcsomeproperty(); } alternatively, can make property abstract:
public abstract class baseclass { public abstract int someproperty { get; } } in either case, forcing derived classes implement property calculation.
an advantage of separating calculation protected method (rather using simpler abstract property) can perform caching in concrete property implementation if calculation slow:
public abstract class baseclass { protected baseclass() { _someproperty = new lazy<int>(calcsomeproperty); } public int someproperty { { return _someproperty.value; } } protected abstract int calcsomeproperty(); private readonly lazy<int> _someproperty; }
Comments
Post a Comment