Properties is used for the access (read and write values) of the private variables of class. Member variables or methods in a class or structures are called Fields. Properties are special kinds of class fields and are accessed using the same syntax.
Keywords that can be used with C# properties
Properties can be marked as private, internal, public or protected internal. These access modifiers determine how you can access the property. A single property can have different access modifiers for the get and set accessors. For instance, the set accessor may be protected or private while the get accessor may be public to allow read-only access.
For Example:
- private string address = “park street”;
- public string Address
- {
- get
- {
- return address;
- }
- protected set
- {
- Address = value;
- }
- }
In the above example, the Address property includes a set and get accessor. The get accessor attains the accessibility level of the property, which in this case is public. The set accessor has protected as the access modifier; it is explicitly restricted. Properties declared as abstract have no implementation in the base class; derived classes write their own property implementation.
The static keyword can also be used for declaring a property. You can access a static property even if no instance of a class exists. The virtual keyword can be used to mark a property. This will allow you to override the property behavior in a derived class. The overridden property can be sealed to indicate it is no longer virtual in the derived class.
Code
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace cSharpCorner
- {
- class Program
- {
- private string code = "OB12";
- private string name = "Amonium";
- private bool latest = true;
-
- public string Code
- {
- get {
- return code;
- }
- set {
- code = value;
- }
- }
-
- public string Name
- {
- get {
- return name;
- }
- set {
- name = value;
- }
- }
-
- public bool Latest
- {
- get {
- return latest;
- }
- set {
- latest = value;
- }
- }
- public override string ToString()
- {
- return "Code = " + Code + ", Name = " + Name + ", Latest = " + Latest;
- }
- }
- class ExampleDemo
- {
- public static void Main()
- {
-
- Program s = new Program();
-
- s.Code = "001";
- s.Name = "Sodium";
- s.Latest = false;
- Console.WriteLine("chemical Info: {0}", s);
- s.Code = "002";
- s.Name = "Water";
- s.Latest = false;
- s.Latest = true;
- Console.WriteLine("chemical Info: {0}", s);
- Console.ReadKey();
- }
- }
- }