Showing posts with label interview question abstract class in c#. Show all posts
Showing posts with label interview question abstract class in c#. Show all posts

Friday, February 26, 2016

In which SCENARIOS we use Abstract Class

For many  people  including me , It is very difficult to answer when to use "Abstract Class" , I had already tried  to find the answer for this from many sites.

Here I share my experiences with this question,  and I am sure you will definitely  be able to answer this question after reading this article.

 "Abstract Class"

Here I explain in which "SCENARIOS" you can use "Abstract Class"  Lets take an example from our Microsoft core library

Suppose I have a class "SqlConnection "  and when you go to its meta definition

    public sealed class SqlConnection : DbConnection, ICloneable
    {
        // Summary:
        //     Initializes a new instance of the System.Data.SqlClient.SqlConnection class.
        public SqlConnection();
        //
        // Summary:
        //     Initializes a new instance of the System.Data.SqlClient.SqlConnection class
        //     when given a string that contains the connection string.
        //
        // Parameters:
        //   connectionString:
        //     The connection used to open the SQL Server database.
        public SqlConnection(string connectionString);
 
        // Summary:
        //     Gets or sets the string used to open a SQL Server database.
        //
        // Returns:
        //     The connection string that includes the source database name, and other parameters
        //     needed to establish the initial connection. The default value is an empty
        //     string.
        //
        // Exceptions:
        //   System.ArgumentException:
        //     An invalid connection string argument has been supplied, or a required connection
        //     string argument has not been supplied.
        [Editor("Microsoft.VSDesigner.Data.SQL.Design.SqlConnectionStringEditor, Microsoft.VSDesigner, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Drawing.Design.UITypeEditor, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")]
        [RefreshProperties(RefreshProperties.All)]
        [ResCategory("DataCategory_Data")]
        [DefaultValue("")]
        [ResDescription("SqlConnection_ConnectionString")]
        [RecommendedAsConfigurable(true)]
        [SettingsBindable(true)]
        public override string ConnectionString { get; set; }
//many more things............................................
}

Here this "SqlConnection" class  inherited one abstract class name "DbConnection" class  lets see what this abstract class contain
 
public abstract class DbConnection : Component, IDbConnection, IDisposable
    {
        // Summary:
        //     Initializes a new instance of the System.Data.Common.DbConnection class.
        protected DbConnection();
 
        // Summary:
        //     Gets or sets the string used to open the connection.
        //
        // Returns:
        //     The connection string used to establish the initial connection. The exact
        //     contents of the connection string depend on the specific data source for
        //     this connection. The default value is an empty string.
        [RefreshProperties(RefreshProperties.All)]
        [ResCategory("DataCategory_Data")]
        [DefaultValue("")]
        [SettingsBindable(true)]
        [RecommendedAsConfigurable(true)]
        public abstract string ConnectionString { get; set; }
        //
        // Summary:
        //     Gets the time to wait while establishing a connection before terminating
        //     the attempt and generating an error.
        //
        // Returns:
        //     The time (in seconds) to wait for a connection to open. The default value
        //     is determined by the specific type of connection that you are using.
        [ResCategory("DataCategory_Data")]
        public virtual int ConnectionTimeout { get; }
        //
        // Summary:
        //     Gets the name of the current database after a connection is opened, or the
        //     database name specified in the connection string before the connection is
        //     opened.
        //
        // Returns:
        //     The name of the current database or the name of the database to be used after
        //     a connection is opened. The default value is an empty string.
        [ResCategory("DataCategory_Data")]
        public abstract string Database { get; }
        //
        // Summary:
        //     Gets the name of the database server to which to connect.
        //
        // Returns:
        //     The name of the database server to which to connect. The default value is
        //     an empty string.
        [ResCategory("DataCategory_Data")]
        public abstract string DataSource { get; }
//and many more things..................................................................................
 }

In this abstract class you can see a property " public abstract string ConnectionString { get; set; }" is declared, and it is override by "public override string ConnectionString { get; set; }"SqlConnection " class.   when we inherited "DbConnection "   abstract class it is necessary to implement abstract string "ConnectionString ". The point is clear when ever you use this class a wide range all the inhered class must implemented this property.

Now , My intension is here to show you Microsoft working style of abstract class. Lets talk about it in simple term.
  •  When you have a requirement where your base class should provide default implementation of certain methods whereas other methods should be open to being overridden by child classes use abstract classes.
     
  • The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share.
     
  • If you are thinking about multiple version of your component then create abstract class. Abstract classes provide a simple and easy way to version your component. By updating base class, all the inheriting classes are automatically updated.
Questions related to Abstract Class

Question 1 What is an Abstract Class?
Answer:  According to Code Project "Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to make classes that only represent base classes, and don’t want anyone to create objects of these class types. You can make use of abstract classes to implement such functionality in C# using the modifier 'abstract'."

Question 2  Does Abstract class have constructor in c#
Answer:  Yes

Question 3  Then, why we do not create object of Abstract Class?
Answer:  When you want to instantiate data in the abstract class. One important reason is due to the fact there's an implicit call to the base constructor prior to the derived constructor execution. Keep in mind that unlike interfaces, abstract classes do contain implementation. That implementation may require field initialization or other instance members. Note the following example and the output:

Souce:stackoverflow

    abstract class Animal
    {
        public string DefaultMessage { get; set; }
 
        public Animal()
        {
            Console.WriteLine("Animal constructor called");
            DefaultMessage = "Default Speak";
        }
        public virtual void Speak()
        {
            Console.WriteLine(DefaultMessage);
        }
    }
 
    class Dog : Animal
    {
        public Dog()
            : base()//base() redundant.  There's an implicit call to base here.
        {
            Console.WriteLine("Dog constructor called");
        }
        public override void Speak()
        {
            Console.WriteLine("Custom Speak");//append new behavior
            base.Speak();//Re-use base behavior too
        }
    }

Although we cannot directly construct an Animal with new, the constructor is implicitly called when we construct a Dog.

OUTPUT:

Animal constructor called
Dog constructor called
Custom Speak
Default Speak


Question 4  It is necessary abstract classes have all the methods abstract?
Answer:  No. An abstract class can have concrete methods too.

Question 5  If c# allow to declare all method abstract then why we use Interface?
Answer:  Answer this question in single line,  Class can implement several interfaces but only one abstract class and you may required  a class inherited server classes  (means abstract "class+Interface") in real word   scenarios. ( as you see above code of Microsoft  "SqlConnection" class.

Question 6  In c#, Can we work with normal classes as Abstract Class do?
Answer: Abstract class is deigned to create non abstract and abstract fields method and properties , which can share by more than one classes , and can be override by its inherited classes and if we create a non abstract class then we will create the object of that class. So a class is incomplete, we didn't allow to create the object of that class.

Question 7  Can we use a sealed keyword with an abstract class?
Answer: No. Sealed classes cannot be inherited while an abstract class is meant to be inherited.