Property Vs. Public Variable
Properties are better than public variables There are two reasons.
1) Public variables are unsafe, as anyone can set any value and you have no control over them.While in case of property you can put a check that no one could set invalid value to them.
Suppose you have a property Salary..
private int m_iSalary=100;
property int Salary
{
get
{
return m_iSalary;
}
set
{
if(value > 0)
{
m_iSalary=value;
}
else
{
MessageBox.Show("You can not set Negative value in Salary.");
}
}
}
2) We can restrict any one, that he can only get the value but could not set from outside of class and vise versa.
property int Salary
{
get
{
return m_iSalary;
}
private set
{
if(value > 0)
{
m_iSalary=value;
}
else
{
MessageBox.Show("You can not set negative value in Salary.");
}
}
}
But inner access modifier should be more restrictive than main access modifier. We can not define access specifier for both(get and set) in one property, You can set only one at a time. And other will use main access specifier.
In set method value is a keyword you can not use any hard code value or any other variable instead of value keyword.
Subscribe to:
Post Comments (Atom)
Followers
Link
Labels
Agille
(3)
Angular 2
(96)
Architecture
(7)
ASP .Net
(30)
C#/VB .Net
(161)
Entityframework
(11)
General
(33)
Git
(2)
Hosting
(2)
HTML
(4)
Interview
(12)
Interview-Agile
(1)
Interview-Angular
(25)
Interview-ASP .Net
(3)
Interview-C#
(16)
Interview-JavaScript
(1)
Interview-MVC
(30)
Interview-SQL Server
(4)
Interview-WCF
(2)
Islam
(6)
Java Script
(37)
JQuery
(1)
MVC
(53)
NodeJS
(1)
Puzzles
(1)
React-Native
(3)
Security
(1)
Shayri
(10)
SQL Server
(41)
VC++
(5)
WCF
(21)
Web API
(27)
WPF
(21)
2 comments:
Hi
I read this post two times.
I like it so much, please try to keep posting.
Let me introduce other material that may be good for our community.
Source: Property interview questions
Best regards
Henry
Nice article , questions are good and answers are crisp. I have also blogged my experience as Top 20 Core Java Interview questions and answers . let me know how do you find it.
Post a Comment