www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons C# Properties Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
C# has formalized the concept of getter / setter methods. The relationship between a get and set method is inherent in C#, whereas it has to be maintained in Java or C++. For example, in Java and C++ we will have to write code similar to the one shown below:

public int getSize() {
return size;
}

public void setSize (int value) {
size = value;
}

foo.setSize (getSize () + 1);


In C# we can define a property and use the same as if we were using a public variable. This is shown below:

public int Size {
get {return size; }
set {size = value; }
}

foo.size = foo.size + 1;

Note: You can write as many C# statements within get { } and set { } as you need. The value is a keyword and when you assign a value to a property, the compiler provides the assigned value in the 'value' identifier. You can also implement a property as read only or write only. Examples are presented below:

public int Size {// write only property
set {size = value; }
}

public int Size { // read only property
get {return size; }
}


The rule is very simple i.e. if you do not implement the get part of a property, it is a write only property. On the other hand, if you do not implement the set part of a property it is a readonly property.
Next >>> Lesson No. 10: C# Pointers







Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.