Fields and Properties in C#

This article has been excerpted from book "The Complete Visual C# Programmer's Guide from the Authors of C# Corner".

Fields are ordinary member variables or member instances of a class. Properties are an abstraction to get and set their values. Properties are also called accessors because they offer a way to change and retrieve a field if you expose a field in the class as private. Generally, you should declare your member variables private, then declare or define properties for them.

There are three obvious reasons for the necessity of properties in C#.

You can delay the creation of actual reference fields until you use them, which saves resources. You can differentiate the representation and actual storage. Representation is implemented via properties and storage is implemented via fields. You can check constraints when setting and getting properties. If the value is not suitable, you do not store the data in the field and a type-safety error is returned. This really provides 100% type-safe accessors on demand.

Properties afford you the advantage of more elegant syntax along with the robustness and better encapsulation of accessor methods. The syntax for implementing a property in C#, along with a constructor and a destructor and using the property is shown in the Age property in Listing 5.74.

Listing 5.74: Constructor Destructor Example

// example property, ctor, dtor, exceptionusing System;publicclassIndividual{Int32 age; // note that this is private// we could do this instead, more explicit// private Int32 age;// the default specifiers are all private!!!

classTestIndividual{publicstaticvoid Main() {try {Individual Jabbar = newIndividual(27);Console.WriteLine("This year, Jabbar was {0} years old", Jabbar.Age); Jabbar.Age++; // uses both get and set to do incrementConsole.WriteLine("Next year, Jabbar will be {0} years old", Jabbar.Age); }

By exposing these members as properties, the class can delay their initialization until they are actually used. Thus, if the application makes no reference to the prop2 and prop3 properties, no objects are created for those objects.

Conclusion

Hope this article would have helped you in understanding Fields and Properties in C#. See other articles on the website on .NET and C#.

The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.