Program for Read only and Write only Properties



Class Diagram :-



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//Program2 for Read only and Write only Properties
namespace Properties
{
    class ClsArithematic
    {
        int Num1, Num2, Result;
        public int PNum1
        {
            set
            {
                Num1 = value;
            }
        }
        public int PNum2
        {
            set
            {
                Num2 = value;
            }
        }
        public int PResult
        {
            get
            {
                return Result;
            }
        }
        public void Add()
        {
            Result = Num1 + Num2;
        }
        public void Subtract()
        {
            Result = Num1 - Num2;
        }
        public void Multiply()
        {
            Result = Num1 * Num2;
        }
        public void Divide()
        {
            Result = Num1 / Num2;
        }
    }
    class ClsProperty2
    {
        static void Main()
        {
            ClsArithematic Obj1 = new ClsArithematic();
            Console.WriteLine("Enter two Numbers");
            Console.WriteLine("Enter Num1 value");
            Obj1.PNum1 = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Enter Num2 value");
            Obj1.PNum2 = Convert.ToInt32(Console.ReadLine());
            Obj1.Add();
            Console.WriteLine("sum of two numbers is          :-   " + Obj1.PResult);
            Obj1.Subtract();
            Console.WriteLine("Difference of two Numbers is   :-   " + Obj1.PResult);
            Obj1.Multiply();
            Console.WriteLine("Product of two numbers is      :-   " + Obj1.PResult);
            Obj1.Divide();
            Console.WriteLine("Quotient of two numbers is     :-   " + Obj1.PResult);
            Console.Read();
        }
    }
}






Output :-


  • In the above example, the Result Data field, which is calculated in ClsArithematic class can’t be modified from outside the class, because property PResult is read only, using which we can’t write the data into data field


    If there is no property we need to “set” our result Data field as public, then result field doesn’t have any security from outside the class


 

No comments:

Post a Comment