Learn Tiny Bit of C# in 7 Days - Day2
Learn Tiny Bit of C# in 7 Days - Day2
Introduction
We have successfully completed day1 before coming here.
Day 2 Agenda
1.
2.
3.
4.
5.
6.
7.
Namespaces
Classes
Abstraction
Encapsulation
Inheritance
Properties
Access Modifiers
If would recommend watching videos from below image for full in depth
topics. Just click on the below image you would be navigated to the Videos.
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.
System.Console.WriteLine("Learn C# in 7 days!");
{
class B
{
So now when we want to access the print function of OMSTeam we will just
use below code
class Program
{
static void Main(string[] args)
{
ProjectA.OMSTeam.B.print(); //Namespace.Namespace.ClassName.Method
}
}
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
ProjectA.OMSTeam;
ProjectA.PromoTeam;
class Program
{
static void Main(string[] args)
{
A.print();
}
}
namespace ProjectA
{
namespace PromoTeam
{
class A
{
}
namespace ProjectA
{
namespace OMSTeam
{
class A
{
}
But when we try to access the OMSTeam class the complier shows following error
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:
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
Omsteam=ProjectA.OMSTeam;//giving alias name to Namespace
PromoTeam = ProjectA.PromoTeam; //giving alias name to Namespace
class Program
{
static void Main(string[] args)
{
Omsteam.A.print();
Omsteam.A.print();
}
}
Now in order to use these Namespace we need to add them in our project by
adding them in references.
We will check the checkbox and select both of them to be used in our project.
using
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
OmsTeam= ProjectA.OmsTeam; //using the namespace with alias name
PromoTeam=ProjectA.PromoTeam; //using the namespace with alias name
class Program
{
static void Main(string[] args)
{
OmsTeam.Article.print(); //calling the print method
PromoTeam.Article.print();//calling the print method
Console.ReadLine();
}
}
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
namespace ClassDef
{
class Employee
{
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 is created the Class Constructor is called. Constructors are
used for object initialization and memory, fields allocation of its
class.
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
namespace ClassDef
{
class Employee
{
string _Name;
int _Age;
public Employee( string Name,int Age)
{
this._Name = Name; //this is points towards object of this classs
this._Age = Age;
}
public void Information()
{
Console.WriteLine("The Information of the Employee is Name={0} and
Age={1}",_Name,_Age);
Console.ReadLine();
}
}
}
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
namespace ClassDef
class Program
{
static void Main(string[] args)
{
Employee obj = new Employee("Saillesh",26);
obj.Information();
}
}
As we go ahead we will see how to use properties and assigning 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.
As I said object is instance of a class, i.e. we can say that a birth or creation
of object is called instantiation.
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:
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 inessential 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 hided
from the external User.
CreateMOM()
When this function executes it first it adds the Meeting Name, Segments
(Retails, Audit, Operational etc.) creates 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 shown below:
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
System.Data.SqlClient;
//Abstraction Namespace
namespace Abstraction
{
/// <summary>
/// Meeting Class contains list of Properties and functions for the Meeting Creation
/// </summary>
class Meeting
{
set
{
_Name = value;
}
try
{
this._Id = AddandGetMeetingId(_Name, _Format, _Location);
bool Status = AdduploadedFiles(this._Id,_FileUploaded);
if(Status ==true)
{
return true;
}
else
{
return false;
}
}
catch(Exception ex)
{
Now here I have set the Class properties _id private and function
AddandGetMeetingId and AdduploadedFiles as private because I dont 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.
We can see from above diagram that only required information is shown the
User. User access the class method as shown below
try
{
Console.WriteLine("Enter the Meeting Name");
objMeeting.Name = Console.ReadLine();
Console.WriteLine("Enter the Format Name");
objMeeting.Format = Console.ReadLine();
Console.WriteLine("Enter the Meeting Location");
objMeeting.Location = Console.ReadLine();
Console.WriteLine("Enter the file Uploaded");
objMeeting.FileUploaded = Console.ReadLine();
bool status = objMeeting.InsertToDb();
if(status==true)
{
Console.WriteLine("Minutes of Meeting Created Successfully");
}
else
{
Console.WriteLine("Failed to Created Minutes of the Meeting");
}
Console.ReadLine();
}
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
System.Data.SqlClient;
System.Configuration;
namespace Abstraction
{
public class DAL
{
public static SqlConnection con;
static DAL()
{
con=new SqlConnection(
ConfigurationManager.ConnectionStrings["DBclass"].ConnectionString);
}
public int CreateMom(string MtngName,string FrmtName,string Location)
{
try
{
string query = "insert into tblMeetingMaster values ('" + MtngName + "','" + FrmtName
+ "','" + Location + "')";
SqlCommand cmd = new SqlCommand(query, DAL.con);
con.Open();
cmd.ExecuteScalar();
string query2 = "select IDENT_CURRENT('tblMeetingMaster')";
SqlCommand cmd1 = new SqlCommand(query2,DAL.con);
decimal value = (decimal)cmd1.ExecuteScalar();
return Convert.ToInt32(value);
}
catch (Exception ex)
{
"')";
try
{
string query = "insert into tblFileUploaded values ('" + MeetingId + "','" + FileName +
SqlCommand cmd = new SqlCommand(query, DAL.con);
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
return false;
throw new Exception(ex.Message);
}
finally
{
con.Close();
con.Dispose();
}
}
}
}
Values inserted in DB
Inheritance
From the above Diagram you can predict there are two Classes Football
Player, Cricket player 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.
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
namespace Inheritance
{
public class Player
{
public string PlayerName;
public string ClubName;
public string PlayGround;
public void PlayerDetails()
{
Console.WriteLine("THE Player details are PlayerName {0}, Registered to{1} playing in
{2}",PlayerName,ClubName,PlayGround);
Console.ReadLine();
}
}
public class CricketPlayer:Player
{
public int Runscored;
}
public class FootballPlayer : Player
{
public int GoalScored;
}
}
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.
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
namespace ParentClassConstructor
{
public class Parent
{
public Parent()
{
Console.WriteLine("Parent class constructor called");
Console.ReadLine();
}
}
public class Child : Parent
{
public Child()
{
Console.WriteLine("Child class constructor called");
Console.ReadLine();
}
class Program
{
static void Main(string[] args)
{
Child objChild = new Child();
}
}
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.
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
But as we can see below we are able to change the values and assigned
the same to our fields.
Console.WriteLine("the values of the new object are ID {0} ,NAME {1}, MARKS {2} ",
obj.ID, obj.NAME,obj.MARKS);
Console.ReadLine();
}
}
When I execute the application we will see that all are Business rules
has been violated and there is no message to the user for the same.
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 wont be
accessible to the external world.
Now we write to methods for set and get i.e. SetId, GetId to control
whats get into the fields and what set into the fields of class.
Now I initialize the object of Employee class we find that we are not
able 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
Now I as I set the value of id as -100 and than call the obj.Getid we see how the flow
of program goes.
STEP1. Once the object is created we try to set the value of _id=-100
STEP2. As the id value passed is less than 1 it enters the exception and
throw a new exception for the same.
STEP 3. It enters the catch block and will print the exception message
as shown below.
Now we input a correct value which is greater than 1 and print the
value using getId function as shown below.
So now we can see that these methods are allowing us to control over
what gets assigned and returned.
Now we will see how we in C# we implement Properties in order to
hide complexity from the User (Encapsulation).
In order to use a property you have to write
Or we can use code snippet shortcut prop and press tab for the same.
And for getting the values of the id we have to just write object name
than property name, it invokes the id provide and it invokes the get
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 want an only read only field like pi in maths that is 3.14 or
other ready only fields as per business logics.
For this we need to make our property with only get accessor
Eg. Here I am taking an example of bonus which is same for all
employees in order to make it a read property will assign only get
accessor to it as shown below.
And if in case you want to make a property you want to write only than
you have to use only set accessor.
Auto Implemented Properties: As earlier discussed short cut for
property prop, actually Microsoft introduces auto implemented
properties in C# 3.0 for scenarios where we dont want to inject any
logic Eg. City etc. In Auto Implemented we dont 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
Eg. 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 dont 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 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
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
namespace AccessModifier
{
public class Customer
{
private int _id;//declared with private
private string _CustomerName;
public int id //public property with get and set accessor
{
get
return id;
}
set
{
}
id = value;
CustomerName = value;
Now once I try to access the private property outside the class I wouldnt be
able to access them due to its protection level.
If I try to access the public members there are no errors and we can easily
access them.
namespace AccessModifier
{
class Program
{
static void Main(string[] args)
{
Customer c1 = new Customer();
c1.id = 1;
c1.CustomerName = "saillesh";
}
}
}
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
using System;
namespace AccessModifier
{
public class Customer
{
protected int _id;
protected string _CustomerName;
public int id
{
get
{
return id;
}
set
{
}
id = value;
CustomerName = value;
}
public class GoldCustomer : Customer
{
private float _Discount;
public float Discount
{
get
return _Discount;
}
set
{
_Discount = value;
}
}
public void PrintDetails()
{
GoldCustomer cust = new GoldCustomer();//creating object of child class
cust._id = 1; ///we can access the protected value of parent class
cust._CustomerName = "Nishant"; //same goes here
}
}
}
Calling Program.cs
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.
Now once I try it from other main project let see what happens so for the
same I have added Project1 class to main project to use the same
As shown below
using System;
using Project1;//using the Namespace
namespace InternalExample
{
class Program
{
static void Main(string[] args)
{
SilverCustomer objSilver = new SilverCustomer();
}
}
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 the
compile time error.
Conclusion
Here we complete our day 2. In Day 3 we will take our C# class to next
Contents. If any confusion you can comment for the same. Add on
information is heartily welcomed.