Property
-
private int m_number; public int My_NUM { get{ return m_number;} set{m_number=value;} } ---------- public int M_NUM2 { get; set; } when we can use of second way why we need to use of first way? Thanks
The second way internally creates a version that matches the first, so in this simple case there's no need to do the first one. If your logic needs to do more though, then it becomes important to have the first form. The typical case here is where you have a property that needs to raise a
PropertyChanged
event when the value changes - you have to trigger this logic from the setter, so you need to do this.Forgive your enemies - it messes with their heads
My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility
-
private int m_number; public int My_NUM { get{ return m_number;} set{m_number=value;} } ---------- public int M_NUM2 { get; set; } when we can use of second way why we need to use of first way? Thanks
As Pete already said, the second way is a shorthand for what you have in the first way, however the first way is much more powerful as you can add statements to the get and or the set method, maybe checking an input value and throwing an exception when it is unacceptable; maybe recalculating or repainting something (that is what the TextBox.Text setter would do). :)
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.
-
private int m_number; public int My_NUM { get{ return m_number;} set{m_number=value;} } ---------- public int M_NUM2 { get; set; } when we can use of second way why we need to use of first way? Thanks
Second way is property declaration in C# 3.0, for C# 2.0 you have to strict with first implementation. If you want to do some validation in (get) and (set) then second way should not work. Like, on saving (set) a value you would like to check then you have to write validation code in set block.
private int m_number;
public int My_NUM
{
get{ return m_number;}
set{
if (value > 0)
m_number=value;
}
}Regards Rushi
-
private int m_number; public int My_NUM { get{ return m_number;} set{m_number=value;} } ---------- public int M_NUM2 { get; set; } when we can use of second way why we need to use of first way? Thanks
The second form is also called as Auto Property.