- Hands-On Object:Oriented Programming with C#
- Raihan Taher
- 456字
- 2021-07-02 12:44:44
Properties
For security reasons, all the fields of a class shouldn't be exposed to the outside world. Consequently, exposing private fields is done by properties in C#, which are members of that class. Underneath the properties are special methods that are called accessors. A property contains two accessors: get and set. The get accessor gets values from the field while the set accessor sets values to the field. There is a special keyword for a property, named value. This represents the value of a field.
By using access modifiers, properties can have different access levels. A property can be public, private, read only, open for read and write, and write only. If only the set accessor is implemented, this means that the only write permission is given. If both set and get accessors are implemented, this means that both read and write permissions are open for that property.
C# provides a smart way of writing setter and getter methods. If you create a property in C#, you don't have to manually write setter and getter methods for a particular field. Consequently, the common practice in C# is to create properties in a class, rather than creating fields and setter and getter methods for those fields.
Let's take a look at how to create property in C#, as shown in the following code:
class Animal {
public string Name {set; get;}
public int Age {set; get;}
}
The Animal class has two properties: Name and Age. Both the properties have Public access modifiers as well as setter and getter methods. This means that both properties are open for read and write operations. The convention is that properties should be in camel case.
If you want to modify your set and get methods, you can do so in the following way:
class Animal {
public string Name {
set {
name = value;
}
get {
return name;
}
}
public int Age {set; get;}
}
In the preceding example, we are not using the shortcut of creating setters and getters for the Name property. We have extensively written what the set and get methods should do. If you look closely, you will see the name field in lowercase. This means that when you create a property in camel case, a field with the same name is created internally, but in Pascal case. The value is a special keyword that actually represents the value of that property.
Properties are working behind the scenes in the background, which makes the code much cleaner and easier to use. It's very much recommended that you use properties instead of local fields.
- Go Web編程
- ASP.NET MVC4框架揭秘
- Amazon S3 Cookbook
- Visual Basic程序設計實驗指導(第4版)
- Oracle 18c 必須掌握的新特性:管理與實戰
- Qt5 C++ GUI Programming Cookbook
- QGIS 2 Cookbook
- Xcode 6 Essentials
- Scala Functional Programming Patterns
- Unity Android Game Development by Example Beginner's Guide
- Python Machine Learning Cookbook
- Python應用與實戰
- Functional Python Programming
- TensorFlow 2.0深度學習應用實踐
- 信息安全技術(第2版)