As we saw in the previous post, we encapsulated field-data by prefixing 'private' access modifiers and exposed certain public methods with conditions to access their values or to manipulate their values. The example provided in the previous post can again be seen as follows:
class Company
{
// made field-data private
private string nameOfCompany;
// made a public method to deal with private field-data
public void setName( string name)
{
if(name.Length < 26)
{
nameOfCompany = name;
}
else
{
Console.WriteLine("Sorry name exceeds the character limit");
}
}
//some more methods
}
------------------------------------------------------------------------------------
class Program
{
public static void Main(string[] args)
{
Company objRef = new Company();
//this piece of line will give error as nameOfCompany is declared private
//objRef.nameOfCompany = "any name";
// public method setName(string name) is called to assign value to private field-data
objeRef.setName( "afdasdfahdfklasjflkhjfkjsdskjdfkasjjflkjk");
}
}
-------------------------------------------------------------------------------------
In the above given code, setName(string name) method is one of the different ways to access/manipulate the field data. C# language has provided more constructs to access the private field-data, which I'll show in the next section.
class Company
{
// made field-data private
private string nameOfCompany;
// made a public method to deal with private field-data
public void setName( string name)
{
if(name.Length < 26)
{
nameOfCompany = name;
}
else
{
Console.WriteLine("Sorry name exceeds the character limit");
}
}
//some more methods
}
------------------------------------------------------------------------------------
class Program
{
public static void Main(string[] args)
{
Company objRef = new Company();
//this piece of line will give error as nameOfCompany is declared private
//objRef.nameOfCompany = "any name";
// public method setName(string name) is called to assign value to private field-data
objeRef.setName( "afdasdfahdfklasjflkhjfkjsdskjdfkasjjflkjk");
}
}
-------------------------------------------------------------------------------------
In the above given code, setName(string name) method is one of the different ways to access/manipulate the field data. C# language has provided more constructs to access the private field-data, which I'll show in the next section.
Different ways of accessing encapsulated data
A. Defining a pair of public getter (to get the value of field-data) and setter (to set the value of field-data) methods.
B.1) Different ways the .NET properties are used in coding:
e) automatic properties
No comments:
Post a Comment