Learn Tiny Bit Of C# In 7 Days - Day 2

Introduction

We successfully completed day 1 before coming here.

Day 2 Agenda

  1. Namespaces
  2. Classes
  3. Abstraction
  4. Encapsulation
  5. Inheritance
  6. Properties
  7. Access Modifiers

Namespaces

Why Namespace?

  • Namespace help us organize our programs.
  • They help us to avoid name clashing.
  • To control the scope of the class and method name in our Projects.

Syntax: Namespace nameofNamespace

Namespace is a collection of classes and are used to organize them.

System.Console.WriteLine("Learn C# in 7 days!");

Here System is a Namespace and Console is a class present in System.

Represent a Shape Namespace
Fig 1.0 Represent a Shape Namespace and its corresponding Classes

Let’s take example where we have two teams which are working on same project with same class so in order to organize them we create namespace with projectname and then the namespace for subclasses as shown below:

  1. namespace ProjectA //project name   
  2. {  
  3.     namespace PromoTeam //to signify whose Team class is this  
  4.     {  
  5.         class A  
  6.         {  
  7.             public static void print()  
  8.             {  
  9.                 System.Console.WriteLine("heelo i am PromoTeam");  
  10.                 Console.ReadLine();  
  11.             }  
  12.         }  
  13.     }  
  14. }  
  15. namespace ProjectA //project name   
  16. {  
  17.     namespace OMSTeam //to signify whose Team class is this  
  18.     {  
  19.         class B  
  20.         {  
  21.             public static void print()  
  22.             {  
  23.                 Console.WriteLine("heelo i am OMSTeam");  
  24.                 Console.ReadLine();  
  25.             }  
  26.         }  
  27.     }  
  28. }  
So now when we want to access the print function of OMSTeam we will just use the following code,
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         ProjectA.OMSTeam.B.print(); //Namespace.Namespace.ClassName.Method  
  6.     }  
  7. }  
Else we can use using statement for the same.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using ProjectA.OMSTeam;  
  7. using ProjectA.PromoTeam;  
  8. class Program  
  9. {  
  10.     static void Main(string[] args)  
  11.     {  
  12.         A.print();  
  13.     }  
  14. }  
  15. namespace ProjectA  
  16. {  
  17.     namespace PromoTeam  
  18.     {  
  19.         class A  
  20.         {  
  21.             public static void print()  
  22.             {  
  23.                 System.Console.WriteLine("heelo i am PromoTeam");  
  24.                 Console.ReadLine();  
  25.             }  
  26.         }  
  27.     }  
  28. }  
  29. namespace ProjectA  
  30. {  
  31.     namespace OMSTeam  
  32.     {  
  33.         class A  
  34.         {  
  35.             public static void print()  
  36.             {  
  37.                 Console.WriteLine("heelo i am OMSTeam");  
  38.                 Console.ReadLine();  
  39.             }  
  40.         }  
  41.     }  
  42. }  
But when we try to access the OMSTeam class the complier shows the following error,

OMSTeam

In order to resolve this we can use fully qualified name.
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         ProjectA.OMSTeam.A.print();  
  6.         ProjectA.PromoTeam.A.print();  
  7.     }  
  8. }  
Namespace Aliases

We can create alias name of the Namespace by using the using statement through which we can resolve this problem using alias name of Namespace as shown below,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Omsteam = ProjectA.OMSTeam; //giving alias name to Namespace  
  7. using PromoTeam = ProjectA.PromoTeam; //giving alias name to Namespace  
  8. class Program  
  9. {  
  10.     static void Main(string[] args)  
  11.     {  
  12.         Omsteam.A.print();  
  13.         Omsteam.A.print();  
  14.     }  
  15. }  
Now we can do the same using class Libraries as shown below:

New project

Class liberary

And name the class as article.

Note: I have changed the class name so that it will look more Business related.
  1. namespace ProjectA.OmsTeam  
  2. {  
  3.     public class Article  
  4.     {  
  5.         public static void print()  
  6.         {  
  7.             Console.WriteLine("heelo i am OMSTeam");  
  8.             Console.ReadLine();  
  9.         }  
  10.     }  
  11. }  
And same we will create for PromoTeam.
  1. namespace ProjectA.PromoTeam  
  2. {  
  3.     public class Article  
  4.     {  
  5.         public static void print()  
  6.         {  
  7.             System.Console.WriteLine("heelo i am PromoTeam");  
  8.             Console.ReadLine();  
  9.         }  
  10.     }  
  11. }  
Now in order to use these Namespace we need to add them in our project by adding them in references.

reference

Solution

We will check the checkbox and select both of them to be used in our project.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using OmsTeam = ProjectA.OmsTeam; //using the namespace with alias name  
  7. using PromoTeam = ProjectA.PromoTeam; //using the namespace with alias name  
  8. class Program  
  9. {  
  10.     static void Main(string[] args)  
  11.     {  
  12.         OmsTeam.Article.print(); //calling the print method  
  13.         PromoTeam.Article.print(); //calling the print method  
  14.         Console.ReadLine();  
  15.     }  
  16. }  
checkbox

Classes and Objects in C#

Classes and Objects in C#

When we store the list of Information regarding a type we make use of classes e.g. Employee so Employee has the varieties of information that are needed to be stored i.e. EmployeeName, EmployeeId, EmployeePhoneNo, EmployeeAddress, Gender, Jobtitle, etc. A class is a template for creating object. Class can also contain methods to perform operations related to Employee that is termed as behavior. Class is basically a template which is a repository of information and that information can be called using a Class Object.

A class consists of state and behavior. Class data is represented by Properties/Fields and behavior is represented by methods.

Syntax: Class ClassName

Go to your project and right click and add NewItem, select class and give your Class name.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace ClassDef  
  7. {  
  8.     class Employee  
  9.     {}  
  10. }  
Now add some fields and methods to an Employee class. Now I declare some data as shown below and I am using Constructor to set the value to the class data.

Note- Constructor is creation of object at run time, as soon as the object creating the Class Constructor is called. Constructors are used for object initialization and memory, field’s allocation of its class.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace ClassDef  
  7. {  
  8.     class Employee  
  9.     {  
  10.         string _Name;  
  11.         int _Age;  
  12.         public Employee(string Name, int Age)  
  13.         {  
  14.             this._Name = Name; //this is points towards object of this classs  
  15.             this._Age = Age;  
  16.         }  
  17.         public void Information()  
  18.         {  
  19.             Console.WriteLine("The Information of the Employee is Name={0} and Age={1}", _Name, _Age);  
  20.             Console.ReadLine();  
  21.         }  
  22.     }  
  23. }  
Passing the field values to the object.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace ClassDef  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             Employee obj = new Employee("Saillesh", 26);  
  13.             obj.Information();  
  14.         }  
  15.     }  
  16. }  
Classes and Objects

As we go ahead we will see how to use properties and assign value to the properties.

Objects

An object is instance of a class, i.e. an instance has properties for identifying its state (attributes) and methods for behavior and event for depicting the change of state defined by the class.

Object Entity

Object Entity means that every object is unique and can be differentiated from other, each time the object is created an Object entity is defined. What we always see and are able to distinguish from each other is an Object.

Passing the field values

When we talk about Saillesh Desktop, we are referring to an object of Class Desktop that can subdivide in to child classes like Desktop of Hp or Sony etc. But as here we are talking about Saillesh Desktop we will discuss only this desktop and its attributes and methods.

You can see the following diagram to see Saillesh Desktop behavior and Attributes.

Object Entity

As I said object is instance of a class, i.e. we can say that a birth or creation of object is called instantiation.

Sample examples of a class : Girl

examples of a class

class

Circle Class

Static Classes – A static class is same as non-static class, the only difference is we cannot create object of Static class.

Note: Static class should have all the methods, fields and properties as static.

Benefits:

 

  • We don’t need to make instance of the class all the methods, fields and properties are easily accessible using Class name.
  • No OOP principles are applicable to Static class.
  • Do not map to Real world objects, it’s just a collection of unrelated methods or logic so that we can increase the reusability in our project.
  • If you want cache data.

Note: Constructor runs only once in Static class.

Declaration

A static class is created by using keyword 'Static' as shown here:

Static class ClassName
{
   //list of properties and methods
}


Abstraction

"A view of a problem that extracts the essential information
relevant to a particular purpose and ignores the remainder of
the information.
"

-- [IEEE, 1983]

"Abstraction is the selective examination of certain aspects of
a problem. The goal of abstraction is to isolate those aspects
that are important for some purpose and suppress those aspects
that are unimportant.
"

-- [Rumbaugh et al, 1991]

"[A] simplified description, or specification, of a system that
emphasizes some of the system's details or properties while
suppressing others. A good abstraction is one that emphasizes
details that are significant to the reader or user and suppress
details that are, at least for the moment, immaterial or
diversionary.
"

-- [Shaw, 1984]

Source: http://www.tonymarston.co.uk/php-mysql/abstraction.txt

Encapsulation

"Encapsulation is used as a generic term for techniques which
realize data abstraction. Encapsulation therefore implies the
provision of mechanisms to support both modularity and information
hiding. There is therefore a one to one correspondence in this
case between the technique of encapsulation and the principle of
data abstraction.
"

-- [Blair et al, 1991]

"Data hiding is sometimes called encapsulation because the data
and its code are put together in a package or 'capsule.'
"

-- [Smith, 1991]

"[E]ncapsulation -- also known as information hiding --
prevents clients from seeing its inside view, were the behavior
of the abstraction is implemented.
"

-- [Booch, 1991]

Source: http://www.tonymarston.co.uk/php-mysql/abstraction.txt

From the above definitions we figured out that Abstraction is more collective thing the principle of Object oriented programming and denotes to show something in simpler way e.g. Building blocks of Building, such as color or shapes. What is necessary to the User and essential feature of the object to the End User and ignoring the essential details? While Encapsulation is a strategy used as part of abstraction to implement the abstraction, wrap data in a unit or capsule i.e. Class. It keeps the data safe from outside code. It refers to the object of the class. We access the class by instantiating the class object. Object properties and method can be hidden from the end user.

Note: Here end user is perspective to the User who references your DLL File. Now we use reference of object then it will show only necessary methods and properties and hide methods which are not necessary which we have hide from the external User.

For example, I have Meeting Management System App.

Where when I create the MOM Minutes of the Meeting and insert the Meetings details to the DB for e.g. using Function:

  • CreateMOM()

When this function executes it first it adds the Meeting Name, Segments (Retails, Audit, Operational etc.) and create the MeetingId for the MOM and then based on the Meeting Id after that based upon the MeetingId it internally calls other methods that creates the child of Meeting as in the following,

  • Participants in the Meeting (Employees who participated in the Meeting)
  • Agenda Covered in the Meeting
  • File uploaded (any excel file)
  • Format Function Covered
  • Sending mail to all the participants related what action was taken in the meeting.

So we can imagine that there are couple of step it does.

  • Now imagine we have another User or Client who is consuming our class rather than telling him all the things we just tell him the method name CreateMOM(), as Abstraction we are hiding the user only the necessary function and encapsulation is hiding the other complex things from it. (Adding participants to other sub tables, agenda covered in the meeting,   etc.) We implement the encapsulation using Access Modifiers (Private).

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.Data.SqlClient;  
  7. //Abstraction Namespace   
  8. namespace Abstraction  
  9. {  
  10.     /// <summary>  
  11.     /// Meeting Class contains list of Properties and functions for the Meeting Creation  
  12.     /// </summary>  
  13.     class Meeting  
  14.     {  
  15.         private int _Id;  
  16.         private string _Name;  
  17.         public string Name  
  18.         {  
  19.             get  
  20.             {  
  21.                 return _Name;  
  22.             }  
  23.             set  
  24.             {  
  25.                 _Name = value;  
  26.             }  
  27.         }  
  28.         private string _Format;  
  29.         public string Format  
  30.         {  
  31.             get  
  32.             {  
  33.                 return _Format;  
  34.             }  
  35.             set  
  36.             {  
  37.                 _Format = value;  
  38.             }  
  39.         }  
  40.         private string _Location;  
  41.         public string Location  
  42.         {  
  43.             get  
  44.             {  
  45.                 return _Location;  
  46.             }  
  47.             set  
  48.             {  
  49.                 _Location = value;  
  50.             }  
  51.         }  
  52.         private string _FileUploaded;  
  53.         public string FileUploaded  
  54.         {  
  55.             get  
  56.             {  
  57.                 return _FileUploaded;  
  58.             }  
  59.             set  
  60.             {  
  61.                 _FileUploaded = value;  
  62.             }  
  63.         }  
  64.         public bool InsertToDb()  
  65.         {  
  66.             try  
  67.             {  
  68.                 this._Id = AddandGetMeetingId(_Name, _Format, _Location);  
  69.                 bool Status = AdduploadedFiles(this._Id, _FileUploaded);  
  70.                 if (Status == true)  
  71.                 {  
  72.                     return true;  
  73.                 }  
  74.                 else  
  75.                 {  
  76.                     return false;  
  77.                 }  
  78.             }  
  79.             catch (Exception ex)  
  80.             {  
  81.                 throw new Exception(ex.Message.ToString());  
  82.             }  
  83.         }  
  84.         private int AddandGetMeetingId(string MeetingName, string FormatName, string MeetingLocation)  
  85.         {  
  86.             try  
  87.             {  
  88.                 DAL objDal = new DAL();  
  89.                 int Id = objDal.CreateMom(MeetingName, FormatName, MeetingLocation);  
  90.                 return Id;  
  91.             }  
  92.             catch (Exception ex)  
  93.             {  
  94.                 throw new Exception(ex.Message.ToString());  
  95.             }  
  96.         }  
  97.         private bool AdduploadedFiles(int id, string FileName)  
  98.         {  
  99.             try  
  100.             {  
  101.                 DAL objDal = new DAL();  
  102.                 bool status = objDal.CreateMom(id, FileName);  
  103.                 return true;  
  104.             }  
  105.             catch (Exception ex)  
  106.             {  
  107.                 throw new Exception(ex.Message.ToString());  
  108.             }  
  109.         }  
  110.     }  
  111. }  
Now here I have set the Class properties _id private and function AddandGetMeetingId and AdduploadedFiles as private because I don’t want end user to see these methods and Properties. Now when I am consuming this class I am only able to see methods and properties which I want User to see hiding the complexities from him and only showing the necessary information that is necessary.

AdduploadedFiles

We can see from the above diagram that only required information is shown to the User. User access the class method as shown below:
  1. try  
  2. {  
  3.     Console.WriteLine("Enter the Meeting Name");  
  4.     objMeeting.Name = Console.ReadLine();  
  5.     Console.WriteLine("Enter the Format Name");  
  6.     objMeeting.Format = Console.ReadLine();  
  7.     Console.WriteLine("Enter the Meeting Location");  
  8.     objMeeting.Location = Console.ReadLine();  
  9.     Console.WriteLine("Enter the file Uploaded");  
  10.     objMeeting.FileUploaded = Console.ReadLine();  
  11.     bool status = objMeeting.InsertToDb();  
  12.     if (status == true)  
  13.     {  
  14.         Console.WriteLine("Minutes of Meeting Created Successfully");  
  15.     }  
  16.     else  
  17.     {  
  18.         Console.WriteLine("Failed to Created Minutes of the Meeting");  
  19.     }  
  20.     Console.ReadLine();  
  21. }  
  22. catch (Exception ex)  
  23. {  
  24.     Console.WriteLine(ex.Message.ToString() + " " + ex.StackTrace.ToString());  
  25. }  
And DAL Layer which will insert data to the Database.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using System.Data.SqlClient;  
  7. using System.Configuration;  
  8. namespace Abstraction  
  9. {  
  10.     public class DAL  
  11.     {  
  12.         public static SqlConnection con;  
  13.         static DAL()  
  14.         {  
  15.             con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBclass"].ConnectionString);  
  16.         }  
  17.         public int CreateMom(string MtngName, string FrmtName, string Location)  
  18.         {  
  19.             try  
  20.             {  
  21.                 string query = "insert into tblMeetingMaster values ('" + MtngName + "','" + FrmtName + "','" + Location + "')";  
  22.                 SqlCommand cmd = new SqlCommand(query, DAL.con);  
  23.                 con.Open();  
  24.                 cmd.ExecuteScalar();  
  25.                 string query2 = "select IDENT_CURRENT('tblMeetingMaster')";  
  26.                 SqlCommand cmd1 = new SqlCommand(query2, DAL.con);  
  27.                 decimal value = (decimal) cmd1.ExecuteScalar();  
  28.                 return Convert.ToInt32(value);  
  29.             }  
  30.             catch (Exception ex)  
  31.             {  
  32.                 throw new Exception(ex.Message.ToString());  
  33.             }  
  34.             finally  
  35.             {  
  36.                 con.Close();  
  37.             }  
  38.         }  
  39.         public bool CreateMom(int MeetingId, string FileName)  
  40.         {  
  41.             try  
  42.             {  
  43.                 string query = "insert into tblFileUploaded values ('" + MeetingId + "','" + FileName + "')";  
  44.                 SqlCommand cmd = new SqlCommand(query, DAL.con);  
  45.                 con.Open();  
  46.                 cmd.ExecuteNonQuery();  
  47.                 return true;  
  48.             }  
  49.             catch (Exception ex)  
  50.             {  
  51.                 return false;  
  52.                 throw new Exception(ex.Message);  
  53.             }  
  54.             finally  
  55.             {  
  56.                 con.Close();  
  57.                 con.Dispose();  
  58.             }  
  59.         }  
  60.     }  
  61. }  
End User Input the Details

User Inputs the Details

Values inserted in DB

Values inserted in DB

Inheritance

Inheritance

From the above diagram you can predict there are two Classes Football Player, Cricket player and both of them are having lots of common properties and methods. So in order to duplicate code in both the classes we move all duplicate code into base class called Player.

base class

Inheritance is a parent child relationship in an object oriented programming where we can create a Parent class and extend the functionality of parent class by creating child class.

While talking about above classes the specific code that left respective include: football and cricket. In football we have Goals Scored, while in Cricket we have Run Scored, etc. Let go ahead and implement the same as written below.

 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace Inheritance  
  7. {  
  8.     public class Player  
  9.     {  
  10.         public string PlayerName;  
  11.         public string ClubName;  
  12.         public string PlayGround;  
  13.         public void PlayerDetails()  
  14.         {  
  15.             Console.WriteLine("THE Player details are PlayerName {0}, Registered to{1} playing in {2}", PlayerName, ClubName, PlayGround);  
  16.             Console.ReadLine();  
  17.         }  
  18.     }  
  19.     public class CricketPlayer: Player  
  20.     {  
  21.         public int Runscored;  
  22.     }  
  23.     public class FootballPlayer: Player  
  24.     {  
  25.         public int GoalScored;  
  26.     }  
  27. }  
  • In this above example derived class inherits from the Parent class.
  • C# Supports only single class inheritance.
  • Child class is a specialization of base class.
  • Parent classes are automatically instantiated before derived class.
  • Parent class constructs executes before child class.

In interview sometimes Interviewer asks us which constructor will be called first when we call a child class constructor.

Parent classes are automatically instantiated before derived class, as soon as we create an object of child class the parent class constructor is called as shown below.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace ParentClassConstructor  
  7. {  
  8.     public class Parent  
  9.     {  
  10.         public Parent()  
  11.         {  
  12.             Console.WriteLine("Parent class constructor called");  
  13.             Console.ReadLine();  
  14.         }  
  15.     }  
  16.     public class Child: Parent  
  17.     {  
  18.         public Child()  
  19.         {  
  20.             Console.WriteLine("Child class constructor called");  
  21.             Console.ReadLine();  
  22.         }  
  23.     }  
  24.     class Program  
  25.     {  
  26.         static void Main(string[] args)  
  27.         {  
  28.             Child objChild = new Child();  
  29.         }  
  30.     }  
  31. }  
Parent classe

Properties

Property is a member that provides the mechanism to what gets assigned and what gets returned from your fields/classes variables. In simple terms we can say that properties help us to inject the logic inside the fields /classes variables. By using the Access modifiers we can make it possible to what gets assigned and what gets returned from your fields. Properties implements Encapsulation because it hides the complexity from the User.
Property member

Why Properties
  • As discussed earlier if we make our class fields public we will not have any control on what gets assigned and what gets returned from your fields.
  • Below are the scenarios which we face when our fields are public.

The following is a class called Employee Class with public fields ID.

  • Our Business rule say that ID should not be less than 1.
  • Name cannot be set to NULL
  • Marks Should be Read only

But as we can see below we are able to change the values and assign the same to our fields.

  1. public class Employee  
  2. {  
  3.     public int ID;  
  4. }  
  5. public class Program  
  6. {  
  7.     static void Main(string[] args)  
  8.     {  
  9.         Employee obj = new Employee();  
  10.         obj.ID = -100; // ID should not be less than 1  
  11.         obj.NAME = null// name should not be empty  
  12.         obj.MARKS = 20; //Marks should be a read only property but here we are able to change it  
  13.         Console.WriteLine("the values of the new object are ID {0} ,NAME {1}, MARKS {2} ", obj.ID, obj.NAME, obj.MARKS);  
  14.         Console.ReadLine();  
  15.     }  
  16. }  
When I execute the application we will see that all Business rules has been violated and there is no message to the user for the same.

Business rules

So in order to validate the Business rule we use get and set methods properties in C#. The programming language that before properties they use Getter and Setter(for better understanding) method as shown below.

Firstly, we create our property to be private so that they won’t be accessible to the external world.
Now we write to methods for set and get i.e. SetId, GetId to control what’s get into the fields and what set into the fields of class.

fields of class

Now I initialize the object of Employee class we find that we are not able to get access to our fields rather we are able to access SetId and GetId methods. Now I set the value to the _id field as shown below:

setid

Now I will set the value of id as -100 and then call the obj.Getid we see how the flow of program goes.

Step 1: Once the object is created we try to set the value of _id=-100

value

Step 2: As the id value passed is less than 1 it enters the exception and throw a new exception for the same.

enters the exception

Step 3: It enters the catch block and will print the exception message as shown below.

exception message

exception

Now we input a correct value which is greater than 1 and print the value using getId function as shown below.

get id

Code

Now we are following the business rules so the output will be,

command

So now we can see that these methods are allowing us to control over what gets assigned and returned.

Now we will see how in C# we implement Properties in order to hide complexity from the User (Encapsulation).

In order to use a property you have to write the following,

order to use a property

Or we can use code snippet shortcut prop and press tab for the same.

prop

Property

And then create your get and set accessor as above.

Now before as we created the object of Employee class and we called the function getID and setId but now we will not get any method beside no will get ID Property as shown below.

ID Property

Now how will it be checked once the value of property ID is passed to the set accessor it has keyword called (value).

keyword

Once the value is assigned to property ID it calls the set accessor as shown below:

accessor

And for getting the values of the id we have to just write object name than property name, it invokes the id provided and invokes the get accessor of this property and returns a value which is present in private.

present in private

run

As we can see get and set are Read Write properties, user can write a value to the fields and same he can read the value from the fields.

So what if we want only read only field like pi in maths that is 3.14 or other ready only fields as per business logic.

For this we need to make our property with only get accessor.

E.g. Here I am taking an example of bonus which is same for all employees. In order to make it a read property we will assign only get accessor to it as shown below.

get accessor

Now if I try and change the property to something else,

bonus

It shows that the value cannot be assigned as it’s a read only property i.e. we can only read the value, not assign them.

cs

cmd

And if in case you want to make a property you want to write only and then you have to use only set accessor.

Auto Implemented Properties: As earlier discussed shortcut for property prop, actually Microsoft introduced auto implemented properties in C# 3.0. For scenarios where we don’t want to inject any logic Eg. City. In Auto Implemented we don’t have to create private fields because compiler will automatically create for us private field and the public property will be used to read and write to that property.

E.g. of Auto Implemented Property.

public int MyProperty { get; set; } //Just one line

Note: In the end I want to end this article saying that the advantage of using properties is that we don’t have to create function for what gets and set in the fields. In properties the compiler on its own generates getter and setter methods as we did earlier before properties when it parses the C# property syntax as per the algorithm defined.

Access Modifiers

All Class members’ behavior, data and class have their accessibility level, which specify that whether they can be accessed from other code in your Assembly.

There are 5 types of different Access Modifiers in C#:
  • Private
  • Protected
  • Friend
  • Protected Friend(Protected Internal)
  • Public

Access Modifiers
Image Source: http://dotnethints.com/blogs/public-vs-protected-vs-private

In Private Access modifier only the members of class can access to the function or variable or accessibility level is within the containing class.

For example

We have a Customer Class with two properties.

CustomerID and CustomerName as shown below,

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace AccessModifier  
  7. {  
  8.     public class Customer  
  9.     {  
  10.         private int _id; //declared with private   
  11.         private string _CustomerName;  
  12.         public int id //public property with get and set accessor  
  13.         {  
  14.             get  
  15.             {  
  16.                 return id;  
  17.             }  
  18.             set  
  19.             {  
  20.                 id = value;  
  21.             }  
  22.         }  
  23.         public string CustomerName  
  24.         {  
  25.             get  
  26.             {  
  27.                 return _CustomerName;  
  28.             }  
  29.             set  
  30.             {  
  31.                 CustomerName = value;  
  32.             }  
  33.         }  
  34.     }  
  35. }  
Now once I try to access the private property outside the class I wouldn’t be able to access them due to its protection level.
protection leve

We can only access the Public Properties not private fields.

Public Properties

If I try to access the public members there are no errors and we can easily access them.
  1. namespace AccessModifier  
  2. {  
  3.     class Program  
  4.     {  
  5.         static void Main(string[] args)  
  6.         {  
  7.             Customer c1 = new Customer();  
  8.             c1.id = 1;  
  9.             c1.CustomerName = "saillesh";  
  10.         }  
  11.     }  
  12. }  
So here we also learnt about Public access modifier all members are accessible in all classes and projects. I.e. Any where

Protected: In Protected access modifiers all the members of the class are accessible to the class member and to the derived classes.

Now I create two classes one Customer and GoldCustomer. Gold Customer inherits from Customer class as shown below,
  1. using System;  
  2. namespace AccessModifier  
  3. {  
  4.     public class Customer  
  5.     {  
  6.         protected int _id;  
  7.         protected string _CustomerName;  
  8.         public int id  
  9.         {  
  10.             get  
  11.             {  
  12.                 return id;  
  13.             }  
  14.             set  
  15.             {  
  16.                 id = value;  
  17.             }  
  18.         }  
  19.         public string CustomerName  
  20.         {  
  21.             get  
  22.             {  
  23.                 return _CustomerName;  
  24.             }  
  25.             set  
  26.             {  
  27.                 CustomerName = value;  
  28.             }  
  29.         }  
  30.     }  
  31.     public class GoldCustomer: Customer  
  32.     {  
  33.         private float _Discount;  
  34.         public float Discount  
  35.         {  
  36.             get  
  37.             {  
  38.                 return _Discount;  
  39.             }  
  40.             set  
  41.             {  
  42.                 _Discount = value;  
  43.             }  
  44.         }  
  45.         public void PrintDetails()  
  46.         {  
  47.             GoldCustomer cust = new GoldCustomer(); //creating object of child class  
  48.             cust._id = 1; ///we can access the protected value of parent class  
  49.             cust._CustomerName = "Nishant"//same goes here  
  50.         }  
  51.     }  
  52. }  
Calling Program.cs

Calling Program
If I try to access it from outside the class we can see that it is inaccessible due to its protection level. So if you want to access the protected class member you can access it from child class using child class object inside a class or using Base keyword.

Base keyword

Friend (Internal): The members with internal access modifiers are available anywhere in the containing project or assembly.

To demonstrate the same we need to add one more project as mentioned below.

Add Class library and Name it Project1.
  1. using System;  
  2. namespace Project1  
  3. {  
  4.     public class SilverCustomer  
  5.     {  
  6.         internal string CustomerName = "saillesh"//internal   
  7.     }  
  8.     public class BronzeCustomer  
  9.     {  
  10.         public void details()  
  11.         {  
  12.             SilverCustomer obj = new SilverCustomer(); //we create an instance of Silver Customer  
  13.             Console.WriteLine(obj.CustomerName); //we can easily access the member of SilverCustomer  
  14.         }  
  15.     }  
  16. }  
Now once I try it from other main project let us see what happens. So for the same I have added Project1 class to main project to use the same.

As shown below:

Project
  1. using System;  
  2. using Project1; //using the Namespace  
  3. namespace InternalExample  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             SilverCustomer objSilver = new SilverCustomer();  
  10.         }  
  11.     }  
  12. }  
Now as soon as I try to access the Internal member we would not be able to access the member and if try to input the member name we will face compile time error.

error
Protected Internal is the combination of both Internal and Protection. All members in current project and all members in derived class in any other project /assembly can access the members. Don’t get confused it means that the class of different project who is inheriting this class will be able to access the member. You can see that as shown below.

Main class of Project1 named as SilverCustomer.
  1. using System;  
  2. namespace Project1  
  3. {  
  4.     public class SilverCustomer  
  5.     {  
  6.         protected internal string CustomerName = "saillesh";  
  7.     }  
  8. }  
Now in other project I have created Platinum Customer Class,
  1. using System;  
  2. using Project1; //using the project1 namespace  
  3. namespace InternalExample  
  4. {  
  5.     public class PlatinumCustomer: SilverCustomer //inheriting the SilverCustomer Class  
  6.     {  
  7.         public void details()  
  8.         {  
  9.             PlatinumCustomer obj = new PlatinumCustomer();  
  10.             obj.CustomerName = "Ankit Negi";  
  11.             we can see that SilverCustomer protected Intenal member is accessible to other project  
  12.         }  
  13.     }  
  14. }  
Conclusion

Here we complete our day 2. In Day 3 we will take our C# class to next level. If any confusion you can comment for the same. Add on information is heartily welcomed. 


Recommended Free Ebook
Similar Articles