Académique Documents
Professionnel Documents
Culture Documents
1. Namespaces
2. Classes
3. Abstraction
4. Encapsulation
5. Inheritance
6. Properties
7. Access Modifiers
Before going ahead I would strongly recommend you to watch and learn .net in 60 days
series for in depth practical knowledge of c#.
Day 3 Agenda
1. Interface
2. Abstract class
3. Abstract classes vs Interface
In Day 3 we have kept few topics but these topics are important that need in
depth knowledge in order to understand them, I hope that you will enjoy Day
3 of Learn tiny bit of C#.
Interface
Interface is like a class that cannot contains the definition i.e. it contains
empty events, methods and properties. We create Interface using interface
keyword. Just like classes interface contains properties, methods, members,
delegates or event but only declaration and no implementation.
In one term we call Interface as a Contract because they force the class to
follow the contract between Class and Interface.
SYNTAX:
interface ICustomer //Write Interface and name of Interface
{
void Bonus();//definition of method
}
E.g.
public interface ICustomer
{
int CustomerName;
}
If we just implement the Interface and does not implement the properties or function it will threw
a compile time error as shown below:
public interface ICustomer
{
int _Name { get; set; }
void Print();
}
public class Customer : ICustomer
{
E.g.
void Print()
{
throw new NotImplementedException();
}
namespace Interface
{
interface ICustomer
{
void Bonus();
}
class Customer:ICustomer //implementing Interface
{
public void Bonus() //implementing the function of ICustomer Interface
{
Console.WriteLine("Bonus of this year");
Console.ReadLine();
}
}
Interface member are public by default, and they allow explicit modifiers if a
class inherits from an interface it must provide implementation for all
interface members. Otherwise, we get a compiler error, as shown below.
Now once we implement the interface the above mentioned error gets
resolved.
using System;
namespace Interface
{
interface ICustomer
{
void Print();
}
interface Icustomer2:ICustomer
{
void Print2();
}
public class Customer:Icustomer2
{
public void Print2()
{
Console.WriteLine("ICustomer2 Method");
}
}
class Program
{
static void Main(string[] args)
{
Customer objCustomer = new Customer();
objCustomer.Print2();
}
}
}
Now once I try to build the same I face the below error:
I.E. when a Class implements an Interface which inherits the other Interface
than the Class has to provide the implementation for both the Interface
methods.
Now once I implement the other Interface method and try to build the
application. The application gets successfully build.
Decoupling
Now we will create our Business Class called User.cs which will contain
properties related to the User like (FirstName, LastName, Address and
MobileNo).
Here I have only created on method while we can create all the operations
that we need to perform as per our Business requirements.
Now once we have create our Interface lets implement the Interface in our
BAL class
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
Interface;
namespace BAL
{
public class User:IRegister
{
public string FirstName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string LastName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string Address
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string MobileNo
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
*Note- Our IRegister Interface implements ICRUD interface so now class has
to implement both the functionality of IRegister as well as ICRUD Interface as
shown above.
We will write our implementation functionality for UserClass .
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Threading.Tasks;
Interface;
namespace BAL
{
public class User:IRegister
{
private int _UserId;
private string _FirstName;
private string _Address;
private string _LastName;
private string _MobileNo;
public string FirstName
{
get
{
return _FirstName;
}
set
{
_FirstName = value;
}
}
public string LastName
{
get
{
return _LastName;
}
set
{
_LastName = value;
}
}
public string Address
{
get
{
return _Address;
}
set
{
_Address = value;
}
}
public string MobileNo
{
get
{
return _MobileNo;
}
set
{
_MobileNo = value;
}
}
public int InsertUser(IDb obj)
{
_UserId= obj.Insert(_FirstName,_LastName,_Address,_MobileNo);
return _UserId;
}
*Note: Here IDb Interface will communicate between BAL and DAL layer and
will also decide which DB server will be used Sql server or Oracle.
Now we will create or DAL layer. Here I am not using stored procedure to
insert User Records to the Database but will request you to use stored
procedure for the same.
using System;
using System.Collections.Generic;
using System.Linq;
using
using
using
using
using
using
using
System.Text;
System.Threading.Tasks;
System.Data;
System.Data.SqlClient;
System.Data.OracleClient;
Interface;
System.Configuration;
namespace DAL
{
public class SqlServer : IDb
{
//connection string
static private string connectionString;
//sql connection
static private SqlConnection con;
static SqlServer()
{
connectionString = ConfigurationManager.ConnectionStrings["SqlDB"].ConnectionString;
con = new SqlConnection(connectionString);
}
public int Insert(string firstName, string lastName, string mobileNo, string addreess)
{
try
{
string query = "insert into tblRegistration values ('" + firstName + "','" + lastName +
"','" + mobileNo + "','" + addreess + "')";
//creating sql command object and passing query and connection object
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteScalar();
string query2 = "select IDENT_CURRENT('tblRegistration')";
SqlCommand cmd2 = new SqlCommand(query2, con);
decimal value = (decimal)cmd2.ExecuteScalar();
return Convert.ToInt32(value);
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
finally
{
con.Close();
}
}
Now here we have created our DAL class which implements IDb Interface
which works as a communication between BAL and DAL layer. It has only one
method as shown above:
Now in the UI rather than creating an object of the Business class we give
this job to a Factory Class which will be responsible for creating objects of the
desired class which is needed. Factory class basically is a type of creational
pattern. As we know that Interface cannot create object of its own but it can
reference to the object of the implemented class. Here we have only one
class but in real time project we will have lots of classes this may vary for the
same and can be improvise with other design patterns.
using Interface;
using BAL;
namespace Factory
{
public class Factory
{
public static IRegister getRegisterobject()
{
return new User();
}
}
}
Now once we have implemented the Factory class lets get the Information
from UI and try to insert the same.
using System;
using Interface;
using System.Configuration;
using DAL;
namespace TestInterface
{
public partial class Register : System.Web.UI.Page
{
IDb objIDB = null;
string DBname=ConfigurationManager.AppSettings["DB"].ToString().ToLower();
protected void Page_Load(object sender, EventArgs e)
{
if(DBname=="oracle")
{
objIDB = new Oracle();
}
else
{
objIDB = new SqlServer();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
IRegister objRegister = Factory.Factory.getRegisterobject();
setObjectFromUi(objRegister);
int Id = objRegister.InsertUser(objIDB);
Response.Write("User Registered successfully with UserId " + Id);
}
private void setObjectFromUi(IRegister userInformation)
{
userInformation.FirstName = txtFirstName.Text;
userInformation.LastName = txtLastName.Text;
userInformation.MobileNo = txtMobile.Text;
userInformation.Address = txtAddress.Text;
}
}
Here at the start of the application we check from the web.config file which
DB to be used based upon the entry IDb Interface will reference towards the
Sql Server or Oracle Server.
Now once the User enters the information IRegister will call Factory class to
create object of User and IRegister will refer towards User Class.
setObjectFromUi(objRegister);
int Id = objRegister.InsertUser(objIDB);
IRegiter reference object will call InsertUser method and pass IDb reference object and at the
User class same will be received and than Idb will communicate with DAL layer.
public int InsertUser(IDb obj)
{
_UserId= obj.Insert(_FirstName,_LastName,_Address,_MobileNo);
return _UserId;
}
We can see that there is no object creation of Concrete class and Db classes
rather Interface has been used to reference to those classes making our
project decoupled from each other. Lets run our application and see how it
works.
Phase 1
Phase 9: Here we can see Idb ibj contains referenece variable towards Sql Server,
now all the fields value will passed to the db Insert function as shown below we
have used _UsedId field to receive the generated UserId of the User.
Phase 10: Now Swl server class metho will be called by IDb interface and the
queries are executed and the genrated UserId will be returned back to User UI
screen.
Phase 11: Showing UserId generated and same will be returned to User UI.
Explicit Interface
Think of a scenario where we have two Interfaces with same method name
than how we will be able to tell the method which we are implemented is of
which Interface?
Here as you can see there are two Interface IPrintSony and IPrintHP.
Customer class is implementing both the Interface and implementing the
methods, we run the program and found that it runs. So how do we figure out
which interface method was called so in order to achieve that we make use
of Explicit Interfaces as shown below.
namespace ConsoleApplication1
{
public interface IPrintSony
{ void Print();
}
public interface IPrintHP
{ void Print();
}
public class Customer:IPrintHP,IPrintSony
{
void IPrintSony.Print()
{
Console.WriteLine("I am an IPrintSony Interface function");
Console.ReadLine();
}
void IPrintHP.Print()
{
Console.WriteLine("I am an IPrintHP Interface function");
Console.ReadLine();
}
public static void Main()
{
Customer objCustomer = new Customer();
((IPrintHP)objCustomer).Print();
((IPrintSony)objCustomer).Print();
}
}
}
Here by I conclude that once the class explicitly implements the Interface the
Interface member can no longer be accessed through class reference
variable, but only via Interface reference variable as shown above.
Abstract Class
An Abstract class is a half defined Base class in C# and we cannot create the
object of the Abstract class. You can create your own Abstract class by using
the modifier called Abstract. An abstract class means we cannot create of
object of the same but we can inherit the Abstract class in our Child classes.
An Abstract Class can contain abstract methods i.e. that only contain
definition they dont have implementation of their own, abstract methods
implementation is done in Child or Derived classes otherwise it will throw
error note(all the child has to implement all abstract methods). Abstract
method can also contain non abstract methods.
namespace AbstractClass
But if I try to give implementation to the abstract class we will face an Error.
We cannot define an Abstract class as static or sealed(it will not be
inherited). We cannot define the access modifier for Abstract class it is by
default Public.
But if we dont want to provide the implementation for the Abstract method
we can put Abstract keyword in class Program, it will not throw an error and
will mark it as an Abstract class i.e. that means this Abstract class has some
Abstract members.
}
class Consultant:Customer
{
public int HourlySalary { get; set; }
public override void Details()
{
Console.WriteLine("The Consultant name {0} , id {1} and Hourly salary is
{2}",this.ID,this.UserName,this.HourlySalary);
}
}
class Fulltime : Customer
{
using System;
namespace AbstractClass
{
class Program
{
static void Main(string[] args)
{
Consultant objcons = new Consultant();
objcons.HourlySalary = 4000;
objcons.ID = 1;
objcons.UserName = "Akansha Bakshi";
objcons.Details();
Console.ReadLine();
}
}
}
We cannot create an object of the Abstract class but we can point the
Abstract class object to the child class object as shown in below
example:
Abstract
Interface