C# read or write only property

In this chapter you will learn:

  1. What is C# read only property
  2. How to create read only property
  3. Read-only calculated properties

Description

We can create a read-only property by simply omitting the set accessor from the property definition.

Syntax

To make Name a read-only property, you would do the following:


private string name; 
              //from w w w .  j ava2 s .c o  m
public string Name  
{ 
   get 
   { 
      return Name; 
   }  
} 

Read-only calculated properties

A property typically has a dedicated backing field to store the underlying data. However, a property can be computed from other data.

For example:


decimal currentPrice, sharesOwned; // w  ww . j  a  v  a2s .  co m

public decimal Worth 
{ 
  get { return currentPrice * sharesOwned; } 
} 

Next chapter...

What you will learn in the next chapter:

  1. What are C# Automatic properties
  2. Syntax to create automatic properties
  3. Example
Home »
  C# Tutorial »
    C# Types »
      C# Properties
C# Properties
C# property accessor modifiers
C# read or write only property
C# Automatic properties
C# Static Properties
C# Abstract Properties