I am creating some properties and came across a scenario I haven't seen before.
Consider
private double _temperature;
private double _maxTemp;
public double Temperature
{
get { return _temperature; }
set { _temperature = value; }
}
public double MaxTemp
{
get { return _maxTemp; }
set { _maxTemp = value; }
}
public bool IsTempToHigh
{
get
{
if (_temperature < _maxTemp)
return true;
else
return false;
}
}
No problem here but I have a lot of properties in this fashion and I rewrote it into this:
public double Temperature { get; set; }
public double MaxTemp { get; set; }
public bool IsTempToHigh
{
get
{
if (Temperature < MaxTemp)
return true;
else
return false;
}
}
Quite a bit cleaner in my opinion and it seems to works just as fine. However, I nerver seen or noticed anyone using the property names directly in gettes (or setters), so is it safe to use or might there be any pitfalls.
Also why does this compile but gives an StackOverflowException:
public double Value
{
get { return Value; }
set { Value = value; }
}
If you mean in terms of IsTempTooHigh
, that's fine (although the condition is the wrong way round for the name). It's entirely valid to refer to one property within another, although you need to be careful that you don't make it recursive. Your autoimplemented properties still have backing fields - they've just been generated by the compiler for you rather than being present in your source code.
I'd rewrite your computed property without the if
, mind you:
public bool IsTempTooHigh { get { return Temperature >= MaxTemp; } }
Or in C# 6:
public bool IsTempTooHigh => Temperature >= MaxTemp;
As for the stack overflow, it's simplest to imagine they were methods instead:
public double GetValue()
{
return GetValue();
}
public void SetValue(double value)
{
SetValue(value);
}
Can you see why calling either of those would cause a stack overflow? Well, it's just the same for properties - they're just methods with a bit of metadata linking them, basically.
See more on this question at Stackoverflow