RESTful Day #1: Enterprise Level Application Architecture with Web API’s using Entity Framework, Generic Repository Pattern and Unit of Work


Introduction

I have been practicing, reading a lot about RESTful services for past few days. To my surprise I could not find a complete series of practical implementations of ASP.NET Web API’s on the web. My effort in this series will be to focus on how we can develop basic enterprise level application architecture with Web API’s.
We’ll be discussing less theory and doing more practical to understand how RESTful services can be created using an ORM, we choose Entity Framework here. My first article in the series is to set up a basic architecture of REST service based application. Later on in my upcoming articles, I’ll explain how we can follow best standards to achieve enterprise level architecture.

Roadmap

 My road for the series is as follows,
I’ll purposely use Visual Studio 2010 and .NET Framework 4.0 because there are few implementations that are very hard to find in .NET Framework 4.0, but I’ll make it easy by showing how we can do it.

REST

Here is an extract from Wikipedia,
Unlike SOAP-based web services, there is no “official” standard for RESTful web APIs. This is because REST is an architectural style, while SOAP is a protocol. Even though REST is not a standard per se, most RESTful implementations make use of standards such as HTTP, URI, JSON, and XML.
I agree to it . Let’s do some coding.

Setup database

I am using SQL Server 2008 as a database server. I have provided the sql scripts to create the database in Sql Server, you can use the same to create one.I have given WebApiDb as my database name. My database contains three tables for now, Products, Tokens, User. In this tutorial we’ll only be dealing with product table to perform CURD operations using Web API and Entity framework. We’ll use Tokens and User in my upcoming article. For those who fail to create database through scripts, here is the structure you can follow,

Web API project

Open your Visual Studio, I am using VS 2010, You can use VS version 2010 or above.
Step 1: Create a new Project in your visual studio,
Step 2: There after choose to create ASP.NET MVC 4 Web application, and give it a name of your choice, I gave itWebAPI.
Step 3: Out of different type of project templates shown to you, choose Web API project,
Once done, you’ll get a project structure like shown below, with a default Home and Values controller.
You can choose to delete this ValuesController, as we’ll be using our own controller to learn.

Setup Data Access Layer

Let’s setup or data access layer first. We’ll be using Entity Framework 5.0 to talk to database. We’ll use Generic Repository Pattern and Unit of work pattern to standardize our layer.
Let’s have a look at the standard definition of Entity Framework given by Microsoft:
“The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. The Entity Framework’s ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals.”
In simple language, Entity framework is an Object/Relational Mapping (ORM) framework. It is an enhancement to ADO.NET, an upper layer to ADO.NET that gives developers an automated mechanism for accessing and storing the data in the database.
Step 1 : Create a new class library in your visual studio, and name it DataModel as shown below,
Step2: In the same way, create one more project i.e. again a class library and call it BusinessEntities,
I’ll explain the use of this class library soon.
Step 3: Move on to your DataModel project , right click on it and add a new item, in the list shown, choose ADO.NET Data Model, and name it WebApiDataModel.edmx.
The file .edmx will contain the database information of our database that we created earlier, let’s set up this. You’ll be presented a wizard like follows,
Choose, generate from database. Choose Microsoft SQl Server like shown in the following image,
Click continue, then provide the credentials of your database, i.e. WebAPIdb, and connect it,
You’ll get a screen, showing the connection string of the database we chose,
Provide the name of the connection string as WebApiDbEntities and click Next.
Choose all the database objects, check all the check boxes, and provide a name for the model. I gave it a name WebApiDbModel.
Once you finish this wizard, you’ll get the schema ready in your datamodel project as follows,
We’ve got our schema in-place using Entity Framework. But few work is still remaining. We need our data context class and entities through which we’ll communicate with database.
So, moving on to next step.
Step 3: Click on tools in Visual Studio and open Extension manager. We need to get db context generator for our datamodel. We can also do it using default code generation item by right clicking in the edmx view and add code generation item, but that will generate object context class and that is heavier than db context. I want light weighted db context class to be created, so we’ll use extension manager to add a package and then create a db context class.
Search for Entity Framework Dbcontext generator in online gallery and select the one for EF 5.x like below,
I guess you need to restart Visual studio to get that into your templates.
Step 4 : Now right click in the .edmx file schema designer and choose “Add Code Generation Item..”.
Step 5 : Now you’ll see that we have got the template for the extension that we added, select that EF 5.x DbContext Generator and click Add.
After adding this we’ll get the db context class and its properties, this class is responsible for all database transactions that we need to perform, so our structure looks like as shown below,
Wow, we ended up in errors. But we got our db context class and our entity models, You can see them in our DataModel project. Errors? Nothing to worry about, it’s just we did not reference entity framework in our project. We’ll do it right away.
Step 6 : Go to Tools -> Library Packet Manager->Packet manager Console. You’ll get the console in left bottom of Visual studio.
Select dataModel project and write a command “Install-Package EntityFramework –Version 5.0.0” to install Entity Framework 5 in our DataModel project.
Press enter. And all the errors get resolved.

Generic Repository and Unit of Work

You can read about repository pattern and creating a repository in detail from my article :https://codeteddy.com/2013/09/03/learning-mvc-part-5repository-pattern-in-mvc3-application-with-entity-framework/.
Just to list down the benefits of Repository pattern,
  • It centralizes the data logic or Web service access logic.
  • It provides a substitution point for the unit tests.
  • It provides a flexible architecture that can be adapted as the overall design of the application evolves.
We’ll create a generic repository that works for all our entities. Creating repositories for each and every entity may result in lots of duplicate code in large projects.For creating Generic Repository you can follow : https://codeteddy.com/2013/09/03/learning-mvc-part-6-generic-repository-pattern-in-mvc3-application-with-entity-framework/
Step 1: Add a folder named GenericRepository in DataModel project and to that folder add a class named Generic Repository. Add following code to that class, that servers as a template based generic code for all the entities that will interact with database,
#region Using Namespaces...

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;

#endregion

namespace DataModel.GenericRepository
{
/// <summary>
    /// Generic Repository class for Entity Operations
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public class GenericRepository where TEntity : class
    {
#region Private member variables...
internal WebApiDbEntities Context;
internal DbSet DbSet;
#endregion

#region Public Constructor...
/// <summary>
        /// Public Constructor,initializes privately declared local variables.
        /// </summary>
        /// <param name="context"></param>
        public GenericRepository(WebApiDbEntities context)
        {
this.Context = context;
this.DbSet = context.Set();
        }
#endregion

#region Public member methods...

/// <summary>
        /// generic Get method for Entities
        /// </summary>
        /// <returns></returns>
        public virtual IEnumerable Get()
        {
            IQueryable query = DbSet;
return query.ToList();
        }

/// <summary>
        /// Generic get method on the basis of id for Entities.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public virtual TEntity GetByID(object id)
        {
return DbSet.Find(id);
        }

/// <summary>
        /// generic Insert method for the entities
        /// </summary>
        /// <param name="entity"></param>
        public virtual void Insert(TEntity entity)
        {
            DbSet.Add(entity);
        }

/// <summary>
        /// Generic Delete method for the entities
        /// </summary>
        /// <param name="id"></param>
        public virtual void Delete(object id)
        {
            TEntity entityToDelete = DbSet.Find(id);
            Delete(entityToDelete);
        }

/// <summary>
        /// Generic Delete method for the entities
        /// </summary>
        /// <param name="entityToDelete"></param>
        public virtual void Delete(TEntity entityToDelete)
        {
if (Context.Entry(entityToDelete).State == EntityState.Detached)
            {
                DbSet.Attach(entityToDelete);
            }
            DbSet.Remove(entityToDelete);
        }

/// <summary>
        /// Generic update method for the entities
        /// </summary>
        /// <param name="entityToUpdate"></param>
        public virtual void Update(TEntity entityToUpdate)
        {
            DbSet.Attach(entityToUpdate);
            Context.Entry(entityToUpdate).State = EntityState.Modified;
        }

/// <summary>
        /// generic method to get many record on the basis of a condition.
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public virtual IEnumerable GetMany(Func<TEntity, bool> where)
        {
return DbSet.Where(where).ToList();
        }

/// <summary>
        /// generic method to get many record on the basis of a condition but query able.
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public virtual IQueryable GetManyQueryable(Func<TEntity, bool> where)
        {
return DbSet.Where(where).AsQueryable();
        }

/// <summary>
        /// generic get method , fetches data for the entities on the basis of condition.
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public TEntity Get(Func<TEntity, Boolean> where)
        {
return DbSet.Where(where).FirstOrDefault();
        }

/// <summary>
        /// generic delete method , deletes data for the entities on the basis of condition.
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public void Delete(Func<TEntity, Boolean> where)
        {
            IQueryable objects = DbSet.Where(where).AsQueryable();
foreach (TEntity obj in objects)
                DbSet.Remove(obj);
        }

/// <summary>
        /// generic method to fetch all the records from db
        /// </summary>
        /// <returns></returns>
        public virtual IEnumerable GetAll()
        {
return DbSet.ToList();
        }

/// <summary>
        /// Inclue multiple
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="include"></param>
        /// <returns></returns>
        public IQueryable GetWithInclude(
            System.Linq.Expressions.Expression<Func<TEntity, 
bool>> predicate, params string[] include)
        {
            IQueryable query = this.DbSet;
            query = include.Aggregate(query, (current, inc) => current.Include(inc));
return query.Where(predicate);
        }

/// <summary>
        /// Generic method to check if entity exists
        /// </summary>
        /// <param name="primaryKey"></param>
        /// <returns></returns>
        public bool Exists(object primaryKey)
        {
return DbSet.Find(primaryKey) != null;
        }

/// <summary>
        /// Gets a single record by the specified criteria (usually the unique identifier)
        /// </summary>
        /// <param name="predicate">Criteria to match on</param>
        /// <returns>A single record that matches the specified criteria</returns>
        public TEntity GetSingle(Func<TEntity, bool> predicate)
        {
return DbSet.Single(predicate);
        }

/// <summary>
        /// The first record matching the specified criteria
        /// </summary>
        /// <param name="predicate">Criteria to match on</param>
        /// <returns>A single record containing the first record matching the specified criteria</returns>
        public TEntity GetFirst(Func<TEntity, bool> predicate)
        {
return DbSet.First(predicate);
        }


#endregion
    }
}

Unit of Work

Again I’ll not explain in detail what Unit of Work is. You can google about the theory or follow my existing article on MVC with Unit of Work.
To give a heads up, again from my existing article, the important responsibilities of Unit of Work are,
  • To manage transactions.
  • To order the database inserts, deletes, and updates.
  • To prevent duplicate updates. Inside a single usage of a Unit of Work object, different parts of the code may mark the same Invoice object as changed, but the Unit of Work class will only issue a single UPDATE command to the database.
The value of using a Unit of Work pattern is to free the rest of our code from these concerns so that you can otherwise concentrate on business logic.
Step 1: Create a folder named UnitOfWork, add a class to that folder named UnitOfWork.cs,
Add GenericRepository properties for all the three entities that we got. The class also implementsIDisposableinterface and it’s method Dispose to free up connections and objects. The class will be as follows,
#region Using Namespaces...

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Data.Entity.Validation;
using DataModel.GenericRepository;

#endregion

namespace DataModel.UnitOfWork
{
/// <summary>
    /// Unit of Work class responsible for DB transactions
    /// </summary>
    public class UnitOfWork : IDisposable
    {
#region Private member variables...

private WebApiDbEntities _context = null;
private GenericRepository _userRepository;
private GenericRepository _productRepository;
private GenericRepository _tokenRepository;
#endregion

public UnitOfWork()
        {
            _context = new WebApiDbEntities();
        }

#region Public Repository Creation properties...

/// <summary>
        /// Get/Set Property for product repository.
        /// </summary>
        public GenericRepository ProductRepository
        {
get
            {
if (this._productRepository == null)
this._productRepository = new GenericRepository(_context);
return _productRepository;
            }
        }

/// <summary>
        /// Get/Set Property for user repository.
        /// </summary>
        public GenericRepository UserRepository
        {
get
            {
if (this._userRepository == null)
this._userRepository = new GenericRepository(_context);
return _userRepository;
            }
        }

/// <summary>
        /// Get/Set Property for token repository.
        /// </summary>
        public GenericRepository TokenRepository
        {
get
            {
if (this._tokenRepository == null)
this._tokenRepository = new GenericRepository(_context);
return _tokenRepository;
            }
        }
#endregion

#region Public member methods...
/// <summary>
        /// Save method.
        /// </summary>
        public void Save()
        {
try
            {
                _context.SaveChanges();
            }
catch (DbEntityValidationException e)
            {

var outputLines = new List<string>();
foreach (var eve in e.EntityValidationErrors)
                {
                    outputLines.Add(string.Format(
"{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:", DateTime.Now, 
                        eve.Entry.Entity.GetType().Name, eve.Entry.State));
foreach (var ve in eve.ValidationErrors)
                    {
                        outputLines.Add(string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage));
                    }
                }
                System.IO.File.AppendAllLines(@"C:\errors.txt", outputLines);

throw e;
            }

        }

#endregion

#region Implementing IDiosposable...

#region private dispose variable declaration...
private bool disposed = false; 
#endregion

/// <summary>
        /// Protected Virtual Dispose method
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
if (!this.disposed)
            {
if (disposing)
                {
                    Debug.WriteLine("UnitOfWork is being disposed");
                    _context.Dispose();
                }
            }
this.disposed = true;
        }

/// <summary>
        /// Dispose method
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        } 
#endregion
    }
}
Now we have completely set up our data access layer, and our project structure looks like as shown below,

Setup Business Entities

Remember, we created a business entities project. You may wonder, we already have database entities to interact with database then why do we need Business Entities? The answer is as simple as that, we are trying to follow a proper structure of communication, and one would never want to expose the database entities to the end client, in our case is Web API, it involves lot of risk. Hackers may manipulate the details and get accessto your database.Instead we’ll use database entities in our business logic layer and use Business Entities as transfer objects to communicate between business logic and Web API project. So business entities may have different names but, their properties remains same as database entities. In our case we’ll add same name business entity classes appendint word “Entity” to them in our BusinessEntity project. So we’ll end up having three classes as follows,

Product entity

public class ProductEntity
    {
public int ProductId { get; set; }
public string ProductName { get; set; }
    }

Token entity

public class TokenEntity
    {
public int TokenId { get; set; }
public int UserId { get; set; }
public string AuthToken { get; set; }
public System.DateTime IssuedOn { get; set; }
public System.DateTime ExpiresOn { get; set; }
    }

User entity

public class UserEntity
    {
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Name { get; set; }
    }

Setup Business Services Project

Add a new class library to the solution named BusinessServices. This layer will act as our business logic layer. Note that, we can make use of our API controllers to write business logic, but I am trying to segregate my business logic in an extra layer so that if in future I want to use WCF, MVC, ASP.NET Web Pages or any other application as my presentation layer then I can easily integrate my Business logic layer in it.
We’ll make this layer testable, so we need to create an interface in and declare CURD operations that we need to perform over product table.Before we proceed, add the reference of BusinessEntities project and DataModel project to this newly created project
Step 1 : Create an interface named IProductServices and add following code to it for CURD operations methods,
using System.Collections.Generic;
using BusinessEntities;

namespace BusinessServices
{
/// <summary>
    /// Product Service Contract
    /// </summary>
    public interface IProductServices
    {
        ProductEntity GetProductById(int productId);
        IEnumerable GetAllProducts();
int CreateProduct(ProductEntity productEntity);
bool UpdateProduct(int productId,ProductEntity productEntity);
bool DeleteProduct(int productId);
    }
}
Step 2 : Create a class to implement this interface.name that class ProductServices,
The class contains a private variable of UnitOfWork and a constructor to initialize that variable,
private readonly UnitOfWork _unitOfWork;

/// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices()
        {
            _unitOfWork = new UnitOfWork();
        }
We have decided not to expose our db entities to Web API project, so we need something to map the db entities data to my business entity classes. We’ll make use of AutoMapper.You can read about AutoMapper in my this article.
Step 3: Just right click project-> Extension manager, search for AutoMapper in online galary and add to BusinessServices project,
Step 4: Implement methods in ProductServices class,
Add following code to the class,
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using AutoMapper;
using BusinessEntities;
using DataModel;
using DataModel.UnitOfWork;

namespace BusinessServices
{
/// <summary>
    /// Offers services for product specific CRUD operations
    /// </summary>
    public class ProductServices:IProductServices
    {
private readonly UnitOfWork _unitOfWork;

/// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices()
        {
            _unitOfWork = new UnitOfWork();
        }

/// <summary>
        /// Fetches product details by id
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public BusinessEntities.ProductEntity GetProductById(int productId)
        {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
            {
                Mapper.CreateMap();
var productModel = Mapper.Map(product);
return productModel;
            }
return null;
        }

/// <summary>
        /// Fetches all the products.
        /// </summary>
        /// <returns></returns>
        public IEnumerable GetAllProducts()
        {
var products = _unitOfWork.ProductRepository.GetAll().ToList();
if (products.Any())
            {
                Mapper.CreateMap();
var productsModel = Mapper.Map<List, List>(products);
return productsModel;
            }
return null;
        }

/// <summary>
        /// Creates a product
        /// </summary>
        /// <param name="productEntity"></param>
        /// <returns></returns>
        public int CreateProduct(BusinessEntities.ProductEntity productEntity)
        {
using (var scope = new TransactionScope())
            {
var product = new Product
                {
                    ProductName = productEntity.ProductName
                };
                _unitOfWork.ProductRepository.Insert(product);
                _unitOfWork.Save();
                scope.Complete();
return product.ProductId;
            }
        }

/// <summary>
        /// Updates a product
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="productEntity"></param>
        /// <returns></returns>
        public bool UpdateProduct(int productId, BusinessEntities.ProductEntity productEntity)
        {
var success = false;
if (productEntity != null)
            {
using (var scope = new TransactionScope())
                {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
                    {
                        product.ProductName = productEntity.ProductName;
                        _unitOfWork.ProductRepository.Update(product);
                        _unitOfWork.Save();
                        scope.Complete();
                        success = true;
                    }
                }
            }
return success;
        }

/// <summary>
        /// Deletes a particular product
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public bool DeleteProduct(int productId)
        {
var success = false;
if (productId > 0)
            {
using (var scope = new TransactionScope())
                {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
                    {

                        _unitOfWork.ProductRepository.Delete(product);
                        _unitOfWork.Save();
                        scope.Complete();
                        success = true;
                    }
                }
            }
return success;
        }
    }
}
Let me explain the idea of the code. We have 5 methods as follows,
  1. To get product by id ( GetproductById ) : We call repository to get the product by id. Id comes as a parameter from the calling method to that service method. It returns the product entity from the database. Note that it will not return the exact db entity, instead we’ll map it with our business entity usingAutoMapper and return it to calling method.
    /// <summary>
            /// Fetches product details by id
            /// </summary>
            /// <param name="productId"></param>
            /// <returns></returns>
            public BusinessEntities.ProductEntity GetProductById(int productId)
            {
    var product = _unitOfWork.ProductRepository.GetByID(productId);
    if (product != null)
                {
                    Mapper.CreateMap();
    var productModel = Mapper.Map(product);
    return productModel;
                }
    return null;
            }
  2. Get all products from database (GetAllProducts) : This method returns all the products residing in database, again we make use of AutoMapper to map the list and return back.
    /// <summary>
            /// Fetches all the products.
            /// </summary>
            /// <returns></returns>
            public IEnumerable GetAllProducts()
            {
    var products = _unitOfWork.ProductRepository.GetAll().ToList();
    if (products.Any())
                {
                    Mapper.CreateMap();
    var productsModel = Mapper.Map<List, List>(products);
    return productsModel;
                }
    return null;
            }
  3. Create a new product (CreateProduct) : This method takes productBusinessEntity as an argument and creates a new object of actual database entity and insert it using unit of work.
    /// <summary>
            /// Creates a product
            /// </summary>
            /// <param name="productEntity"></param>
            /// <returns></returns>
            public int CreateProduct(BusinessEntities.ProductEntity productEntity)
            {
    using (var scope = new TransactionScope())
                {
    var product = new Product
                    {
                        ProductName = productEntity.ProductName
                    };
                    _unitOfWork.ProductRepository.Insert(product);
                    _unitOfWork.Save();
                    scope.Complete();
    return product.ProductId;
                }
            }
I guess you can now write update and delete methods. So I am writing the code of complete class,
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using AutoMapper;
using BusinessEntities;
using DataModel;
using DataModel.UnitOfWork;

namespace BusinessServices
{
/// <summary>
    /// Offers services for product specific CRUD operations
    /// </summary>
    public class ProductServices:IProductServices
    {
private readonly UnitOfWork _unitOfWork;

/// <summary>
        /// Public constructor.
        /// </summary>
        public ProductServices()
        {
            _unitOfWork = new UnitOfWork();
        }

/// <summary>
        /// Fetches product details by id
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public BusinessEntities.ProductEntity GetProductById(int productId)
        {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
            {
                Mapper.CreateMap();
var productModel = Mapper.Map(product);
return productModel;
            }
return null;
        }

/// <summary>
        /// Fetches all the products.
        /// </summary>
        /// <returns></returns>
        public IEnumerable GetAllProducts()
        {
var products = _unitOfWork.ProductRepository.GetAll().ToList();
if (products.Any())
            {
                Mapper.CreateMap();
var productsModel = Mapper.Map<List, List>(products);
return productsModel;
            }
return null;
        }

/// <summary>
        /// Creates a product
        /// </summary>
        /// <param name="productEntity"></param>
        /// <returns></returns>
        public int CreateProduct(BusinessEntities.ProductEntity productEntity)
        {
using (var scope = new TransactionScope())
            {
var product = new Product
                {
                    ProductName = productEntity.ProductName
                };
                _unitOfWork.ProductRepository.Insert(product);
                _unitOfWork.Save();
                scope.Complete();
return product.ProductId;
            }
        }

/// <summary>
        /// Updates a product
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="productEntity"></param>
        /// <returns></returns>
        public bool UpdateProduct(int productId, BusinessEntities.ProductEntity productEntity)
        {
var success = false;
if (productEntity != null)
            {
using (var scope = new TransactionScope())
                {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
                    {
                        product.ProductName = productEntity.ProductName;
                        _unitOfWork.ProductRepository.Update(product);
                        _unitOfWork.Save();
                        scope.Complete();
                        success = true;
                    }
                }
            }
return success;
        }

/// <summary>
        /// Deletes a particular product
        /// </summary>
        /// <param name="productId"></param>
        /// <returns></returns>
        public bool DeleteProduct(int productId)
        {
var success = false;
if (productId > 0)
            {
using (var scope = new TransactionScope())
                {
var product = _unitOfWork.ProductRepository.GetByID(productId);
if (product != null)
                    {

                        _unitOfWork.ProductRepository.Delete(product);
                        _unitOfWork.Save();
                        scope.Complete();
                        success = true;
                    }
                }
            }
return success;
        }
    }
}
Job done at business service level. Let’s move on to API controller to call these methods.

Setup WebAPI project

Step1 : Just add the reference of BusinessEntity and BusinessService in the WebAPI project, our architecture becomes like this,
Step 2: Add a new WebAPI controller in Controller folder. Right click Controller folder and add a new controller.
We get a controller as follows,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WebApi.Controllers
{
public class ProductController : ApiController
    {
// GET api/product
        public IEnumerable<string> Get()
        {
return new string[] { "value1", "value2" };
        }

// GET api/product/5
        public string Get(int id)
        {
return "value";
        }

// POST api/product
        public void Post([FromBody]string value)
        {
        }

// PUT api/product/5
        public void Put(int id, [FromBody]string value)
        {
        }

// DELETE api/product/5
        public void Delete(int id)
        {
        }
    }
}
We get HTTP VERBS as method names. Web API is smart enough to recognize request with the name of the VERB itself. In our case we are doing CRUD operations, so we don’t need to change the names of the method, we just needed this. We only have to write calling logic inside these methods. In my upcoming articles of the series, we will figure out how we can define new routes and provide method names of our choice with those routes.
Step 3: Add logic to call Business Service methods, just make an object of Business Service and call its respective methods, our Controller class becomes like,
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BusinessEntities;
using BusinessServices;

namespace WebApi.Controllers
{
public class ProductController : ApiController
    {

private readonly IProductServices _productServices;

#region Public Constructor

/// <summary>
        /// Public constructor to initialize product service instance
        /// </summary>
        public ProductController()
        {
            _productServices =new ProductServices();
        }

#endregion

// GET api/product
        public HttpResponseMessage Get()
        {
var products = _productServices.GetAllProducts();
if (products != null)
            {
var productEntities = products as List ?? products.ToList();
if (productEntities.Any())
return Request.CreateResponse(HttpStatusCode.OK, productEntities);
            }
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Products not found");
        }

// GET api/product/5
        public HttpResponseMessage Get(int id)
        {
var product = _productServices.GetProductById(id);
if (product != null)
return Request.CreateResponse(HttpStatusCode.OK, product);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No product found for this id");
        }

// POST api/product
        public int Post([FromBody] ProductEntity productEntity)
        {
return _productServices.CreateProduct(productEntity);
        }

// PUT api/product/5
        public bool Put(int id, [FromBody]ProductEntity productEntity)
        {
if (id  > 0)
            {
return _productServices.UpdateProduct(id, productEntity);
            }
return false;
        }

// DELETE api/product/5
        public bool Delete(int id)
        {
if (id > 0)
return _productServices.DeleteProduct(id);
return false;
        }
    }
}
Just run the application, we get,
But now how do we test our API? We don’t have client. Guys, we’ll not be writing a client now to test it.We’ll add a package that will do all our work.
Just go to Manage Nuget Packages, by right clicking WebAPI project and type WebAPITestClient in searchbox in online packages,
You’ll get “A simple Test Client for ASP.NET Web API”, just add it. You’ll get a help controller in Areas-> HelpPage like shown below,

Running the Application

Before running the application, I have put some test data in our product table.
Just hit F5, you get the same page as you got earlier, just append “/help” in its url, and you’ll get the test client,
You can test each service by clicking on it.
Service for GetAllProduct,
For Create a new product,
In database, we get new product,
Update product:
We get in database,
Delete product:
In database:
Job done.

Design Flaws

  1. Architecture is tightly coupled. IOC (Inversion of Control) needs to be there.
  2. We cannot define our own routes.
  3. No exception handling and logging.
  4. No unit tetsts.

Conclusion

We now know how to create a WebAPI and perform CRUD operations using n layered architecture.
But still there are some flaws in this design.In my next two articles I’ll explain how to make the system loosely coupled using Dependency Injection Principle. We’ll also cover all the design flaws to make our design better and stronger. Till then Happy Coding J You can also download the source code from GitHub.
Advertisements

Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)


Introduction

My article of the series “Diving in OOP” will explain enum datatype in C#. We’ll learn by doing hands on lab and not only by theory. We’ll explore the power of enum and will cover almost every scenario in which we can use enum. We’ll follow a practical approach of learning to understand this concept. We may come across complex examples to understand the concept more deeply.

Enums (The Definition)

Let’s start with the definition taken from MSDN:

“The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.
Usually it is best to define an enum directly within a namespace so that all classes in the namespace can access it with equal convenience. However, an enum can also be nested within a class or struct.
By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. For example, in the following enumeration, Sat is 0, Sun is 1, Mon is 2, and so forth.”

Pre-requisites

I expect that my readers of this article should have very basic knowledge of C# and I always wish that my readers should enjoy while reading this article. Also, keep writing programs by yourself that are given as examples in this article, to get hands on and understand the concept more deeply.

Roadmap

Let’s recall our road map.

A Practical Approach

Enum plays almost the same responsibility as the class does, i.e., creating a new data type, and it exists at the same level as class, interfaces or structs.
Just open your Visual Studio and add a console application named Enums. You’ll get Program.cs class.
Note: Each and every code snippet in this article is tried and tested.
Declare an enum at the same level as of Program class, call it as Color.

Program.cs

namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
        }
    }

enum Color
{
Yellow,
Blue,
Brown,
Green
}
}

In the above mentioned example, we created a new datatype with the help of enum. The datatype is Colorhaving four distinct values, Yellow,BlueBrown and Green. The text that we write inside the declared enum could be anything of your wish; it just provides a custom enumerated list to you.
Modify your main program as shown below:
using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
            Console.WriteLine(Color.Yellow);
            Console.ReadLine();
        }
    }

enum Color
{
Yellow,
Blue,
Brown,
Green
}
}

Run the program.
 
OutputYellow
 
Now just typecast Color.Yellow to int, what do we get?
using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
            Console.WriteLine((int)Color.Yellow);
            Console.ReadLine();
        }
    }

enum Color
{
Yellow,
Blue,
Brown,
Green
}
}

 
Output0
 
We see that enum is called as static variables, so an enum can be considered here as static objects. Thereforeother enums in the above example can be declared in the same way as Yellow, like Blue can be declared asColor.Blue. The output in the above two examples we see is when we typecast and Yellow without typecasting, hence we see here that its behaviour is very similar to an array where Yellow has a value 0, similarly Blue has a value 1Brown2Green3.
Therefore, when we do Color.Yellow, it’s like displaying a number 0, so from this can we infer that an enumrepresents a constant number, therefore an enum type is a distinct type having named constants.
Point to remember: An enum represents for a constant number, and an enum type is known as a distinct type having named constants.

Underlying Data type

Program.cs

using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
            Console.WriteLine((byte)Color.Yellow);
            Console.WriteLine((byte)Color.Blue);
            Console.ReadLine();
        }
    }

enum Color:byte
{
Yellow,
Blue,
Brown,
Green
}
}

Output

0
1
 
Note: Each and every code snippet in this article is tried and tested.
The only change we did here is that we specified the type to the underlying enum that we declared. The defaultdatatype for the enum is int, here we have specified the data type as byte and we get the result.
There are more data types that can be specified
for enum like longulongshortushortintuint,byte andsbyte.
Point to remember: We can’t declare char as an underlying data type for enum objects because char stores Unicode characters, but enum objects data type can only be number.

Inheritance in Enum

Program.cs

using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
            Console.WriteLine((byte)Color.Yellow);
            Console.WriteLine((byte)Color.Blue);
            Console.ReadLine();
        }
    }

enum Color:byte
{
Yellow,
Blue,
Brown,
Green

}

enum Shades:Color
{

}
}

Output

Compile time error: Type bytesbyteshortushortintuintlong, or ulong expected.
We clearly see here enums can’t be derived from any other type except that of mentioned in the error.
Point to rememberenum can’t be derived from any other type except that of type bytesbyteshortushort,intuintlong, or ulong.
Let’s derive a class from enum, call it class Derived, so our code.

Program.cs

class Program
    {
static void Main(string[] args)
        {
            Console.WriteLine((byte)Color.Yellow);
            Console.WriteLine((byte)Color.Blue);
            Console.ReadLine();
        }
    }

Enum

enum Color:byte
    {
        Yellow,
        Blue,
        Brown,
        Green
    }

Derived.cs

class Derived:Color
    {

}

Compile the code.

Output

Compile time error: ‘Enums.Derived’: cannot derive from sealed type ‘Enums.Color’
Point to remember: By default, enum is a sealed class and therefore sticks to all the rules that a sealed class follows, so no class can derive from enum, i.e., a sealed type.
Can System.Enum be a base class toenum?

Program.cs

using System;

namespace Enums
{
internal enum Color: System.Enum
{
Yellow,
Blue
}

internal class Program
{
private static void Main(string[] args)
{
}
}
}

Output

Compile time error: Type bytesbyteshortushortintuintlong, or ulong expected.
Point to remember: The enum type is implicitly derived from System.Enum and so we cannot explicitly derive it from System.Enum.
To add more,enum is also derived from three interfaces IComparableIFormattable and IConvertible.

A. IComparable

Let’s check,

Program.cs

using System;

namespace Enums
{
internal enum Color
{
Yellow,
Blue,
Green
}

internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(Color.Yellow.CompareTo(Color.Blue));
Console.WriteLine(Color.Blue.CompareTo(Color.Green));
Console.WriteLine(Color.Blue.CompareTo(Color.Yellow));
Console.WriteLine(Color.Green.CompareTo(Color.Green));
Console.ReadLine();
}
}
}

Output

-1
-1
 1
 0
Sometimes, we may get into situations where we have large number of enums defined and we want to compare the values of enum to each other to check if they are smaller, larger or equal value to one another.
Since all enums implicitly derive from Enum class that implements the interface IComparable, they all have a methodCompareTo(), that we just used in the above example. The method being nonstatic has to be used through a member. Yellow has value 0, Blue as 1 and Green as 2. In the first statement, when Color.Yellow compared toColor.Blue, value of Yellow is smaller than Blue hence -1 returned, same applied for the second statement when Color.Blue compared to Color.GreenGreen has larger value, i.e., 2 than that of Color.Blue having value 1 only. In the third statement, i.e., vice versa of first statement, we get the result of camparisonas 1,becauseBlue is larger than Yellow. In the last statement where Color.Green compares to itself, we undoubtedly get the value 0.
So value -1 means the value is smaller, 1 means value is larger and 0 means equal values for both the enummembers.
Another comparison example is shown below:

Program.cs

using System;

namespace Enums
{
enum Color
{
Yellow,
Blue,
Green
}

internal class Program
{
private static void Main(string[] args)
{
int myColor = 2;
if(myColor== Color.Green)
{
Console.WriteLine(my color”);
}
Console.ReadLine();
}
}
}

Output

Compile time error : Operator '==' cannot be applied to operands of type 'int' and 'Enums.Color'
In the above example, we tried to compare an int type to Enum type and resulted in a compile time error. Sinceenum acts as an individual data type so it cannot be directly compared to an int, however, we can typecast the enumtype to int to perform comparison, like in the below example:

Program.cs

using System;

namespace Enums
{
enum Color
{
Yellow,
Blue,
Green
}

internal class Program
{
private static void Main(string[] args)
{
int myColor = 2;
if(myColor== (int)Color.Green)
{
Console.WriteLine(my color”);
}
Console.ReadLine();
}
}
}

 
Output: my color

B. IFormattable

Program.cs

using System;

namespace Enums
{
internal enum Color
{
Yellow,
Blue,
Green
}

internal class Program
{
private static void Main(string[] args)
{
System.Console.WriteLine(Color.Format(typeof(Color), Color.Green, X”));
System.Console.WriteLine(Color.Format(typeof(Color), Color.Green, d”));
Console.ReadLine();
}
}
}

Output

00000002
2
Format is the method derived from IFormatter interface. It’s a static method so can be used directly with theenum class defined as Color. It’sfirst parameter is the type of the enum class, second is the member that has to be formatted and third is the format, i.e., hexadecimal or decimal, like we used in the above example, and we got a positive result output too.

C. IConvertible

using System;

namespace Enums
{
enum Color
{
Yellow,
Blue,
Green
}

internal class Program
{
private static void Main(string[] args)
{
string[] names;
names = Color.GetNames(typeof (Color));
foreach (var name in names)
{
Console.WriteLine(name);
}
Console.ReadLine();
}
}
}

Output

Yellow
Blue
Green
 
Note: Each and every code snippet in this article is tried and tested.
GetNames is a static method that accepts Type, i.e., instance of type as a parameter and in return gives an array of strings. Like in the above example, we had array of 3 members in our enum, therefore their names are displayed one by one.
Another example is as follows:

Program.cs

using System;

namespace Enums
{
enum Color
{
Yellow,
Blue,
Green
}

internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(Color.Blue.ToString());
Console.WriteLine(Color.Green.ToString());
Console.ReadLine();
}
}
}

Output

Blue
Green
As we see in the above example, we converted an enum type to staring type and got an output too, so, numerous predefined conversion methods can be used to convert enum from one data type to another.
 
Point to remember: Numerous predefined conversion methods can be used to convert enum from one data type to another.
Duplicity, default values and initialization:

Program.cs

using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
            Console.WriteLine((byte)Color.Yellow);
            Console.WriteLine((byte)Color.Blue);
            Console.ReadLine();
        }
    }

enum Color
{
Yellow,
Blue,
Brown,
Green,
Blue
}
}

Output

Compile time error: The type 'Enums.Color' already contains a definition for 'Blue'
In the above example, we just repeated the enum member Blue of Color, and we got a compile time error, hence we now know that an enum cannot contain two members having the same name. By default, if the first value is not specified, the first member takes the value and increments it by one to succeeding members.
Let’s take one more example.

Program.cs

using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
            Console.WriteLine((int)Color.Yellow);
            Console.WriteLine((int)Color.Blue);
            Console.WriteLine((int)Color.Brown);
            Console.WriteLine((int)Color.Green);

Console.ReadLine();
}
}

enum Color
{
Yellow =2,
Blue,
Brown=9,
Green,

}
}

Output

2
3
9
10
Surprised! We can always specify the default constant value to any enum member, here we see, we specified value 2to yellow, so as per law of enum, the value of blue will be incremented by one and gets the value 3. We again specified as a default value toBrown, and so its successor Green gets incremented by one and gets that value 10.
Moving on to another example.

Program.cs

using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {

}
}

enum Color:byte
{
Yellow =300 ,
Blue,
Brown=9,
Green,
}
}

Output

Compile time error: Constant value '300' cannot be converted to a 'byte'
We just derived ourenum from byte, we know we can do that? We then changed the value of yellow from 2 to300, and we resulted in a compile time error. Since here our underlying data type was byte, so it is as simple as that, that we cannot specify the value to enum members which exceeds the range of underlying data types. The value 300is beyond the range of byte. It is similar to assigning the beyond range value to a byte data type variable.
Another example:

Program.cs

using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
            Console.WriteLine((int)Color.Yellow);
            Console.WriteLine((int)Color.Blue);
            Console.WriteLine((int)Color.Brown);
            Console.WriteLine((int)Color.Green);

Console.ReadLine();
}
}

enum Color
{
Yellow = 2,
Blue,
Brown = 9,
Green = Yellow
}
}

Output

2
3
9
2
Here we initialized Green to Yellow, and we did not get any error, so we see, more than one enum members can be initialized a same constant value.
Point to remember: More than one enum members can be initialized a same constant value.

Program.cs

using System;
namespace Enums
{
class Program
    {
static void Main(string[] args)
        {
            Color.Yellow = 3;
        }
    }

enum Color
{
Yellow = 2,
Blue,
Brown = 9,
Green = Yellow
}
}

Output

Compile time error: The left-hand side of an assignment must be a variable, property or indexer
In the above example, we tried to initialize the enum member out of the scope of defined enum, i.e., in another class, and got a compile time error. We must not forget that an enum acts as a constant, which cannot change its value.
Point to remember: An enum acts as a constant, so its value cannot be changed once initialized.

Readability

Program.cs

using System;

namespace Enums
{
internal enum Color
{
Yellow,
Blue,
Brown,
Green
}

internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine(CheckColor(Color.Yellow));
Console.WriteLine(CheckColor(Color.Brown));
Console.WriteLine(CheckColor(Color.Green));
Console.ReadLine();
}

public static string CheckColor(Color color)
{
switch (color)
{
case Color.Yellow:
return Yellow”;
case Color.Blue:
return Blue”;
case Color.Brown:
return Brown”;
case Color.Green:
return Green”;
default:
return no color”;
}
}
}
}

Output

Yellow
Brown
Green
Here, in the above example, we have declared an enum Color containing various color members.There is a class named program that contains a static method named CheckColor, that has a switch statement checkingcolor on the basis of passed parameter to the method, i.e., Enum Color. In Main method, we try to access thatCheckColor method, passing various parameters. We see that the switch statement in CheckColor method can take any of the datatype passed and in return case statements use name of that type and not the plain intnumber to compare the result. We see that this made our program more readable. So enum plays an important role in making the program more readable and structured, easy to grasp.

Circular Dependency

Program.cs

using System;

namespace Enums
{
internal enum Color
{
Yellow=Blue,
Blue
}

internal class Program
{
private static void Main(string[] args)
{
}
}
}

Output

Compile time error: The evaluation of the constant value for 'Enums.Color.Yellow' involves a circular definition
Like constants, we also cannot have circular dependency in enums. We assigned valueBlue to Yellow, and Blue in turn is incremented by one as a next enum member, this results in a circular dependency of Blue to yellow, and resulted in error, C# is smart enough to catch these kind of tricks.

Diving Deep

Let’s take some complex scenarios:

Lab1

Program.cs

using System;

namespace Enums
{
enum Color
{

}

internal class Program
{
private static void Main(string[] args)
{
Color color = (Color) -1;
Console.ReadLine();
}
}
}

 
Note: Each and every code snippet in this article is tried and tested.

Output

Compile time error: 
To cast a negative value, you must enclose the value in parentheses
'Enums.Color' is a 'type' but is used like a 'variable'
In the above example, we are casting a negative value to enum, but the compiler says that while casting a negative value, we must keep that in parenthesis. It’s not strange, as C# knows that “-” is also a unary operator, that while using above code may create a confusion for compiler that we are using subtraction or typecasting a negative value. So always use parenthesis while typecasting negative values.

Lab2

Program.cs

using System;

namespace Enums
{
enum Color
{
value__
}

internal class Program
{
private static void Main(string[] args)
{

}
}
}

Output

Compile time error: The enumerator name 'value__' is reserved and cannot be used
We clearly see here that we have value__ as reserved member for the enumerator. C# compiler like this keyword has large number of reserved inbuilt keywords.
Image credit: www.vector.rs
It may keep this reserved keyword to keep track of the enum members internally but not sure.

Summary

Let’s recall all the points that we have to remember.
  1. An enum represents for a constant number, and an enum type is known as a distinct type having named constants.
  2. We can’t declare char as an underlying data type for enum objects because char stores Unicode characters, but enum objects data type can only be number.
  3. An enum can’t be derived from any other type except that of type bytesbyteshortushortintuint,long, or ulong.
  4. By default, enum is a sealed class and therefore sticks to all the rules that a sealed class follows, so no class can derive from enum, i.e., a sealed type.
  5. The enum type is implicitly derived from System.Enum and so we cannot explicitly derive it fromSystem.Enum.
  6. enum is also derived from three interfaces IComparableIFormattable and IConvertible.
  7. Numerous predefined conversion methods can be used to convert enum from one data type to another.
  8. More than one enum members can be initialized a same constant value.
  9. An enum acts as a constant, so its value cannot be changed once initialized.
  10. The enumerator name ‘value__‘ is reserved and cannot be used.

Conclusion

With this article, we completed almost all the scenarios related to enum. We did a lot of hands-on lab to clear our concepts. I hope my readers now know by heart about these basic concepts and will never forget them.
These may also help you in cracking C# interviews.
Keep coding and enjoy reading.
Also, do not forget to rate/comment/like my article if it helped you by any means, this helps me to get motivated and encourages me to write more and more.

Read more:

Other Series

My other series of articles:

For more informative articles visit my Blog.

For more technical articles you can reach out to CodeTeddy.

Read More

For more technical articles, you can reach out to A Practical Approach.

Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protected/Internal/Sealed/Constants/Static and Readonly Fields)


Introduction

Thanks to my readers for their tremendous support which has motivated me to continue this OOP series further.
We have already covered almost all the aspects of Inheritance and Polymorphism in C#. My article will highlight almost all the aspects/scenarios of access modifiers in C#. We’ll learn by doing hands on lab and not only by theory. We’ll cover my favourite topic Constants in a very different manner by categorizing the sections in the form of “Labs”. My effort in this article will be to cover each and every concept of the related topic, so that at the end of the article, we can confidently say that we know “All about access modifiers in C#”. Just dive into OOP.

Pre-requisites

I expect that readers of this article should have very basic knowledge of C#. The reader should only know the definition of access modifiers. Last but not the least, as always, I wish that my readers should enjoy reading this article.

Roadmap

Let’s recall our road map:

Access Modifiers

Let us take the definition from Wikipedia this time:

“Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation of components.”

Like the definition says, we can control the accessibility of our class methods and members through access modifiers, let us understand this in detail by taking every access modifier one by one.

Public, Private, Protected at Class Level

Whenever we create a class, we always want to have the scope to decide who can access certain members of the class. In other words, we would sometimes need to restrict access to the class members. The one thumb rule is that members of a class can freely access each other. A method in one class can always access another method of the same class without any restrictions. When we talk about the default behavior, the same class is allowed complete access but no else is provided access to the members of the class. The default access modifier is private for class members.
Point to remember: The default access modifier is private for class members.
Let’s do some hands on lab. Just open your Visual Studio and add a console application in C# namedAccessModifiers. You’ll get a Program.cs class file by default. In the same file, add a new class named Modifiersand add the following code to it:
using System;

namespace AccessModifiers
{
class Modifiers
{
static void AAA()
{
Console.WriteLine(Modifiers AAA”);
}

public static void BBB()
{
Console.WriteLine(Modifiers BBB”);
AAA();
}
}

class Program
{
static void Main(string[] args)
{
Modifiers.BBB();
}
}
}

So, your Program.cs file becomes like shown in the above code snippet. We added a class Modifiers and two staticmethods AAA and BBB. Method BBB is marked as public. We call the method BBB from Main method.The method is called directly by the class name because it is marked static.
When we run the application, we get the output as follows:

Output

Modifiers BBB
Modifiers AAA
 
BBB is marked public and so anyone is allowed to call and run it. Method AAA is not marked with any access modifier which automatically makes it private, that is the default. The private modifier has no effect on members of the same class and so method BBB is allowed to call method AAA. Now this concept is called member access.
Modify the Program class and try to access AAA as:
class Program
    {
static void Main(string[] args)
        {
            Modifiers.AAA();
            Console.ReadKey();
        }
    }

Output

'AccessModifiers.Modifiers.AAA()' is inaccessible due to its protection level
So , since methodAAA is private, therefore no one else can have access to it except Modifiers class.
Note: Each and every code snippet written in this article is tried and tested.
 
Modifiers
Now mark the AAA method as protected, our class looks like:
class Modifiers
    {
protected static void AAA()
        {
            Console.WriteLine("Modifiers AAA");
        }

public static void BBB()
{
Console.WriteLine(Modifiers BBB”);
AAA();
}
}

Program

class Program
    {
static void Main(string[] args)
        {
            Modifiers.AAA();
            Console.ReadKey();
        }
    }

Output

'AccessModifiers.Modifiers.AAA()' is inaccessible due to its protection level
Again the same output. We cannot access the method AAA even after we introduced a new modifier namedprotected. But BBB can access AAA method because it lies in the same class.

Modifiers in Inheritance

Let’s add one more class and make a relation of base and derived class to our existing class and add one more method to our base class. So our class structure will look something like this:

Modifiers Base Class

class ModifiersBase
    {
static void AAA()
        {
            Console.WriteLine("ModifiersBase AAA");
        }
public static void BBB()
        {
            Console.WriteLine("ModifiersBase BBB");
        }
protected static void CCC()
        {
            Console.WriteLine("ModifiersBase CCC");
        }
    }

Modifiers Derive Class

class ModifiersDerived:ModifiersBase
    {
public static void XXX()
        {
            AAA();
            BBB();
            CCC();
        }
    }

Program Class

class Program
    {
static void Main(string[] args)
        {
            ModifiersDerived.XXX();
            Console.ReadKey();
        }
    }

Output

'AccessModifiers.ModifiersBase.AAA()' is inaccessible due to its protection level
Now in this case, we are dealing with derived class. Whenever we mark a method with the specifier, protected, we are actually telling C# that only derived classes can access that method and no one else can. Therefore in method XXX, we can call CCC because it is marked protected, but it cannot be called from anywhere else including Main function. The method AAA is made private and can be called only from the class ModifiersBase. If we remove AAA from method XXX, the compiler will give no error.
Therefore, now we are aware of three important concepts. Private means only the same class has access to the members, public means everybody has access and protected lies in between where only derived classes have access to the base class method.
All the methods for example reside in a class. The accessibility of that method is decided by the class in which it resides as well as the modifiers on the method. If we are allowed an access to a member, then we say that the member is accessible, else it is inaccessible.

Internal Modifier at Class Level

Let’s take one another scenario. Create a class library with a name “AccessModifiersLibrary” in your Visual Studio. Add a class named ClassA in that class library and mark the class as internal, the code will be as shown below:
AccessModifiersLibrary.ClassA:

namespace AccessModifiersLibrary
{
internal class ClassA
{
}
}

Now compile the class, and leave it. Its DLL will be generated in ~\AccessModifiersLibrary\bin\Debug folder.
Now in your console application, “AccessModifiers” i.e. created earlier. Add the reference ofAccessModifiersLibrary library by adding its compiled DLL as a reference to AccessModifiers.
In Program.cs of AccessModifiers console application, modify the Program class like shown below:

AccessModifiers.Program

using AccessModifiersLibrary;

namespace AccessModifiers
{
class Program
{
static void Main(string[] args)
{
ClassA classA;
}
}
}

And compile the code.

Output

Compile time error: 'AccessModifiersLibrary.ClassA' is inaccessible due to its protection level
We encountered this error because the access specifier internal means that we can only access ClassA fromAccessModifiersLibrary.dll and not from any other file or code. Internal modifier means that access is limited to current program only. So try never to create a component and mark the class internal as no one would be able to use it.
And what if we remove the field internal from ClassA, will the code compile? i.e.,

AccessModifiersLibrary.ClassA

namespace AccessModifiersLibrary
{
class ClassA
    {
    }
}

AccessModifiers.Program

using AccessModifiersLibrary;

namespace AccessModifiers
{
class Program
{
static void Main(string[] args)
{
ClassA classA;
}
}
}

Output

Compile time error: 'AccessModifiersLibrary.ClassA' is inaccessible due to its protection level
We again got the same error. We should not forget that by default if no modifier is specified, the class is internal. So our class ClassA is internal by default even if we do not mark it with any access modifier, so the compiler results remain the same.
Had the class ClassA been marked public, everything would have gone smooth without any error.
Point to remember: A class marked as internal can only be have its access limited to the current assembly only.

Namespaces with Modifiers

Let’s for fun, mark a namespace of AccessModifiers class library as public in Program class:

Program

public namespace AccessModifiers
{
class Program
    {
static void Main(string[] args)
        {

}
}
}

Compile the application.

Output

Compile time error: A namespace declaration cannot have modifiers or attributes
 
Point to remember: Namespaces as we see by default can have no accessibility specifiers at all. They are by defaultpublic and we cannot add any other access modifier including public again too.

Private Class

Let’s do one more experiment and mark the class Program as private, so our code becomes:
namespace AccessModifiers
{
private class Program
    {
static void Main(string[] args)
        {

}
}
}

Compile the code.

Output

Compile time error: Elements defined in a namespace cannot be explicitly declared as private, protected, or protected internal
Point to remember: A class can only be public or internal. It cannot be marked as protected or private. The default is internal for the class.
Access modifiers for the members of the class:
Now here is a big statement, that the members of a class can have all the above explained access modifiers, but default modifier is private.
Point to remember: Members of a class can be marked with all the access modifiers, and the default access modifier isprivate.
What if we want to mark a method with two access modifiers?
namespace AccessModifiers
{
public class Program
    {
static void Main(string[] args)
        {
        }

public private void Method1()
{

}
}
}

Compile the code.

Output

Compile time error: More than one protection modifier
Therefore, we can’t mark a member with more than one access modifier often. But there are such scenarios too, we’ll cover them in next sections. Already defined types like int and object have no accessibility restrictions. They can be used anywhere and everywhere.

Internal Class and Public Method

Create a class library with a class named ClassA marked internal and have a public method MethodClassA(), as:
namespace AccessModifiersLibrary
{
internal class ClassA
    {
public void MethodClassA(){}
    }
}
Add the reference of class library to our console application. Now in Program.cs of console application, try to access that method MethodClassA of ClassA.

Program

using AccessModifiersLibrary;

namespace AccessModifiers
{
public class Program
{
public static void Main(string[] args)
{
ClassA classA = new ClassA();
classA.MethodClassA();
}
}
}

Output

Compile time errors:
'AccessModifiersLibrary.ClassA' is inaccessible due to its protection level
The type 'AccessModifiersLibrary.ClassA' has no constructors defined
'AccessModifiersLibrary.ClassA' is inaccessible due to its protection level
'AccessModifiersLibrary.ClassA' does not contain a definition for 'MethodClassA' and
no extension method 'MethodClassA' accepting a first argument of type 'AccessModifiersLibrary.ClassA'
could be found (are you missing a using directive or an assembly reference?)
So many errors. The errors are self explanatory though. Even the method MethodClassA of ClassA is public, it could not be accessed in Program class due to protection level of ClassA, i.e. internal. The type enclosing the method MethodClassA is internal, so no matter if the method is marked public, we cannot access it in any other assembly.

Public Class and Private Method

Let’s make the class ClassA as public and method as private:
AccessModifiersLibrary.ClassA:

namespace AccessModifiersLibrary
{
public class ClassA
{
private void MethodClassA(){}
}
}

Program

using AccessModifiersLibrary;

namespace AccessModifiers
{
public class Program
{
public static void Main(string[] args)
{
ClassA classA = new ClassA();
classA.MethodClassA();
}
}
}

Output on compilation

'AccessModifiersLibrary.ClassA' does not contain a definition
for 'MethodClassA' and no extension method 'MethodClassA' accepting a first argument
of type 'AccessModifiersLibrary.ClassA' could be found (are you missing a using directive or an assembly reference?)
Now we marked our class Public, still can’t access the private method. So for accessing a member of the class, the access modifier of class as well as method is very important.
 
Note: Each and every code snippet written in this article is tried and tested.

Public Class and Internal Method

Make ClassA as public and MethodClassA as internal:
AccessModifiersLibrary.ClassA:

namespace AccessModifiersLibrary
{
public class ClassA
{
Internal void MethodClassA(){}
}
}

Program

using AccessModifiersLibrary;

namespace AccessModifiers
{
public class Program
{
public static void Main(string[] args)
{
ClassA classA = new ClassA();
classA.MethodClassA();
}
}
}

Output on compilation

'AccessModifiersLibrary.ClassA' does not contain a definition for 'MethodClassA' and no extension
method 'MethodClassA' accepting a first argument of type 'AccessModifiersLibrary.ClassA' could be
found (are you missing a using directive or an assembly reference?)
So an internal marked member means that no one from outside that DLL can access the member.

Protected Internal

In the class library, make three classes ClassAClassB and ClassC, and place the code somewhat like this:
namespace AccessModifiersLibrary
{
public class ClassA
    {
protected internal void MethodClassA()
        {

}
}

public class ClassB:ClassA
{
protected internal void MethodClassB()
{
MethodClassA();
}
}

public class ClassC
{
public void MethodClassC()
{
ClassA classA=new ClassA();
classA.MethodClassA();
}
}
}

And in Program class in our console application, call the MethodClassC of ClassC.

Program

using AccessModifiersLibrary;

namespace AccessModifiers
{
public class Program
{
public static void Main(string[] args)
{
ClassC classC=new ClassC();
classC.MethodClassC();
}
}
}

Compiler output

The code successfully compiles with no error.
 
Protected internal modifier indicates two things, that either the derived class or the class in the same file can have access to that method, therefore in the above mentioned scenario, the derived class ClassB and the class in the same file, i.e., ClassC can access that method of ClassA marked as protected internal.
 
Point to rememberProtected internal means that the derived class and the class within the same source code file can have access.

Protected Member

In our Program.cs in console application, place the following code:
namespace AccessModifiers
{
class AAA
    {
protected int a;
void MethodAAA(AAA aaa,BBB bbb)
        {
            aaa.a = 100;
            bbb.a = 200;
        }
    }
class BBB:AAA
     {
void MethodBBB(AAA aaa, BBB bbb)
         {
             aaa.a = 100;
             bbb.a = 200;
         }
     }
public class Program
    {
public static void Main(string[] args)
        {
        }
    }
}

Compiler Output

Cannot access protected member 'AccessModifiers.AAA.a' via a qualifier of type 'AccessModifiers.AAA';
the qualifier must be of type 'AccessModifiers.BBB' (or derived from it)
Class AAA is containing a protected member, i.e., a. But to the same class, no modifiers make sense. However as isprotected, in the derived class method MethodBBB, we cannot access it through AAA as aaa.a gives us an error. However bbb which looks like BBB does not give an error. To check this out, comment out the line aaa.a=100 inMethodBBB (). This means that we cannot access the protected members from an object of the base class, but from the objects of derived class only. This is in spite of the fact that is a member of AAA i.e. the base class. Even so, we still cannot access it. Also we cannot access from the method Main.

Accessibility Priority in Inheritance

Program

namespace AccessModifiers
{
class AAA
    {

}
public class BBB:AAA
{

}
public class Program
{
public static void Main(string[] args)
{
}
}
}

Compiler Output

Compile time error: Inconsistent accessibility: base class 'AccessModifiers.AAA' is less accessible than class 'AccessModifiers.BBB'
The error again gives us one more point to remember.
 
Point to remember: In between public and internalpublic always allows greater access to its members.
The class AAA is by default marked internal and BBB that derives from AAA is made public explicitly. We got an error as the derived class BBB has to have an access modifier which allows greater access than the base class access modifier. Here internal seems to be more restrictive than public.
But if we reverse the modifiers to both the classes i.e. ClassA marked as public and ClassB internal or default, we get rid of the error.
 
Point to remember: The base class always allows more accessibility than the derived class.
Another scenario:

Program

namespace AccessModifiers
{
class AAA
    {

}
public class BBB
{
public AAA MethodB()
{
AAA aaa= new AAA();
return aaa;
}
}
public class Program
{
public static void Main(string[] args)
{
}
}
}

Compiler output

Inconsistent accessibility: return type 'AccessModifiers.AAA' is less accessible than method 'AccessModifiers.BBB.MethodB()'
Here the accessibility of AAA is internal which is more restrictive than public. The accessibility of method MethodBis public which is more than that of the typeAAA. Now the error occurred because return values of a method must have greater accessibility than that of the method itself, which is not true in this case.
 
Point to remember: The return values of a method must have greater accessibility than that of the method itself.

Program

namespace AccessModifiers
{
class AAA
    {

}
public class BBB
{
public AAA aaa;
}
public class Program
{
public static void Main(string[] args)
{
}
}
}

Compiler Output

Inconsistent accessibility: field type 'AccessModifiers.AAA' is less accessible than field 'AccessModifiers.BBB.aaa'
Now rules are the same for everyone. The class AAA or data type aaa is internalaaa field is public which makes it more accessible than AAA which is internal. So we got the error.
Change the code to:
namespace AccessModifiers
{
class AAA
    {

}
public class BBB
{
AAA a;
}
public class Program
{
public static void Main(string[] args)
{
}
}
}

The output compilation results in no error.
We learnt a lot about these access modifiers like publicprivateprotectedinternalprotected internal. We also learnt about their priority of access and usage, let’s summarize their details in a tabular format for revision. Later, we’ll move to other types as well.
Tables taken from MSDN:
Declared accessibility Meaning
public Access is not restricted.
protected Access is limited to the containing class or types derived from the containing class.
internal Access is limited to the current assembly.
protected internal Access is limited to the current assembly or types derived from the containing class.
private Access is limited to the containing type.
“Only one access modifier is allowed for a member or type, except when you use the protected internalcombination.
Access modifiers are not allowed on namespaces. Namespaces have no access restrictions.
Depending on the context in which a member declaration occurs, only certain declared accessibilities are permitted. If no access modifier is specified in a member declaration, a default accessibility is used.
Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.
Nested types, which are members of other types, can have declared accessibilities as indicated in the following table.”
Members of Default member accessibility Allowed declared accessibility of the member
enum Public None
class Private public
protected
internal
private
protected internal
interface Public None
struct Private public
internal
private

Sealed Classes

Sealed” is a special class of access modifier in C#. If a class is marked as sealed, no other class can derive from thatsealed class. In other words, a class marked as sealed can’t act as a base class to any other class.

Program

namespace AccessModifiers
{
sealed class AAA
    {

}
class BBB:AAA
{

}
public class Program
{
public static void Main(string[] args)
{
}
}
}

Compiler Output

'AccessModifiers.BBB': cannot derive from sealed type 'AccessModifiers.AAA'
Hence proved.
 
Point to remember: A class marked sealed can’t act as a base class to any other class.
Access the members of sealed class.

Program

using System;

namespace AccessModifiers
{
sealed class AAA
{
public int x = 100;
public void MethodA()
{
Console.WriteLine(Method A in sealed class”);
}
}
public class Program
{
public static void Main(string[] args)
{
AAA aaa=new AAA();
Console.WriteLine(aaa.x);
aaa.MethodA();
Console.ReadKey();
}
}
}

Compiler Output

100
Method A in sealed class
So, as we discussed, the only difference between a sealed and a non sealed class is that the sealed class cannot be derived from. A sealed class can contain variables, methods, properties like a normal class do.
 
Point to remember: Since we cannot derive from sealed classes, the code from the sealed classes cannot be overridden.
 
Note: Each and every code snippet written in this article is tried and tested.

Constants

Lab1

Our Program class in the console application.

Program

public class Program
    {
private const int x = 100;
public static void Main(string[] args)
        {
            Console.WriteLine(x);
            Console.ReadKey();
        }
    }

Output

100
We see, a constant marked variable or a const variable behaves like a member variable in C#. We can provide it an initial value and can use it anywhere we want.
 
Point to remember: We need to initialize the const variable at the time we create it. We are not allowed to initialize it later in our code or program.

Lab2

using System;

namespace AccessModifiers
{
public class Program
{
private const int x = y + 100;
private const int y = z – 10;
private const int z = 300;

public static void Main(string[] args)
{
System.Console.WriteLine({0} {1} {2}”,x,y,z);
Console.ReadKey();
}
}
}

Can you guess the output? What? Is it a compiler error?

Output

390 290 300
Shocked? A constant field can no doubt depend upon another constant. C# is very smart to realize that to calculate the value of variable marked const, it first needs to know the value of y variable. y’s value depends upon anotherconst variable z, whose value is set to 300. Thus C# first evaluates to 300 then becomes 290 i.e. z -1 and finally x takes on the value of y i.e. 290 + 100 resulting in 390.

Lab3

Program

using System;

namespace AccessModifiers
{
public class Program
{
private const int x = y + 100;
private const int y = z – 10;
private const int z = x;

public static void Main(string[] args)
{
System.Console.WriteLine({0} {1} {2}”,x,y,z);
Console.ReadKey();
}
}
}

Output

The evaluation of the constant value for 'AccessModifiers.Program.x' involves a circular definition
We just assigned z=x from our previous code, and it resulted into error. The value of const x depends upon y, and yin turn depends upon value of z, but we see value depends upon as is assigned directly to z, it results in a circular dependency.
 
Point to remember: Like classes, const variables cannot be circular, i.e., they cannot depend on each other.

Lab4

const is a variable whose value once assigned cannot be modified, but its value is determined at compile time only.
using System;

namespace AccessModifiers
{
public class Program
{
public const ClassA classA=new ClassA();
public static void Main(string[] args)
{
}
}

public class ClassA
{

}
}

Output

Compile time error: 'AccessModifiers.Program.classA' is of type 'AccessModifiers.ClassA'.
A const field of a reference type other than string can only be initialized with null.
 
Point to remember: A const field of a reference type other than string can only be initialized with null.
If we assign the value to null in Program class:
using System;

namespace AccessModifiers
{
public class Program
{
public const ClassA classA=null;
public static void Main(string[] args)
{
}
}

public class ClassA
{

}
}

Then the error will vanish. The error disappears as we now initialize classA to an object which has a value that can be determined at compile time i.e., null. We can never change the value of classA, so it will always be null. Normally, we do not have consts as classA reference type as they have value only at runtime.
 
Point to remember: One can only initialize a const variable to a compile time value, i.e., a value available to the compiler while it is executing.
new() actually gets executed at runtime and therefore does not get value at compile time. So this results in an error.

Lab5

ClassA

public class ClassA
    {
public const int aaa = 10;
    }

Program

public class Program
    {
public static void Main(string[] args)
        {
            ClassA classA=new ClassA();
            Console.WriteLine(classA.aaa);
            Console.ReadKey();
        }
    }

Output

Compile time error: Member 'AccessModifiers.ClassA.aaa'
cannot be accessed with an instance reference; qualify it with a type name instead
 
Point to remember: A constant by default is static and we can’t use the instance reference, i.e., a name to reference a const. A const has to be static as no one will be allowed to make any changes to a const variable.
Just mark the const as static.
using System;

namespace AccessModifiers
{
public class ClassA
{
public static const int aaa = 10;
}

public class Program
{
public static void Main(string[] args)
{
ClassA classA=new ClassA();
Console.WriteLine(classA.aaa);
Console.ReadKey();
}
}
}

Output

Compile time error: The constant 'AccessModifiers.ClassA.aaa' cannot be marked static
C# tells us frankly that a field i.e. already static by default cannot be marked as static.
Point to remember: A const variable cannot be marked as static.

Lab6

using System;

namespace AccessModifiers
{
public class ClassA
{
public const int xxx = 10;
}

public class ClassB:ClassA
{
public const int xxx = 100;
}

public class Program
{
public static void Main(string[] args)
{
Console.WriteLine(ClassA.xxx);
Console.WriteLine(ClassB.xxx);
Console.ReadKey();
}
}
}

Output

10
100
Compiler Warning: 'AccessModifiers.ClassB.xxx' hides inherited
member 'AccessModifiers.ClassA.xxx'. Use the new keyword if hiding was intended.
We can always create a const with the same name in the derived class as another const in the base class. The constvariable of class ClassB xxx will hide the const xxx in class ClassA for the class ClassB only.

Static Fields

Point to remember: A variable in C# can never have an uninitialized value.
Let’s discuss this in detail.

Lab1

Program

using System;

namespace AccessModifiers
{
public class Program
{
private static int x;
private static Boolean y;
public static void Main(string[] args)
{
Console.WriteLine(x);
Console.WriteLine(y);
Console.ReadKey();
}
}
}

Output

0
False
 
Point to rememberStatic variables are always initialized when the class is loaded first. An int is given a default value of zero and a bool is given a default to False.

Lab2

Program

using System;

namespace AccessModifiers
{
public class Program
{
private int x;
private Boolean y;
public static void Main(string[] args)
{
Program program=new Program();
Console.WriteLine(program.x);
Console.WriteLine(program.y);
Console.ReadKey();
}
}
}

Output

0
False
 
Point to remember: An instance variable is always initialized at the time of creation of its instance.
An instance variable is always initialized at the time of creation of its instance. The keyword new will create an instance of the class Program. It will allocate memory for each of the non static, i.e. instance variables and then initialize each of them to their default values as well.

Lab3

Program

using System;

namespace AccessModifiers
{
public class Program
{
private static int x = y + 10;
private static int y = x + 5;
public static void Main(string[] args)
{
Console.WriteLine(Program.x);
Console.WriteLine(Program.y);
Console.ReadKey();
}
}
}

Output

10
15
Output is self explanatory. C# always initializes static variables to their initial value after creating them. Variables xand are therefore given a default of zero value. C# now realizes that these variables declared need to be assigned some values. C# does not read all the lines at once but only one at a time. It will now read the first line and as the variable y has a value of 0, so will get a value of 10. Then at the next line, is the value of x + 5. The variable xhas a value of 10 and so now becomes 15. As C# does not see both lines at the same time, it does not notice the circularity of the above definition.

Lab4

Program

using System;

namespace AccessModifiers
{
public class Program
{
int x = y + 10;
int y = x + 5;
public static void Main(string[] args)
{

}
}
}

Output

Compile time error:

A field initializer cannot reference the non-static field, method, or property ‘AccessModifiers.Program.y’
A field initializer cannot reference the non-static field, method, or property ‘AccessModifiers.Program.x’

The lab we did in Lab3 does not work for instance variables as the rules of an instance variable are quite different than that of static variables. The initializer of an instance variable has to be determined at the time of creation of the instance. The variable y does not have a value at this point in time. It can’t refer to variables of the same object at the time of creation. So we can refer to no instance members to initialize an instance member.

Readonly Fields

Readonly fields are one of the most interesting topics of OOP in C#.

Lab1

Program

using System;

namespace AccessModifiers
{
public class Program
{
public static readonly int x = 100;

public static void Main(string[] args)
{
Console.WriteLine(x);
Console.ReadKey();
}
}
}

Output

100
Wow, we get no error, but remember not to use a non static variable inside a static method, else we’ll get an error.

Lab2

Program

using System;

namespace AccessModifiers
{
public class Program
{
public static readonly int x = 100;

public static void Main(string[] args)
{
x = 200;
Console.WriteLine(x);
Console.ReadKey();
}
}
}

Output

Compile time error: A static readonly field cannot be assigned to
(except in a static constructor or a variable initializer).
We cannot change the value of a readonly field except in a constructor.
Point to remember: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer).

Lab3

Program

using System;

namespace AccessModifiers
{
public class Program
{
public static readonly int x;

public static void Main(string[] args)
{
}
}
}

Here we find one difference between const and readonly, unlike constreadonly fields need not have to be initialized at the time of creation.

Lab4

Program

using System;

namespace AccessModifiers
{
public class Program
{
public static readonly int x;

static Program()
{
x = 100;
Console.WriteLine(Inside Constructor”);
}

public static void Main(string[] args)
{
Console.WriteLine(x);
Console.ReadKey();
}
}
}

Output

Inside Constructor
100
One more major difference between const and readonly is seen here. A static readonly variable can be initialized in the constructor as well, like we have seen in the above mentioned example.

Lab5

Program

using System;

namespace AccessModifiers
{
public class ClassA
{

}
public class Program
{

public readonly ClassA classA=new ClassA();
public static void Main(string[] args)
{
}
}
}

We have already seen this example in const section. The same code gave an error with const does not give an error with readonly fields. So we can say that readonly is a more generic const and it makes our programs more readable as we refer to a name and not a number. Is 10 more intuitive or priceofcookie easier to understand? The compiler would for efficiency convert all consts and readonly fields to the actual values.

Lab6

Program

using System;

namespace AccessModifiers
{
public class ClassA
{
public int readonly x= 100;
}
public class Program
{
public static void Main(string[] args)
{
}
}
}

Output

Compile time error:

Member modifier ‘readonly’ must precede the member type and name
Invalid token ‘=’ in class, struct, or interface member declaration

Wherever we need to place multiple modifiers, remind yourself that there are rules that decide the order of access modifiers, which comes first. Now here the readonly modifier precedes the data type int, we already discussed at the very start of the article. This is just a rule that must always be remembered.

Lab7

Program

using System;

namespace AccessModifiers
{
public class ClassA
{
public readonly int x= 100;

void Method1(ref int y)
{

}

void Method2()
{
Method1(ref x);
}
}
public class Program
{

public static void Main(string[] args)
{
}
}
}

Output

Compile time error:

A readonly field cannot be passed ref or out (except in a constructor)
A readonly field can’t be changed by anyone except a constructor.
The method Method1 expects a ref parameter which if we have forgotten allows you
to change the value of the original. Therefore C# does not permit a readonly
as a parameter to a method that accepts a ref or an out parameters.

Summary

Let’s recall all the points that we have to remember:
  1. The default access modifier is private for class members.
  2. A class marked as internal can have its access limited to the current assembly only.
  3. Namespaces as we see by default can have no accessibility specifiers at all. They are by default public and we cannot add any other access modifier including public again too.
  4. A class can only be public or internal. It cannot be marked as protected or private. The default isinternal for the class.
  5. Members of a class can be marked with all the access modifiers, and the default access modifier is private.
  6. Protected internal means that the derived class and the class within the same source code file can have access.
  7. Between public and internalpublic always allows greater access to its members.
  8. Base class always allows more accessibility than the derived class.
  9. The return values of a method must have greater accessibility than that of the method itself.
  10. A class marked sealed can’t act as a base class to any other class.
  11. Since we cannot derive from sealed classes, the code from the sealed classes cannot be overridden.
  12. We need to initialize the const variable at the time we create it. We are not allowed to initialize it later in our code or program.
  13. Like classes, const variables cannot be circular, i.e., they cannot depend on each other.
  14. const field of a reference type other than string can only be initialized with null.
  15. One can only initialize a const variable to a compile time value, i.e., a value available to the compiler while it is executing.
  16. A constant by default is static and we can’t use the instance reference, i.e., a name to reference a const. Aconst has to be static as no one will be allowed to make any changes to a const variable.
  17. const variable cannot be marked as static.
  18. A variable in C# can never have an uninitialized value.
  19. Static variables are always initialized when the class is loaded first. An int is given a default value of zero and a bool is given a default of False.
  20. An instance variable is always initialized at the time of creation of its instance.
  21. static readonly field cannot be assigned to (except in a static constructor or a variable initializer).

Conclusion

With this article, we completed almost all the scenarios of access modifiers. We did a lot of hands-on lab to clear our concepts. I hope my readers now know by heart about these basic concepts and will never forget them. In my upcoming article, i.e., the last article of this series, we’ll be discussing about Properties and Indexers in C#.
Keep coding and enjoy reading. 
Also do not forget to rate/comment/like my article if it helped you by any means, this helps me get motivated and encourages me to write more and more.

Read more:

Other Series

My other series of articles:

For more informative articles visit my Blog.

For more technical articles you can reach out to CodeTeddy.

Diving in OOP (Day 4): Polymorphism and Inheritance (All About Abstract Classes in C#)


1. Introduction

We learnt a lot about polymorphism and inheritance. In this article of the series “Diving in OOP”, we’ll discuss about the most hot and exciting topic of OOP in C#, i.e., Abstract Classes. The concept of Abstract classes is the same for any other language, but in C# we deal with it in a bit different way. Abstract classes play a different and very interesting role in polymorphism and inheritance. We’ll cover all the aspects of abstract classes with our hands-on lab and theory as an explanation to what output we get. We’ll also list down points to remember at the end of the article.

Pre-requisites

Wonder, we are dealing with the fourth part of our learning objective. Now my only expectation with my readers is to enjoy the series.

2. Roadmap

Let’s recall our road map:

3. Abstract Classes

Let’s get the definition from MSDN:

“The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class. An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.
Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return type of the method.”

4. Abstract Classes in Action

Add a console application named “InheritanceAndPolymorphism” in your Visual Studio. You’ll get a class namedProgram.cs, just add one more class named ClassA.cs, note that the ClassA should be marked abstract, and the following code to ClassA.cs and Program.cs:
using System;

namespace InheritanceAndPolymorphism
{
public abstract class ClassA
{

}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassA classA = new ClassA();
Console.ReadKey();
}
}
}

Compile the code.

Output

Compile time error: Cannot create an instance of the abstract class or interface 'InheritanceAndPolymorphism.ClassA'
 
Point to remember: We cannot create an object of abstract class using new keyword.
Now we go into understanding the concept. No power can stop abstract keyword to be written before a class. It acts as a modifier to the class. We cannot create an object of abstract class using new keyword. Seems that the class is useless for us as we cannot use it for other practical purposes as we used to do.

5. Non Abstract Method Definition in Abstract Class

Let’s add some code to our abstract class:
    /// <summary>
    /// Abstract class ClassA
    /// </summary>
    public abstract class ClassA
    {
        public int a;
        public void XXX()
        {

}
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassA classA = new ClassA();
Console.ReadKey();
}
}

We again see the error that we encountered earlier. Again, it reminds that we cannot use new if we have already used an abstract modifier.

6. Abstract Class Acting as a Base Class

Let’s add one more class now:
    /// <summary>
    /// Abstract class ClassA
    /// </summary>
    public abstract class ClassA
    {
        public int a;
        public void XXX()
        {

}
}

/// <summary>
/// Derived class.
/// Class derived from abstract class ClassA
/// </summary>
public class ClassB:ClassA
{

}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassB classB = new ClassB();
Console.ReadKey();
}
}

We get no error? A class can be derived from abstract class. Creating an object of ClassB does not gives us any error.
 
Point to remember: A class can be derived from an abstract class.
 
Point to remember: A class derived from an abstract class can create an object.

7. Non Abstract Method Declaration in Abstract Class

Another scenario:
    /// <summary>
    /// Abstract class ClassA
    /// </summary>
    public abstract class ClassA
    {
        public int a;
        public void XXX()
        {

}

public void YYY();
}

/// <summary>
/// Derived class.
/// Class derived from abstract class ClassA.
/// </summary>
public class ClassB:ClassA
{

}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassB classB = new ClassB();
Console.ReadKey();
}
}

We just declared a method named YYY() in our abstract class ClassA.
Compile the code, we get:

Output

Compile time error: 'InheritanceAndPolymorphism.ClassA.YYY()' 
must declare a body because it is not marked abstract, extern, or partial
 
InheritanceAndPolymorphism is the namespace I used for my console application so you can ignore that, no need to confuse with the logic.
In the above code, we just added a method declaration in the abstract class. An abstract method indicates that the actual definition or code of the method is created somewhere else. The method prototype declared in abstractclass must also be declared abstract as per the rules of C#.

8. Abstract Method Declaration in Abstract Class

Just make the method YYY() as abstract in ClassA:
    /// <summary>
    /// Abstract class ClassA
    /// </summary>
    public abstract class ClassA
    {
        public int a;
        public void XXX()
        {

}

abstract public void YYY();
}

/// <summary>
/// Derived class.
/// Class derived from abstract class ClassA.
/// </summary>
public class ClassB:ClassA
{

}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassB classB = new ClassB();
Console.ReadKey();
}
}

Output

Compiler error: 'InheritanceAndPolymorphism.ClassB' does not implement 
inherited abstract member 'InheritanceAndPolymorphism.ClassA.YYY()'
 
Point to remember: If we declare any method as abstract in our abstract class, then it’s the responsibility of the derived class to provide the body of that abstract method, unless a body is provided for that abstract method, we cannot create an object of that derived class.
In the above mentioned scenario, we declared method YYY() as abstract in ClassA. Since ClassB derives fromClassA, now it becomes the responsibility of ClassB to provide the body of that abstract method, else we cannot create an object of ClassB.

9. Abstract Method Implementation in Derived Class

Now provide a body of method YYY() in ClassB. Let’s see what happens:
    /// <summary>
    /// Abstract class ClassA
    /// </summary>
    public abstract class ClassA
    {
        public int a;
        public void XXX()
        {

}

abstract public void YYY();
}

/// <summary>
/// Derived class.
/// Class derived from abstract class ClassA.
/// </summary>
public class ClassB:ClassA
{
public void YYY()
{

}
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassB classB = new ClassB();
Console.ReadKey();
}
}

Everything seems fine now, but no? Compile the code, what we get:

Output

Two compile time errors this time:
Compile time error: 'InheritanceAndPolymorphism.ClassB' does not implement 
inherited abstract member 'InheritanceAndPolymorphism.ClassA.YYY()'

Compile time warning: ‘InheritanceAndPolymorphism.ClassB.YYY()’ hides
inherited member ‘InheritanceAndPolymorphism.ClassA.YYY()’.

To make the current member override that implementation, add the override keyword. Otherwise add the newkeyword.
We have been continuously trying to compile our code, but no success till now. The compiler error indicates clearly that both of our base and derived class contains the same method named YYY().
If both our derived class and base class contain the method with the same name, always an error occurs. The only way to overcome this error is derived class explicitly add the modifier override to its method signature. We have already discussed such scenarios in our previous parts of the articles of Diving in OOP series.
Let’s add the override keyword before derived class method YYY().
/// <summary>
    /// Abstract class ClassA
    /// </summary>
    public abstract class ClassA
    {
        public int a;
        public void XXX()
        {

}

abstract public void YYY();
}

/// <summary>
/// Derived class.
/// Class derived from abstract class ClassA.
/// </summary>
public class ClassB:ClassA
{
public override void YYY()
{

}
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassB classB = new ClassB();
Console.ReadKey();
}
}

We get no warning or error now?

10. Abstract Method Implementation in Derived Class with Different Return Type

Let’s just change the return type of the method YYY() in derived class:
  /// <summary>
    /// Abstract class ClassA
    /// </summary>
    public abstract class ClassA
    {
        public int a;
        public void XXX()
        {

}

abstract public void YYY();
}

/// <summary>
/// Derived class.
/// Class derived from abstract class ClassA.
/// </summary>
public class ClassB:ClassA
{
public override int YYY()
{

}
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassB classB = new ClassB();
Console.ReadKey();
}
}

We changed return type of method YYY from void to int in derived class. Compile the code.

Output

Compile time error: 'InheritanceAndPolymorphism.ClassB.YYY()': return type must be 'void' 
to match overridden member 'InheritanceAndPolymorphism.ClassA.YYY()'
Therefore one more constraint.
 
Point to remember: When we override an abstract method from a derived class, we cannot change the parameters passed to it or the return type irrespective of the number of methods declared as abstract in abstractclass.
Let’s see the implementation of the second line mentioned in “point to remember”,
    /// <summary>
    /// Abstract class ClassA
    /// </summary>
    public abstract class ClassA
    {
        public int a;
        public void XXX()
        {

}

abstract public void YYY();
abstract public void YYY1();
abstract public void YYY2();
abstract public void YYY3();
}

/// <summary>
/// Derived class.
/// Class derived from abstract class ClassA.
/// </summary>
public class ClassB:ClassA
{
public override int YYY()
{

}
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassB classB = new ClassB();
Console.ReadKey();
}
}

Compiler error:
'InheritanceAndPolymorphism.ClassB' does not implement 
inherited abstract member 'InheritanceAndPolymorphism.ClassA.YYY3()'

‘InheritanceAndPolymorphism.ClassB’ does not implement inherited
abstract member ‘InheritanceAndPolymorphism.ClassA.YYY2()’

‘InheritanceAndPolymorphism.ClassB’ does not implement inherited
abstract member ‘InheritanceAndPolymorphism.ClassA.YYY1()’

If we implement these three methods in derived class, we’ll get no error.
Point to remember: An abstract class means that the class is incomplete and cannot be directly used. Anabstract class can only be used as a base class for other classes to derive from.

11. Variable Initialization in Abstract Class

Therefore as seen earlier, we get an error if we use a new keyword on an abstract class. If we do not initialize a variable in an abstract class like we used a, it will automatically have a default value of 0 which is what the compiler kept warning us about. We can initialize int variable a of ClassA to any value we wish. The variables in abstractclass act similar to that in any other normal class.

12. Power of Abstract Class

Whenever a class remains incomplete, i.e., we do not have the code for some methods, we mark those methodsabstract and the class is marked abstract as well. And so, we can compile our class without any error or blocker. Any other class can then derive from our abstract class but they have to implement the abstract, i.e., our incomplete methods from abstract class.
Abstract therefore enables us to write code for a part of the class and allows the others (derived classes) to complete the rest of the code.

13. Abstract Method in Non Abstract Class

Let’s take another code block:
    /// <summary>
    /// Abstract class ClassA
    /// </summary>
    public class ClassA
    {
        public int a;
        public void XXX()
        {

}

abstract public void YYY();
}

/// <summary>
/// Derived class.
/// Class derived from abstract class ClassA.
/// </summary>
public class ClassB:ClassA
{
public override void YYY()
{

}
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassB classB = new ClassB();
Console.ReadKey();
}
}

Compile the code.

Output

Compiler error: 'InheritanceAndPolymorphism.ClassA.YYY()' is abstract 
but it is contained in non-abstract class 'InheritanceAndPolymorphism.ClassA'
We just removed abstract keyword from class ClassA. The error clearly conveys a message that if a single method is marked abstract in a class, then the class will have to be abstract as well.
 
Point to remember: If a class has even a single abstract method, then the class has to be declared abstract as well.
 
Point to remember: An abstract method also cannot use the modifiers such as static or virtual.
We can only have the abstract method in an abstract class. Any class that derives from abstract class has to give implementation to its abstract method. By default, the modifier new gets added to the derived class method, that makes it a new/different method.

14. Abstract Base Method

    /// <summary>
    /// Abstract class ClassA
    /// </summary>
    public abstract class ClassA
    {
        public int a;
        public void XXX()
        {

}

abstract public void YYY();
}

/// <summary>
/// Derived class.
/// Class derived from abstract class ClassA.
/// </summary>
public class ClassB:ClassA
{
public override void YYY()
{
base.YYY();
}
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassB classB = new ClassB();
Console.ReadKey();
}
}

Output

Compile time error : Cannot call an abstract base member: 
'InheritanceAndPolymorphism.ClassA.YYY()'
We cannot call the method YYY() from the base class ClassA as it does not carry any implementation/code along with it and has also been declared abstract. Common sense prevails? and C# off course does not allow us to call a method that does not contain code.

15. Abstract Class Acting as Derived as Well as Base Class

Let’s modify our code a bit, and prepare our class structure something as follows:
    /// <summary>
    /// Base class ClassA
    /// </summary>
    public class ClassA
    {
        public virtual void XXX()
        {
            Console.WriteLine("ClassA XXX");
        }
    }

/// <summary>
/// Derived abstract class.
/// Class derived from base class ClassA.
/// </summary>
public abstract class ClassB:ClassA
{
public new abstract void XXX();
}

public class ClassC:ClassB
{
public override void XXX()
{
System.Console.WriteLine(ClassC XXX”);
}
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassA classA = new ClassC();
ClassB classB = new ClassC();
classA.XXX(); classB.XXX();
}
}

Compile the code, and run.

Output

ClassA XXX
ClassC XXX
We created a base class named ClassA that is not abstract and added a virtual method XXX to it. Since the method is non abstract but marked virtual so it has to be overridden in its deriving class. We added one more class named ClassB and marked that class abstract, note that this class is derived from ClassA. So this class has a choice to override the method marked as virtual in base class. But we’ll do something different and tricky,
We marked XXX method in this derived class as new abstract, and did not give anybody to this method. Now what? We will add one more class ClassC, that will derive from ClassBClassC has no choice but to override the methodXXX. Therefore we override the method XXX in ClassC.
In main method, we created two objects ClassA classA = new ClassC(); and ClassB classB = new ClassC();
First object looks like that of ClassC but refers to ClassA and second one again seems to be like ClassC but refers to ClassB.
In case of classA.XXX() will definitely first look into the class ClassA. Here, it finds the method XXX marked as virtual. These kind of scenarios we have already taken n number of times in our earlier articles where we discussed about run time polymorphism . C# will then crawl over to class ClassB. Here it gets shocked that the method XXX()is abstract, i.e., there is no code or implementation for method XXX() and also that it is a method marked as new, thus severing all links with the base class. And so flow halts and all and the method XXX() from ClassA gets executed.
In the case of b.XXX()(), since the method is new, the links to the base class gets broken, we are left with no choice but to invoke the method from ClassC as it says override.
We cannot replace the modifier new with the keyword override for the method XXX() in abstract class ClassB.
Let’s replace the override modifier in ClassC with “new” like:
 public class ClassC:ClassB
     {
        public new void XXX()
        {
            System.Console.WriteLine("ClassC XXX");
        }
     }

Output

Compile time error: 'InheritanceAndPolymorphism.ClassC' does not implement 
inherited abstract member 'InheritanceAndPolymorphism.ClassB.XXX()'
The error indicates that as there is no code for the method XXX. Remember the XXX() of class ClassA has nothing to do at all with that of ClassB and ClassC.
Also there is one more point to remember.
 
Point to remember: Virtual methods run slower that non virtual methods.

16. Can Abstract Class be Sealed?

Let’s take this final question into our consideration. Let’s test this too with an example.
    /// <summary>
    /// sealed abstract class ClassA
    /// </summary>
    public sealed abstract class ClassA
    {
        public abstract void XXX()
        {
            Console.WriteLine("ClassA XXX");
        }
    }

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
}
}

Compile the code.

Output

Compile time error: 'InheritanceAndPolymorphism.ClassA': 
an abstract class cannot be sealed or static
And so we get two points to remember.
 
Point to rememberAbstract class cannot be sealed class.
 
Point to rememberAbstract class cannot be a static class.

17. Points to Remember

Let’s sum up all the points to remember:
  1. We cannot create an object of abstract class using new keyword.
  2. A class can be derived from an abstract class.
  3. Class derived from an abstract class can create an object.
  4. If we declare any method as abstract in our abstract class, then it’s the responsibility of the derived class to provide the body of that abstract method, unless a body is provided for that abstract method, we cannot create an object of that derived class.
  5. When we override an abstract method from a derived class, we cannot change the parameters passed to it or the return type irrespective of the number of methods declared as abstract in abstract class.
  6. An abstract class means that the class is incomplete and cannot be directly used. An abstract class can only be used as a base class for other classes to derive from.
  7. If a class has even a single abstract method, then the class has to be declared abstract as well.
  8. An abstract method also cannot use the modifiers such as static or virtual.
  9. Virtual methods run slower that non virtual methods.
  10. Abstract class cannot be sealed class.
  11. Abstract class cannot be a static class.

18. Conclusion

With this article, we complete our understanding of inheritance and polymorphism. We have covered almost all the aspects of Polymorphism and Inheritance. Abstract classes are one of my favorites so I just wanted to take them separately. I hope my readers enjoyed this article too and learnt about abstract classes in C#.
In my upcoming articles of the series, we’ll be discussing about other OOP features in the C# way with full hands-on lab and lot of discussion.
Keep coding and enjoy reading. 
Also do not forget to rate/comment/like my article if it helped you by any means. This helps me to get motivated and encourages me to write more and more.

Read more:

Other Series

My other series of articles:

For more informative articles visit my Blog.

For more technical articles you can reach out to CodeTeddy.

Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time Polymorphism)


1. Introduction

This part of the article series will focus more on run time polymorphism also called late binding. We’ll use the same technique of learning, less theory and more hands-on. We’ll take small code snippets to learn the concept more deeply. To master this concept is like learning more than 50% of OOP.

2. Pre-requisites

Since this is the third part of the series, I expect my readers to be experts in compile time polymorphism and inheritance. Although it doesn’t matter if you are directly starting to learn from this article, you can take the other articles later.

3. Roadmap

Our roadmap for learning OOP is clear, but let’s just revise it:

4. Runtime Polymorphism or Late Binding or Dynamic Binding

In simple C# language, in run time polymorphism or method overriding, we can override a method in base class by creating similar method in derived class this can be achieved by using inheritance principle and using “virtual & override” keywords.

5. What are New and Override Keywords in C#?

Create a console application named InheritanceAndPolymorphism in your Visual Studio.
Just add two classes and keep the Program.cs as it is.The two classes will be named ClassA.cs and ClassB.cs and add one method in each class as follows:

ClassA

public class ClassA
    {
        public void AAA()
        {
            Console.WriteLine("ClassA AAA");
        }

public void BBB()
{
Console.WriteLine(ClassA BBB”);
}

public void CCC()
{
Console.WriteLine(ClassA CCC”);
}
}

ClassB

    public class ClassB
    {
        public void AAA()
        {
            Console.WriteLine("ClassB AAA");
        }

public void BBB()
{
Console.WriteLine(ClassB BBB”);
}

public void CCC()
{
Console.WriteLine(ClassB CCC”);
}
}

Program.cs

    /// <summary>
    /// Program: used to execute the method.
    /// Contains Main method.
    /// </summary>
    public class Program
    {
        private static void Main(string[] args)
        {

}
}

We see both classes ClassA and ClassB have the same number of methods with similar names in both the classes. Now let’s inherit ClassA from ClassB, and create instances of the classes and call their methods in program.cs.
So our code for the two classes becomes:
/// <summary>
    /// ClassB, acting as a base class
    /// </summary>
    public class ClassB
    {
        public void AAA()
        {
            Console.WriteLine("ClassB AAA");
        }

public void BBB()
{
Console.WriteLine(ClassB BBB”);
}

public void CCC()
{
Console.WriteLine(ClassB CCC”);
}
}

/// <summary>
/// Class A, acting as a derived class
/// </summary>
public class ClassA : ClassB
{
public void AAA()
{
Console.WriteLine(ClassA AAA”);
}

public void BBB()
{
Console.WriteLine(ClassA BBB”);
}

public void CCC()
{
Console.WriteLine(ClassA CCC”);
}
}

Program.cs

    /// <summary>
    /// Program: used to execute the method.
    /// Contains Main method.
    /// </summary>
    public class Program
    {
        private static void Main(string[] args)
        {
            ClassA x = new ClassA();
            ClassB y=new ClassB();
            ClassB z=new ClassA();

x.AAA(); x.BBB(); x.CCC();
y.AAA(); y.BBB();y.CCC();
z.AAA(); z.BBB(); z.CCC();
}
}

Now press F5, i.e., run the code, what do we get?

Output

ClassB AAA
ClassB BBB
ClassB CCC
ClassA AAA
ClassA BBB
ClassA CCC
ClassB AAA
ClassB BBB
ClassB CCC
But with the output, we also got three warnings.

Warnings

'InheritanceAndPolymorphism.ClassA.AAA()' hides inherited member 
'InheritanceAndPolymorphism.ClassB.AAA()'. Use the new keyword if hiding was intended.

‘InheritanceAndPolymorphism.ClassA.BBB()’ hides inherited member
‘InheritanceAndPolymorphism.ClassB.BBB()’. Use the new keyword if hiding was intended.

‘InheritanceAndPolymorphism.ClassA.CCC()’ hides inherited member
‘InheritanceAndPolymorphism.ClassB.CCC()’. Use the new keyword if hiding was intended.

 
Point to remember: In C#, a smaller object could be equated to a bigger object.
Class ClassB is the super class of class ClassA. That means ClassA is the derived class and ClassB is the base class. The class ClassA comprises ClassB and something more. So we can conclude that object of ClassA is bigger than object of ClassB. Since ClassA is inherited from ClassB, it contains its own methods and properties. Moreover, it will also contain methods/properties that are inherited from ClassB too.
Let’s take the case of object y. It looks like ClassB and initialized by creating an object that also looks like ClassB, well and good. Now, when we call the methods AAA and BBB and CCC through the object y, we know that it will call them from ClassB.
Object x looks like that of ClassA, i.e., the derived class. It is initialized to an object that looks like ClassA. When we call AAABBB and CCC method through x, it calls AAABBB and CCC from ClassA.
Now there is a somewhat tricky situation we are dealing with:
Object z again looks like ClassB, but it is now initialized to an object that looks like ClassA which does not give an error as explained earlier. But there is no change at all in the output we get and the behavior is identical to that of object y.Therefore initializing it to an object that looks like ClassB or ClassA does not seem to matter.

6. Experiment

Let’s experiment with the code, and put override behind AAA and new behind BBB methods of ClassA, i.e., the derived class.
Our code is as follows:

ClassB

    /// <summary>
    /// ClassB, acting as a base class
    /// </summary>
    public class ClassB
    {
        public void AAA()
        {
            Console.WriteLine("ClassB AAA");
        }

public void BBB()
{
Console.WriteLine(ClassB BBB”);
}

public void CCC()
{
Console.WriteLine(ClassB CCC”);
}
}

ClassA

    /// <summary>
    /// Class A, acting as a derived class
    /// </summary>
    public class ClassA : ClassB
    {
        public override void AAA()
        {
            Console.WriteLine("ClassA AAA");
        }

public new void BBB()
{
Console.WriteLine(ClassA BBB”);
}

public void CCC()
{
Console.WriteLine(ClassA CCC”);
}
}

Program.cs

    /// <summary>
    /// Program: used to execute the method.
    /// Contains Main method.
    /// </summary>
    public class Program
    {
        private static void Main(string[] args)
        {
            ClassB y = new ClassB();
            ClassA x = new ClassA();
            ClassB z = new ClassA();

y.AAA(); y.BBB(); y.CCC();
x.AAA(); x.BBB(); x.CCC();
z.AAA(); z.BBB(); z.CCC();

Console.ReadKey();
}
}

We get output:
Error:  'InheritanceAndPolymorphism.ClassA.AAA()': cannot override inherited member 
'InheritanceAndPolymorphism.ClassB.AAA()' because it is not marked virtual, abstract, or override
InheritanceAndPolymorphism: It’s the namespace I used for my console application, so you can ignore that.
We got an error after we added these two modifiers in the derived class methods, the error tells us to mark the methods virtualabstract or override in the base class.
OK, how does it matter to me?
I marked all the methods of base class as virtual.
Now our code and output looks like:
/// <summary>
    /// ClassB, acting as a base class
    /// </summary>
    public class ClassB
    {
        public virtual void AAA()
        {
            Console.WriteLine("ClassB AAA");
        }

public virtual void BBB()
{
Console.WriteLine(ClassB BBB”);
}

public virtual void CCC()
{
Console.WriteLine(ClassB CCC”);
}
}

/// <summary>
/// Class A, acting as a derived class
/// </summary>
public class ClassA : ClassB
{
public override void AAA()
{
Console.WriteLine(ClassA AAA”);
}

public new void BBB()
{
Console.WriteLine(ClassA BBB”);
}

public void CCC()
{
Console.WriteLine(ClassA CCC”);
}
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassB y = new ClassB();
ClassA x = new ClassA();
ClassB z = new ClassA();

y.AAA(); y.BBB(); y.CCC();
x.AAA(); x.BBB(); x.CCC();
z.AAA(); z.BBB(); z.CCC();

Console.ReadKey();
}
}

Output

ClassB AAA
ClassB BBB
ClassB CCC
ClassA AAA
ClassA BBB
ClassA CCC
ClassA AAA
ClassB BBB
ClassB CCC
 
Point to remember: The override modifier is needed as the derived class methods will get first priority and be called upon.
We see here that there is only a single small change in the workings of the object z only and not in x and y. This strange output occurred only after we added virtual modifier in the base class methods. The difference is in the objectzz looks like the base class ClassB but is initialized to an instance that looks like that of derived class ClassA. C# knows this fact. When we run z.AAA(), C# remembers that instance z was initialized by a ClassA object and hence it first goes to class ClassA, too obvious. Here the method has a modifier override which literally means, forget about the data type of which is ClassB, call AAA from ClassA as it overrides the AAA of the base class. The override modifier is needed as the derived class methods will get first priority and be called upon.
We wanted to override the AAA of the base class ClassB. We are infact telling C# that this AAA is similar to the AAAof the one in base class.
New keyword acts in the exact opposite to override keyword. The method BBB as we see has the new modifier.z.BBB() calls BBB from ClassB and not ClassA. New means that the method BBB is a new method and it has absolutely nothing to do with the BBB in the base class. It may have the same name i.e. BBB as in the base class, but that is only a coincidence. As z looks like ClassB, the BBB of ClassB gets called even though there is a BBB inClassA. When we do not write any modifier, then it is assumed that we wrote new. So every time we write a method, C# assumes it has nothing to do with the base class.
 
Point to remember: These modifiers like new and override can only be used if the method in the base class is avirtual method. Virtual means that the base class is granting us permission to invoke the method from the derived class and not the base class. But, we have to add the modifier override if our derived class method has to be called.

7. Run Time Polymorphism with Three Classes

Let’s get into some more action. Let’s involve one more class in the play. Let’s add a class named ClassC, and design our three classes and program.cs as follows:
    /// <summary>
    /// ClassB, acting as a base class
    /// </summary>
    public class ClassB
    {
        public  void AAA()
        {
            Console.WriteLine("ClassB AAA");
        }

public virtual void BBB()
{
Console.WriteLine(ClassB BBB”);
}

public virtual void CCC()
{
Console.WriteLine(ClassB CCC”);
}
}

/// <summary>
/// Class A, acting as a derived class
/// </summary>
public class ClassA : ClassB
{
public virtual void AAA()
{
Console.WriteLine(ClassA AAA”);
}

public new void BBB()
{
Console.WriteLine(ClassA BBB”);
}

public override void CCC()
{
Console.WriteLine(ClassA CCC”);
}
}

/// <summary>
/// Class C, acting as a derived class
/// </summary>
public class ClassC : ClassA
{
public override void AAA()
{
Console.WriteLine(ClassC AAA”);
}

public void CCC()
{
Console.WriteLine(ClassC CCC”);
}
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassB y = new ClassA();
ClassB x = new ClassC();
ClassA z = new ClassC();

y.AAA(); y.BBB(); y.CCC();
x.AAA(); x.BBB(); x.CCC();
z.AAA(); z.BBB(); z.CCC();

Console.ReadKey();
}
}

Output

ClassB AAA
ClassB BBB
ClassA CCC
ClassB AAA
ClassB BBB
ClassA CCC
ClassC AAA
ClassA BBB
ClassA CCC
Don’t be scared of the long example that we have taken. This will help you to learn the concept in detail. We have already learned that we can initialize a base object to a derived object. But vice versa will result into error. This leads to an instance of a base class being initialized to an instance of the derived class. So the question is now that which method will be called when. The method from the base class or from the derived class.
 
Point to remember: If the base class object declared the method virtual and the derived class used the modifieroverride, the derived class method will get called. Otherwise the base class method will get executed. Therefore forvirtual methods, the data type created is decided at run time only.
 
Point to remember: All the methods not marked with virtual are non virtual, and the method to be called is decided at compile time, depending upon the static data type of the object.
If the object of a class is initialized to the same data type, none of the above rule would apply. Whenever we have a mismatch, we always need rules to resolve the mismatch. So we can land up with a scenario where an object to a base class can call a method in the derived class.
The object y that looks like of ClassB but is initialized here to the derived class, i.e., ClassA.
y.AAA() first looks into the class ClassB. Here, it verifies whether the method AAA is marked virtual. The answer is an emphatic no and hence everything comes to halt and the method AAA gets called from class ClassB.
y.BBB also does the same thing, but the method now is defined virtual in class ClassB. Thus C# looks at the classClassB, the one it was initialized to. Here BBB is marked with the modifier “new”. That means BBB is a new method which has nothing to do with the one in the base class. They only accidentally share the same name. So as there is no method called BBB (as it is a new BBB) in the derived class, the one from base class gets called. In the scene ofy.CCC(), the same above steps are followed again, but in the class ClassB, we see the modifier override, that by behaviour overrides the method in the base class. We are actually telling C# to call this method in class ClassA and not the one in the base class, i.e., ClassB.
I just got this picture from the internet that depicts our current situation of classes. We are learning the concept like charm now. OOP is becoming easy now.
The object x which also looks like that of class ClassB is now initialized with an object that looks like our newly introduced class ClassC and not ClassA like before. Since AAA is a non virtual method, it gets called from ClassB. In the case of method BBB, C# now looks into class ClassC. Here, it does not find a method named BBB and so ultimately propagates and now looks into class ClassA. Therefore the above rules repeat on and on and it gets called from class ClassB. In the case of x.CCC, in class ClassC, it is already marked new by default and therefore this method has nothing to do with the one declared in class ClassB. So the one from ClassC does not get called but the one from class ClassB where it is marked as override.
Now if we modify a bit our CCC method in ClassC and change it to the code as shown below:
        public override void CCC()
        {
            Console.WriteLine("ClassC CCC");
        }
We changed default new to override, the CCC of ClassC will now be called.
The last object z looks like that of ClassA but is now initialized to an object that looks like the derived class ClassC, we know we can do this. So z.AAA() when called, looks first into class ClassA where it is flagged as virtual. Do you recall that AAA is non virtual in class ClassB but marked as a virtual in ClassA. From now on, the method AAA is virtual in ClassC also but not in class ClassBVirtual always flows from upwards to downwards like a waterfall. Since AAA() is marked virtual, we now look into class ClassC. Here it is marked override and thereforeAAA() gets called from class ClassC. In the case of BBB()BBB() is marked virtual in class ClassB and new inClassA, but as there is no method BBB in ClassC, none of the modifier matters at all in this case. Finally it gets invoked from class ClassA. At last for method CCC, in class ClassC it is marked as new. Hence, it has no relation with the CCC in class ClassA which results in method CCC gets invoked from ClassA but not ClassB.
One more example:
    internal class A
    {
        public virtual void X()
        {
        }
    }

internal class B : A
{
public new void X()
{
}
}

internal class C : B
{
public override void X()
{
}
}

In the above example, the code is very much self explanatory, the output which we’ll get is:
Error: 'InheritanceAndPolymorphism.C.X()': cannot override inherited member 
'InheritanceAndPolymorphism.B.X()' because it is not marked virtual, abstract, or override
Strange! We got an error as the method X() in class is marked new. That means it hides the X() of class A. If we talk about class Cdoes not supply a method named X. The method X defined in class B has nothing to do with the method defined in class A. This means that the method of class does not inherit the virtual modifier from the method X() of class A. This is what the compiler complained about. As the method X in B has no virtualmodifier, in C we cannot use the modifier override. We can, however, use the modifier new and remove the warning?

8. Cut Off Relations

    internal class A
    {
        public virtual void X()
        {
            Console.WriteLine("Class: A ; Method X");
        }
    }

internal class B : A
{
public new virtual void X()
{
Console.WriteLine(Class: B ; Method X”);
}
}

internal class C : B
{
public override void X()
{
Console.WriteLine(Class: C ; Method X”);
}
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
A a = new C();
a.X();
B b = new C();
b.X();

Console.ReadKey();
}
}

Output

Class: A ; Method X
Class: C ; Method X
If in the above code, we remove the modifier override from X() in class C, we get:

Output

Class: A ; Method X
Class: B ; Method X
Yes, that’s the problem with virtual methods. Sometimes, they are too confusing, the result is entirely different with what we expect. Object looks like an but is initialized to the derived class C. Since is virtual, C# now goes and looks into class C. But before looking into the class C, it realizes that in class BX is new. That’s it, this thing cuts of all connection with the in A. Thus the keyword new is preceded with virtual, otherwise the override modifier would give us an error in class C. As in class is marked as new method, having nothing to do with the class A, class Cinherits a new which also has nothing to do with the class A. The in class is related to the of class and not of class A. Thus the of class gets invoked.
In the second case, object b looks like class now but in turn is initialized to an object of class C. C# first looks at classB. Here is new and virtual both, which makes it a unique method X. Sadly, the in has the override modifier which sees to it that the X of C hides the X of B. This calls the of instead. If we remove the override modifier from in class C, the default will be new, that cuts off the relation from the X of B. Thus, as it is, a new method, the Xof gets invoked.
virtual method cannot be marked by the modifiers staticabstract or override. A non virtual method is said to be invariant. This means that the same method gets called always, irrespective of whether one exists in the base class or derived class. In a virtual method, the run-time type of the object decides on which method to be called and not the compile-time type as is in the case of non virtual methods. For a virtual method, there exists a most derived implementation which always gets called.

9. Runtime Polymorphism with Four Classes

OK! We did a lot of coding. How about if I tell you that we are going to add one more class to our code, yes that is class ClassD. So we go more deep into the concept of Polymorphism and Inheritance.
We add one more class to the three classes solution on which we were working on (remember?). So our new class is named ClassD.
Let’s take our new class into action:
/// <summary>
    /// Class A
    /// </summary>
    public class ClassA
    {
        public virtual void XXX()
        {
            Console.WriteLine("ClassA XXX");
        }
    }

/// <summary>
/// ClassB
/// </summary>
public class ClassB:ClassA
{
public override void XXX()
{
Console.WriteLine(ClassB XXX”);
}
}

/// <summary>
/// Class C
/// </summary>
public class ClassC : ClassB
{
public virtual new void XXX()
{
Console.WriteLine(ClassC XXX”);
}
}

/// <summary>
/// Class D
/// </summary>
public class ClassD : ClassC
{
public override void XXX()
{
Console.WriteLine(ClassD XXX”);
}
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassA a = new ClassD();
ClassB b = new ClassD();
ClassC c=new ClassD();
ClassD d=new ClassD();

a.XXX();
b.XXX();
c.XXX();
d.XXX();

Console.ReadKey();
}
}

Output

ClassB XXX
ClassB XXX
ClassD XXX
ClassD XXX

Explanation

One last explanation of virtual and override will be a bit complex.
The first output, ClassB XXX, is the outcome of the statement a.XXX();. We have the method XXX marked virtual in class ClassA. Therefore, when using new keyword, we now proceed to class ClassB and not ClassD as explained earlier. Here, XXX has an override and since C# knows that class ClassC inherits this function XXX. In the classClassC, since it is marked as new, C# will now go back and not proceed further to class ClassD. Finally the methodXXX gets called from class ClassB as shown in the output above.
If we change the method XXX in class ClassC to override, then C# will proceed to class ClassD and call the XXX of class ClassD as it overrides the XXX of ClassC.
    /// <summary>
    /// Class C
    /// </summary>
    public class ClassC : ClassB
    {
        public override void XXX()
        {
            Console.WriteLine("ClassC XXX");
        }
    }
Remove the override from XXX in class ClassD and the method will get invoked from class ClassC as the default isnew.
When we talk about object b, everything seems similar to object a, as it overrides the XXX of class ClassA.
When we restore back the defaults, let’s have a look at the third line. Object here looks like ClassC. In class ClassC,XXX() is new and therefore it has no connection with the earlier XXX methods. In class ClassD, we actually override the XXX of class ClassC and so the XXX of ClassD gets invoked. Just remove the override and then it will get invoked from class ClassC. The object does not follow any of the above protocols as both the sides of the equal sign are of same data types.
 
Point to remember: An override method is a method that has the override modifier included on it. This introduces a new implementation of a method. We can’t use the modifiers such as newstatic or virtual along withoverride. But abstract is permitted.
Another example:
/// <summary>
    /// Class A
    /// </summary>
    public class ClassA
    {
        public virtual void XXX()
        {
            Console.WriteLine("ClassA XXX");
        }
    }

/// <summary>
/// ClassB
/// </summary>
public class ClassB:ClassA
{
public override void XXX()
{
base.XXX();
Console.WriteLine(ClassB XXX”);
}
}

/// <summary>
/// Class C
/// </summary>
public class ClassC : ClassB
{
public override void XXX()
{
base.XXX();
Console.WriteLine(ClassC XXX”);
}
}

/// <summary>
/// Class D
/// </summary>
public class ClassD : ClassC
{
public override void XXX()
{
Console.WriteLine(ClassD XXX”);
}
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassA a = new ClassB();
a.XXX();
ClassB b = new ClassC();
b.XXX();
Console.ReadKey();
}
}

Output

ClassA XXX
ClassB XXX
ClassA XXX
ClassB XXX
ClassC XXX
When we use the reserved keyword base, we can access the base class methods. Here no matter XXX is virtual or not, it will be treated as non virtual by the keyword base. Thus the base class XXX will always be called. The object aalready knows that XXX is virtual. When it reaches ClassB, it sees base.XXX() and hence it calls the XXX method ofClassA. But in the second case, it first goes to class ClassC, here it calls the base.XXX, i.e., the method XXX of classClassB, which in return invokes method XXX of class ClassA.

10. The Infinite Loop

/// <summary>
    /// Class A
    /// </summary>
    public class ClassA
    {
        public virtual void XXX()
        {
            Console.WriteLine("ClassA XXX");
        }
    }

/// <summary>
/// ClassB
/// </summary>
public class ClassB:ClassA
{
public override void XXX()
{
((ClassA)this).XXX();
Console.WriteLine(ClassB XXX”);
}
}

/// <summary>
/// Program: used to execute the method.
/// Contains Main method.
/// </summary>
public class Program
{
private static void Main(string[] args)
{
ClassA a = new ClassB();
a.XXX();

}
}

Output

Error: {Cannot evaluate expression because the current thread is in a stack overflow state.}
In this kind of case, no casting will stop the infinite loop. Therefore even though this is being cast to a class ClassA, it will always call XXX from class ClassB and not ClassA. So we get no output.

11. Summary

Let’s summarize all the points to remember we got in the big article.
  1. In C#, a smaller object could be equated to a bigger object.
  2. The override modifier is needed as the derived class methods will get first priority and be called upon.
  3. These modifiers like new and override can only be used if the method in the base class is a virtualmethod. Virtual means that the base class is granting us permission to invoke the method from the derived class and not the base class. But, we have to add the modifier override if our derived class method has to be called.
  4. If the base class object declared the method virtual and the derived class used the modifier override, thederived class method will get called. Otherwise, the base class method will get executed. Therefore forvirtual methods, the data type created is decided at run time only.
  5. All the methods not marked with virtual are non virtual, and the method to be called is decided at compile time, depending upon the static data type of the object.
  6. An override method is a method that has the override modifier included on it. This introduces a new implementation of a method. We can’t use the modifiers such as newstatic or virtual along withoverride. But abstract is permitted.

12. Conclusion

Long article, my readers advice me to write short articles, but I can’t help myself. I write in a flow until and unless I clear the whole concept I do not wish to stop. My purpose is to share each and every detail in an easy manner, so that you start loving OOP. However in this article, I have tried to categorize the sections under different headings for the sake of readability.
In this article, we learnt the concept of run time polymorphism and inheritance. We covered most of the scenarios by doing hands-on lab. We’ll be covering more topics in my upcoming articles. Feel free to write comments or queries. Do like my article and rate if it helped you by any means, that will make me happy. Happy coding.

Read more:

Other Series

My other series of articles:

For more informative articles visit my Blog.

For more technical articles you can reach out to CodeTeddy.

Diving in OOP (Part 2) : Polymorphism and Inheritance (Inheritance)


Introduction

In our first part of the article, we learned about different scenarios of method overloading and did lots of interesting hands on too. My article in the second part of the series will focus solely on inheritance concept in OOP. Let’s define Inheritance using some bullet points:

Roadmap

We still stick to our roadmap that we defined before starting the series for learning OOP:

Note: Each and every code snippet written in this article is tried and tested.

Inheritance in Action

OK. Let’s do some hands on. Create a console application and name it InheritanceAndPolymorphism. Add a class named ClassA and a class named ClassB, with the following code:
ClassA:

class ClassA
{

}

ClassB:

class ClassB
{
public int x = 100;
public void Display1()
{
Console.WriteLine(ClassB Display1″);
}
public void Display2()
{
Console.WriteLine(ClassB Display2″);
}
}

We see classClassA is empty and we added two methods in class ClassB, i.e. Display1 and Display2. We also have a variable declared and defined with a value 100.
Now in the main method of Program.cs, write the following code:

Program.cs

class Program
    {
        static void Main(string[] args)
        {

ClassA a = new ClassA();
a.Display1();
}
}

If we run the code, we immediately result in the compile time error.
 
Error'InheritanceAndPolymorphism.ClassA‘ does not contain a definition for ‘Display1‘ and no extension method ‘Display1‘ accepting a first argument of type ‘InheritanceAndPolymorphism.ClassA‘ could be found (are you missing a using directive or an assembly reference?)
i.e. Too obvious, we don’t have definition of Display1 method in ClassA, nor can we access the same method usingClassA instance because it is not derived from any such class like ClassB that contains Display1 method. The class ClassA does not contain any code or variable defined. An empty class does not throw any error as we are able to instantiate an object that looks like a (instance of ClassA). The error comes about because the class ClassA has no method called Display1. However the class ClassB has a method named Display1. Guess how fun it could be if we are allowed to access all the code of classB from ClassA itself.
Just derive the class ClassA from ClassB using : operator as code shown below:
ClassA:

class ClassA:ClassB
{

}

ClassB:

class ClassB
{
public int x = 100;
public void Display1()
{
Console.WriteLine(ClassB Display1″);
}
public void Display2()
{
Console.WriteLine(ClassB Display2″);
}
}

Program.cs

class Program
    {
        static void Main(string[] args)
        {
            ClassA a = new ClassA();
            a.Display1();
            Console.ReadKey();
        }
    }
And now run the code as it was, we get an output now.

Output

ClassB Display1
i.e. now ClassA can access the inherited public methods of ClassB. The error vanishes and the Display1 inClassB gets invoked. If after the name of a class we specify : ClassB i.e., the name of another class, a lot changes at once. ClassA is now said to have been derived from ClassB. What that means is all the code we wrote in ClassBcan now be accessed and used in ClassA. It is if we actually wrote all the code that is contained in ClassB in ClassA. If we had created an instance that looks like that of ClassB, everything that the instance could do, now an instance ofClassA can also do. But we have not written a line of code in ClassA. We are made to believe that ClassA has one variable x and two functions Display1 and Display2 as ClassB contains these two functions. Therefore, we enter
into the concepts of inheritance where ClassB is the base class, ClassA the derived class.
Let’s take another scenario. Suppose we get into a situation where ClassA also has a method of same name as of inClassB. Let’s define a method Derive1 in ClassA too, so our code for classA becomes:
class ClassA:ClassB
    {
        public void Display1()
        {
            System.Console.WriteLine("ClassA Display1");
        }
    }

ClassB:

class ClassB
{
public int x = 100;
public void Display1()
{
Console.WriteLine(ClassB Display1″);
}
public void Display2()
{
Console.WriteLine(ClassB Display2″);
}
}

Now if we run the application using the following code snippet for Program.cs class:
class Program
    {
        static void Main(string[] args)
        {
            ClassA a = new ClassA();
            a.Display1();
            Console.ReadKey();
        }
    }
The question is what will happen now? What will be the output? Will there be any output or any compilation error. Ok, let’s run it.
We get Output:
ClassA Display1
But did you notice one thing, we also got a warning when we run the code:
 
Warning: ‘InheritanceAndPolymorphism.ClassA.Display1()‘ hides inherited member ‘InheritanceAndPolymorphism.ClassB.Display1()‘. Use the new keyword if hiding was intended.
 
Point to remember: No one can stop a derived class to have a method with the same name already declared in its base class.
So, ClassA undoubtedly can contain Display1 method, that is already defined with the same name in ClassB.
When we invoke a.Display1(), C# first checks whether the class ClassA has a method named Display1. If it does not find it, it checks in the base class. Earlier Display1 method was only available in the base class ClassB and hence got executed. Here, since it is there in ClassA, it gets called from ClassA and not ClassB.
 
Point to remember: Derived classes get a first chance at execution, then the base class.
The reason for this is that the base class may have a number of methods and for various reasons, we may not be satisfied with what they do. We should have the full right to have our copy of the method to be called. In other words, the derived classes methods override the ones defined in the base class.
What happens if we call base class Display1 method too with base keyword in derived class, i.e., by usingbase.Display1(), so our ClassA code will be:
ClassA:

class ClassA:ClassB
{
public void Display1()
{
Console.WriteLine(ClassA Display1″);
base.Display1();
}
}

ClassB:

class ClassB
{
public int x = 100;
public void Display1()
{
Console.WriteLine(ClassB Display1″);
}
public void Display2()
{
Console.WriteLine(ClassB Display2″);
}
}

Program.cs

class Program
    {
        static void Main(string[] args)
        {
            ClassA a = new ClassA();
            a.Display1();
            Console.ReadKey();
        }
    }

Output

ClassA Display1 
ClassB Display1
We see here first our ClassA Display1 method is called and then ClassB Display1 method.
Now if you want the best of both the classes , you may want to call the base classes (ClassBDisplay1 first and then yours or vice versa. To achieve this, C# gives you a free keyword, called