Properties , As there are lot of things going on in my life regarding hike in Bangalore properties ,…..
Here I am trying to understand properties in C#
properties are nothing but natural extension of data fields
Here is an simple example which explain diff between code using properties and not using properties .
With out using properties
using System;
class MyClass
{
private int x;
public void SetX(int i)
{
x = i;
}
public int GetX()
{
return x;
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.SetX(10);
int xVal = mc.GetX();
Console.WriteLine(xVal);//Displays 10
}
}
Syntax for properties
{
get
{
}
set
{
}
}
Where
If we use properties, the code sample will be
using System;
class MyClass
{
private int x;
public int propertyValue
{
get
{
return x;
}
set
{
x = value;
}
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.propertyValue = 10;
int xVal = mc.propertyValue;
Console.WriteLine(xVal);//Displays 10
}
}
mc.propertyValue = 10; // calls set accessor of the property propertyValue, and pass 10 as value of the standard field 'value'.
This is used for setting value for the data member x.
.
For more info you can visit this link
http://www.c-sharpcorner.com/UploadFile/rajeshvs/PropertiesInCS11122005001040AM/PropertiesInCS.aspx
No comments:
Post a Comment