Monday, April 30, 2012

Properties


Properties are named members of classes, structs, and interfaces. They provide a flexible
mechanism to read, write, or compute the values of private fields through accessors.
Properties are an extension of fields and are accessed using the same syntax. Unlike
fields, properties do not designate storage locations. Instead, properties have accessors
that read, write, or compute their values.


Get accessor
The execution of the get accessor is equivalent to reading the value of the field.
The following is a get accessor that returns the value of a private field name:

private string name; // the name field
public string Name // the Name property
{
get
{
return name;
}
}


Set accessor


The set accessor is similar to a method that returns void. It uses an implicit parameter
called value, whose type is the type of the property. In the following example, a set
accessor is added to the Name property:
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
When you assign a value to the property, the set accessor is invoked with an argument
that provides the new value. For example:


e1.Name = "Reshmi"; // The set accessor is invoked here
It is an error to use the implicit parameter name (value) for a local variable declaration in
a set accessor.

How to make a Property Read Only/Write Only
There are times when we may want a property to be read-only – such that it can’t be
changed.
This is where read-only properties come into the picture. A Read Only property is one
which includes only the get accessor, no set accessor.


public read Only int empid
{
get
{
return empid;
}
}
Similar to read-only properties there are also situations where we would need
something known as write-only properties. In this case the value can be changed
but not retrieved. To create a write-only property, use the WriteOnly keyword and
only implement the set block in the code as shown in the example below.


public writeOnly int e
{
set
{
e = value
}
}





No comments:

Using Authorization with Swagger in ASP.NET Core

 Create Solution like below LoginModel.cs using System.ComponentModel.DataAnnotations; namespace UsingAuthorizationWithSwagger.Models {     ...