神刀安全网

Learn Tiny Bit Of C# In 7 Days – Day 3

Before reading this article, I highly recommend reading my previous parts:

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

  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 learning tiny bit of C#.

Interface

Interface is like a class that cannot contain 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      }   
  • Interface cannot contain Fields (variables)

    E.g.

    public interface ICustomer   {      int CustomerName;   }   

    If we try to declare a field inside an Interface we face a compile time error saying Interface cannot contain fields. We can declare a public.
    Learn Tiny Bit Of C# In 7 Days - Day 3

  • Interface member cannot have a definition.
    This means that a function of Interface cannot have its definition of its own.
    E.g.
    public interface ICustomer   {       void Print()       {           Console.WriteLine("Hello");       }   }   

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

How to implement Interface

As we inherit a class in C# using (:) same we have to do when we want to implement an Interface.

  • We need to Implement the Interface members,
    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   {}   

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

  • When we implement the Interface the members should be Public,
    E.g.
    public interface ICustomer   {       int _Name       {           get;           set;       }       void Print();   }   public class Customer: ICustomer   {       public int _Name       {           get           {               throw new NotImplementedException();           }           set           {               throw new NotImplementedException();           }       }       void Print()       {           throw new NotImplementedException();       }   } * Implement the Interface members   public interface ICustomer   {       int _Name       {           get;           set;       }       void Print();   }   public class Customer: ICustomer   {       public int _Name       {           get           {               throw new NotImplementedException();           }           set           {               throw new NotImplementedException();           }       }       public 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.

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

Now once we implement the interface the above mentioned error gets resolved.

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

We can see the command prompt window with the output:

What if a Class implementing an Interface inherits another Interface

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 following error:

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

When a class implements an Interface which inherits other Interface then the class has to provide the implementation for both the Interface methods.

public class Customer: Icustomer2   {       public void Print2()       {           Console.WriteLine("ICustomer2 Method");       }       public void Print()       {           Console.WriteLine("ICustomer1 Method");       }   }   

Now once I implement the other Interface method and try to build the application it gets successfully build.

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

We cannot create an instance of Interface, but an Interface reference variable can be pointed towards a class object which is implementing the Interface.

Now the question comes why we should use Interface: 

  1. ENFORCE the Standardization/ consistency(Contract)
  2. Decoupling

ENFORCE the Standardization/ consistency (Contract)

In law, a contract (or informally known as an agreement in some jurisdictions) is an agreement having a lawful object entered into voluntarily by two or more parties, each of whom intends to create one or more legal obligations between them. Source: Wikipedia.

Basically by the words contract we mean that class will implement all methods of Interface. Class that implements the Interface here signs the Contract that I will implement all the methods, etc. of the Interface. We will be showing the example for the same in the following example.

Decoupling

Decoupling as the word specifies dissociate (something) from something else, so here in programming world decoupling stand where we separate the dependency between our business layer concrete classes, UI layer and DAL Layer as shown below. As we have seen we cannot create an object of the Interface, but an Interface reference variable can point towards a derived class object.

So let’s get started we will create a Registration Page where we will be inserting the User Details into the database without directly calling BAL or DAL from the concrete classes rather we will call these classes via an Interface. This topic will be little bit difficult to understand. Please focus and try to go with a practical  implementation.

So switch to Visual Studio:

  • I have created a web application named TestInterface which is basically a Web Form based application.
  • We create a UI as shown below:
    Learn Tiny Bit Of C# In 7 Days - Day 3

So when we create an Enterprise application we should make them in 3 layer architecture which means UI, BAL (Business Layer or Concrete classes) and DAL Data Access Layer.

So we have created our UI which generally talk to the concrete classes and then the concrete classes talk with DAL class to insert or update or delete information and vice versa. In this scenario we make a strong coupling between our Layers that means our Layers are not decoupled from each other in order to make them decoupled we make use of an Interface.

  • Now we will create our Business Class called User.cs which will contain properties related to the user like FirstName, LastName, Address and MobileNo)
  • We create an Interface called ICRUD (Create, Read, Update and Delete) where we will define our Methods that will be enforced to be implemented by the User Class.
  • We create our IRegister Interface which will implement ICRUD and contains properties as in the following:
    public interface IRegister   {         string FirstName { get; set; }      string LastName { get; set; }      string Address { get; set; }      string MobileNo { get; set; }      }    
  • Now we will also create an Interface responsible for communicating between our BAL and DAL layer and will also decide which DB to be used. (SQL Server or oracle).
    public interface IDb   {       /// <summary>       /// Insert to method will take 4 parameters to save the information to the db       /// and return the generated ID for the User and same will be displayed to the User       /// </summary>       /// <param name="_FirstName">Coming from BAL RegisterUser _FirstName property</param>       /// <param name="_LastName">Coming from BAL RegisterUser _LastName property</param>       /// <param name="_Address">Coming from BAL RegisterUser _Address property</param>       /// <param name="_MobileNo">Coming from BAL RegisterUser _MobileNo property</param>       /// <returns></returns>       int Insert(string _FirstName, string _LastName, string _Address, string _MobileNo);   }   

Here I have only created one method while we can create all the operations that we need to perform as per our business requirements.

Now once we have created our Interface let us implement the Interface in our BAL class.

using System;   using System.Collections.Generic;   using System.Linq;   using System.Text;   using System.Threading.Tasks;   using 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();               }           }           public int InsertUser()           {               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.

public interface ICustomer   {      int CustomerName;   }   

0

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 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.

public interface ICustomer   {      int CustomerName;   }   

1

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 improvised with other design patterns.

public interface ICustomer   {      int CustomerName;   }   

2

Now once we have implemented the Factory class let’s get the Information from UI and try to insert the same.

public interface ICustomer   {      int CustomerName;   }   

3

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.

public interface ICustomer   {      int CustomerName;   }   

4

Now once the User enters the information IRegister will call Factory class to create object of User and IRegister will refer towards User Class.

public interface ICustomer   {      int CustomerName;   }   

5

IRegister reference object will call InsertUser method and pass IDb reference object and at the User class same will be received and then Idb will communicate with DAL layer.

public interface ICustomer   {      int CustomerName;   }   

6

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. Let’s run our application and see how it works.

Phase 1

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

Phase 2:IDb referencing towards SqlServer Class,

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

Phase 3:Loading connection string,

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

Phase 4:Register Page Appear,

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

Phase 5:As soon as User Enters the information.

Factory class getRegisterObject function will be called and Iregister reference variable will point towards User class,

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

Phase 6:Creation of User Object,

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

Phase 7:Setting User Information into properties of Class.

We can clearly see that all work is done by Interface we are not creating any object of class Interface communicating with all.

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

Phase 8:Class method InsertUser will be called and Reference variable of IDb will be passed which point towards the DB which we want to use.

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

Phase 9:Here we can see Idb ibj contains reference variable towards SQL Server, now all the fields value will be passed to the db Insert function. As shown below we have used _UsedId field to receive the generated UserId of the User.

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

Phase 10:Now SQl server class method will be called by IDb interface and the queries are executed and the generated UserId will be returned back to User UI screen.

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

Phase 11:Showing UserId generated and same will be returned to User UI.

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

So here we learnt how Interface helps us to follow the standardization of Vocabulary and helps in Decoupling. I hope all phases would be helpful so that you can learn them phase by phase. I have attached the project and will request you to execute the same.

Explicit Interface

Think of a scenario where we have two Interfaces with same method name then how we will be able to tell the method which we implemented is of which Interface.

public interface ICustomer   {      int CustomerName;   }   

7

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.

public interface ICustomer   {      int CustomerName;   }   

8 Learn Tiny Bit Of C# In 7 Days - Day 3

Hereby 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 object of the same but we can inherit the Abstract class in our child classes. 

  • Abstract Class only comes in Inheritance hierarchy i.e. Is A relationship.
  • Abstract is used in order to remove duplication in Inheritance model using Generalization and Specialization relationship.

Abstract keyword is used to create Abstract class e.g.:

public interface ICustomer   {      int CustomerName;   }   

9

An Abstract Class can contain abstract methods i.e. that only contain definition they don’t 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.

public interface ICustomer   {       void Print()       {           Console.WriteLine("Hello");       }   }   

0

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.

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

i.e. Abstract methods cannot contain implementation.

As discussed above we cannot create object of the Abstract class. Let us try the same, so as soon as we create an instance of the Abstract class. Abstract class can be used as a Base class for other classes.

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

When we declare a method as Abstract and we inherit the Abstract class we have to implement the Abstract method otherwise it will throw an exception.

public interface ICustomer   {       void Print()       {           Console.WriteLine("Hello");       }   }   

1 Learn Tiny Bit Of C# In 7 Days - Day 3

But if we don’t 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.

In order to implement abstract methods in Derived class we have to use override in the abstract methods of Abstract class. Small example is shown below:

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

Here Employee is a generalized entity which has generalized properties which later inherited and override by the Child entity to define specialized relationship.

Like Consultant Employee, FullTime Employee.

public interface ICustomer   {       void Print()       {           Console.WriteLine("Hello");       }   }   

2

In derived class the abstract method of Abstract class should be of same return type and definition otherwise it will show error. 

  • Non Abstract Methods:

    If we declare method without Abstract keyword it is a Non Abstract method i.e. that means it’s not mandatory to have Abstract members in Abstract class.

  • We cannot create an object of the Abstract class but we can point the Abstract class object to the child class object as in the following example:
    public interface ICustomer   {       void Print()       {           Console.WriteLine("Hello");       }   }   

    3

  • Abstract class cannot be Sealed.
    Learn Tiny Bit Of C# In 7 Days - Day 3

Why and when should we use Abstract class

Lets’ take an example if we implement the above example doing Inheritance method and creating a concrete class as base and child class Fulltime Employee and Parttime Employee inheriting the Base Class BaseEmployee.

We would be able to create the object of the BaseEmployeeClass, where in real time we only have two employees FullTime and PartTime so it would be wrong if we allow developers the object creation of BaseEmployeeClass. So we want to prevent them to create instance of the BaseEmployee. To solve this problem we use the concept of Abstract class. Once we mark the class as Abstract we cannot create object of the Abstract classes, preventing us from creating object of BaseEmployeeClass.

Hence I can conclude that we should use Abstract class when we want to move common functionality of two or more classes into a single base class and when we don’t want anyone to instantiate the base class.

Abstract classes vs Interface

Abstract Interface
Abstract classes can have implementation for some of its members. Interface cannot have implementation for any of its members.
Abstract class members are by default Private Interface members are by default Public (they cannot have access modifiers)
Abstract class can have fields. Interface cannot contain fields.
• A class can implement multiple interfaces at the same time.• A class cannot inherit multiple classes at the same time.
Abstract classes can be inherited from a class Interface can only be inherited from an Interface.
Abstract classes are used when we want to share common functionality in parent child relationship, which cannot be initiated. Interfaces are used to define the contract enforce the standardization, decoupling
Abstract classes are inherited Interface are implemented
Abstract class member can have Access Modifiers. Interface members are Public because purpose of an interface is to enable other types to access a class or struct. No access modifiers can be applied to interface members.

原文  http://www.c-sharpcorner.com/UploadFile/cb1429/learn-tiny-bit-of-C-Sharp-in-7-days-day-3784/

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Learn Tiny Bit Of C# In 7 Days – Day 3

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮