Click here to Skip to main content
15,913,685 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
in c++ to declare variable,just write like this,int x=10;
i recently moced to c#.i found in variables declaration we are using get set
,what is the use of this,cant we declare variables directly like c++.
can any one give me clear example of this.
thanks
Posted

i think access specifiers and accessors are different things know?
well have a look at :
http://msdn.microsoft.com/en-us/library/aa287786%28v=vs.71%29.aspx[^]

and http://msdn.microsoft.com/en-us/library/w86s7x04.aspx[^] also
for more information
 
Share this answer
 
v2
Comments
satishmachineni 6-Apr-12 6:58am    
thanks for replying i got some
We can declare variables in the same way:
C#
int myInt = 6;
string myString = "hello";
These are called fields

When you use the get and set accessors, you are declaring it as a property which is a very different animal. A property is a a set of methods that are called when a variable is accessed - the get method is called when you fetch the value and the set method is called when you assign a value.

This is a lot more flexible: not only can you have a public getter so anyone can get the the value, you can add a private (or protected, or internal) setter to prevent changes outside your class.
You can also do anything within the get and set methods - you can build your string variable from a number of sources:
C#
private string firstName;
private string secondName;
public string Name
   {
   get { return firstName + " " + secondName; }
   set 
      {
      string[] parts = value.Split(' ');
      firstName = parts[0];
      secondName = parts[1];
      }
   }
public string Email
   {
   get { return firstName + "." + secondName + "@myCompany.com";
   }
This helps to keep the internals of your class away from the class that is using them.


[edit]Oops! Forgot to declare string array... :O - OriginalGriff[/edit]
 
Share this answer
 
v2
Comments
satishmachineni 6-Apr-12 6:43am    
thanks cleared most of my doubts
satishmachineni 6-Apr-12 6:48am    
can u tell me what is parts here
OriginalGriff 6-Apr-12 7:03am    
It's an array of strings to hold the parts of the string when it is broken at the space by the Split method.
I've modified the example to declare it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900