Properties In C#
Roman Fairushyn
Senior Software Engineer | .NET Enthusiast | Tech Content Creator | Teacher in State University of Telecommunications | Talks about #azure, #csharp, #dotnet, and #programming
In C#, a property is a member of a class that provides a flexible mechanism to read, write, or compute the value of a private field. They are a type of class member that have accessors which define the operations to be performed on a field of the class.
Properties Syntax:
In this example,?SampleProperty?is a property. It has a?get?accessor and a?set?accessor. The?get?accessor returns the value of?_sampleField, and the?set?accessor assigns a value to?_sampleField.
Auto-Implemented Properties:
C# also supports auto-implemented properties where you don't need to define a separate field.
n this case, the compiler creates a private, anonymous field that can only be accessed through the property's?get?and?set?accessors.
Read-Only Properties:
Read-only properties have a?get?accessor but no?set?accessor.
You can set the value of a read-only property in the constructor of the class.
Write-Only Properties:
Write-only properties have a?set?accessor but no?get?accessor. However, these are much less common.
Properties with Private Setters:
You can also create a property with a private set accessor, which can only be set within the class it is defined.
In this case,?SampleProperty?can be read from anywhere, but it can only be changed from within the?SampleClass.
Properties with Different Access Modifiers:
C# also allows you to specify different access levels for the?get?and?set?accessors.
In this example, the?get?accessor is public, but the?set?accessor is private.
Properties are a key part of object-oriented programming in C#, providing a way to control access to class data and allowing for more sophisticated behavior than that provided by simple data fields. In a technical interview, you may be asked to create or manipulate properties, so understanding their syntax and uses is crucial.