Menu Close

Category: Blog

PROPERTIES IN C#

Programming languages that does not have properties use getter and setter methods to encapsulate and protect fields.

In this example we use the SetId(Int Id) and GetId() methods to encapsulate _id class field

As a result, we have better control on what gets assigned and returned from the _id field.

Note: Encapsulation is one of the primary pillars of object oriented programming.


PROPERTIES:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;

namespace ConsoleApplication4
{
    public class Student
    {
        private int _id;
        private string _Name;
        private int _PassMark = 35;

        public int GetPassMark()
        {
            return this._PassMark;
        }
        public void SetName(string Name)
        {

            //return string.IsNullOrEmpty(this._Name) ? “no name” : this._Name;{ this is using turnary operator
            if (string.IsNullOrEmpty(Name))
            {
                throw new Exception(“NAME SHOULD NOT BE EMPTY OR NULL”);
            }
            this._Name = Name;
        }

        public string GetName()
        {
            if (string.IsNullOrEmpty(this._Name))
            {
                return  ” no name”;
            }
            else
            {
                return this._Name;
            }
        }
       

        public void SetId(int Id)
        {
            if(Id <= 0)
            {
                throw new Exception(“Student Id can not be negative”);
            }
            this._id = Id;
        }

        public int GetId()
        {
            return this._id;
        }
    }


   public class Program
    {
        static void Main()
        {
            Student C1 = new Student();
            C1.SetId(101);
            C1.SetName(“MALLA”);

            Console.WriteLine(“student id = {0}”, C1.GetId());
            Console.WriteLine(“student Name = {0}”, C1.GetName());
            Console.WriteLine(“student PassMark = {0}”, C1.GetPassMark());
            Console.ReadLine();
        }

        
    }
}


===========================

In C# we use set and get properties


Read/Write properties

Read Only Properties

Write Only Properties

Auto Implemented Properties

properties

1. we use get and set accessors to implement properties

2. A property with both get and set accessor is a Read/Write property

3. A property with only get accessor is a Read Only property.

4. A property with only set accessor is a Write only property

Note: The advantage of properties over traditional Get() and Set() methods is that, you can access them as if they were public fields.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;

namespace ConsoleApplication4
{
    public class Student
    {
        private int _Id;
        private string _Name;
        private int _PassMark = 35;
        private string _City;
        private string _Email;

        public string Email { get; set; }
            //get // when there is no logic then we can simply write like above.
            //{
            //    return this._Email;
            //}
            //set
            //{
            //    this._Email = value;
            //}
       
        public string city
        {
            get
            {
                return this._City;
            }
            set
            {
                this._City = value;
            }

        }

        public int PassMark
        {
            get
            {
                return this._PassMark;
            }
        }
        public string Name
        {

           set{
            if (string.IsNullOrEmpty(value))
            {
                throw new Exception(“NAME SHOULD NOT BE EMPTY OR NULL”);
            }
            this._Name = value;
        }
            get
            {
                return string.IsNullOrEmpty(this._Name) ? “No Name” : this._Name;
            }
    }

        public int Id
        {
            set
            {
                if (value <= 0)
                {
                    throw new Exception(“student id is not negative value”);

                }
                this._Id = value;
            }
            get
            {
                return this._Id;
            }
        }
    }
        public class Program
        {
            static void Main()
            {
                Student C1 = new Student();
                C1.Id =101;
                C1.Name = “malla”;
               
                Console.WriteLine(“student id = {0}”, C1.Id);
                Console.WriteLine(“student Name = {0}”, C1.Name);
                Console.WriteLine(“student PassMark = {0}”, C1.PassMark);
                Console.ReadLine();
            }
        }
    }

———————————-

>If there is no additional logic in the property accessors, then we can make use of auto-implementation properties introduced in c# 3.0
>Auto-implementation properties reduce the amount of code that we have to write.
>when you use auto-implementation properties, the compiler creates a private anonymous field that can only be accessed through the property’s get and set accessors.

Share this:

METHOD OVERRIDING VS METHOD HIDING AND METHOD OVERLOADING IN C# WITH EXAMPLE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;

namespace ConsoleApplication4
{

    public class BaseClass
    {
        public virtual void print()
        {
            Console.WriteLine(“I am a  Base Class print Method “);
        }
    }
    public class DerivedClass : BaseClass
    {
/* public new void print() is for method hiding */ 
        public override void print()
        {
            Console.WriteLine(“I am a Derived Class print Method “);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            BaseClass B = new DerivedClass();
            B.print();
            Console.ReadLine();

        }

    }
}
======================
METHOD OVERLOADING
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;

namespace ConsoleApplication4
{
    // Method overloading , same method names but different parameters
    class Program
    {
        static void Main(string[] args)
        {
            Add(2, 3);  //N HERE BECAUSE OF STATIC METHOD BELOW WE CAN CALL THE                                     //METHOD WITHOUT INSTANCE 
            Console.ReadLine();
       
        }

        public static void Add(int FN, int LN)
        {
            Console.WriteLine(“sum = {0} “, FN + LN);
        }

        public static void Add(int FN, int LN, out int SUM)
        {
            Console.WriteLine(“I am a Derived Class print Method “);
            SUM = FN + LN;
        }

    }
}

Share this:

POLYMORPHISM IN C# WITH SAMPLE EXAMPLE

Polymorphism is a primary pillars of object oriented programming

Polymorphism allow you to invoke derived class methods through a base class reference during runtime. 

In the base class the method is declared as virtual and in the derived class we override the same method with “override keyword”.

The virtual keyword indicates, the method can be overridden in any derived class. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;

namespace ConsoleApplication4
{

    /// <summary>
    /// Polymorphism example
    /// </summary>
    public class Employee
    {
        public string FirstName = “FN”;
        public string LastName = “LN”;
     

        public virtual void PrintFullName()
        {
            Console.WriteLine(FirstName + ” ” + LastName);
        }

    }

    public class FullTimeEmployee : Employee
    {
        public override void PrintFullName()
        {
            Console.WriteLine(FirstName + ” ” + LastName + “- FullTimeEmployee”);
        }
     
    }
    public class PartTimeEmployee : Employee
    {
        public override void PrintFullName()
        {
            Console.WriteLine(FirstName + ” ” + LastName + ” – PartTimeEmployee”);
        }
    }
    public class TemporaryEmployee : Employee
    {
        public override void PrintFullName()
        {
            Console.WriteLine(FirstName + ” ” + LastName + ” – TemporaryEmployee”);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
           Employee[] employees = new Employee[4];

           employees[0] = new FullTimeEmployee();
           employees[1] = new PartTimeEmployee();
           employees[2] = new TemporaryEmployee();
           employees[3] = new Employee();
           foreach (Employee e in employees)
           {
               e.PrintFullName();
               Console.ReadLine();
           }      

        }

    }
}

Share this:

METHOD HIDING IN C# WITH SAMPLE EXAMPLE

## METHOD HIDING

## INVOKE BASE CLASS MEMBERS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;

namespace ConsoleApplication4
{
    public class Employee
    {
        public string FirstName;
        public string LastName;
        public string Email;

        public void PrintFullName()
        {
            Console.WriteLine(FirstName + ” ” + LastName);
        }
    }

    public class PartTimeEmployee : Employee
    {
        public new void PrintFullName()
        {
            Console.WriteLine(FirstName + ” ” + LastName  +  ” — Contractor”);
        }
    }

    public class FullTimeEmployee : Employee
    {

    }
    class Program
    {
        static void Main(string[] args)
        {
           Employee PTE = new PartTimeEmployee();
            PTE.FirstName = “PART TIME “;
            PTE.LastName  =  “EMPLOYEE”;
            PTE.PrintFullName();
            Console.ReadLine();

            FullTimeEmployee FTE = new FullTimeEmployee();
            FTE.FirstName = “FULL TIME”;
            FTE.LastName = “EMPLOYEE”;
            FTE.PrintFullName();
            Console.ReadLine();
        }

    }
}

Share this:

INHERITANCE IN C# WITH SAMPLE EXAMPLE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;

namespace ConsoleApplication4
{
    /// <summary>
    /// Base class Employee( Inheritance example)
    /// </summary>
    public class Employee
    {
        public string FirstName;
        public string LastName;
        public string Email;
   
        public void PrintFullName()
        {
            Console.WriteLine(FirstName + ” ” + LastName);
        }
    }
    /// <summary>
    /// Derived class inheriting Employee
    /// </summary>
    public class FullTimeEmployee : Employee
    {

      public  float YearlySalary;
    }
    /// <summary>
    /// Derived class inherting Employee
    /// </summary>

    public class PartTimeEmployee :  Employee
    {
     public  float HourlyRate;

    }
    class Program
    {
        static void Main(string[] args)
        {
            FullTimeEmployee FTE = new FullTimeEmployee();
            FTE.FirstName = “Mitali”;
            FTE.LastName = “Gurram”;
            FTE.Email = “malla.gurram@gmail.com”;
            FTE.YearlySalary = 100000;
            FTE.PrintFullName();
            Console.ReadLine();

            PartTimeEmployee PTE = new PartTimeEmployee();
            PTE.FirstName = “GMR”;
            PTE.LastName = “IT SOLUTIONS”;
            PTE.HourlyRate = 90;
            PTE.PrintFullName();
            Console.ReadLine();
        }

    }
}

=============
DERIVED CLASS  CAN CONTROL BASE CLASS CONSTRUCTORS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication4;

namespace ConsoleApplication4
{
    public class ParentClass
    {     //parent constructor
        public ParentClass()
        {
            Console.WriteLine(” parentclass constructor called”);
            Console.ReadLine();
        }
        public ParentClass(string Message)
        {
            Console.WriteLine(Message);
            Console.ReadLine();
        }
    }

    public class ChildClass : ParentClass
    {    //childclass constructor
        public ChildClass() :  base(“Derived class controlling parent class”)
        {
            Console.WriteLine(“childclass constructor called”);
             Console.ReadLine();
        }
    }

   
    class Program
    {
        static void Main(string[] args)
        {
           ChildClass CC = new ChildClass();
           
        }

    }
}

Share this: