Create read only property with read only field - CSharp Custom Type

CSharp examples for Custom Type:Property

Description

Create read only property with read only field

Demo Code

using System;// w w  w  .ja va 2s  . c  o  m
using System.Collections.Generic;
using System.Text;
public class Person
{
   private readonly string _firstName;
   private readonly string _lastName;
   public string FirstName
   {
      get
      {
         return _firstName;
      }
   }
   public string LastName
   {
      get
      {
         return _lastName;
      }
   }
   public int Age { get; set; }
   private decimal _salary;
   public Person(string firstName, string lastName, int age, decimal salary = 45000)
   {
      _firstName = firstName;
      _lastName = lastName;
      Age = age;
      //default value
      _salary = salary;
   }
}
class Program
{
   static void Main(string[] args)
   {
      Person person = new Person("A", "S", 44);
      person.Age = 28;
      Console.WriteLine("{0} {1} - age: {2}", person.FirstName, person.LastName, person.Age);
   }
}

Result


Related Tutorials