Advance C# Question


can we create derived class object from base class c#

Answer: No.

In general, When we create object of a class, its reference is stored in stack memory and object is stored in heap and address of object is assigned to class reference.

For example child is the class and Child objch=new child(); is the object then

Child objch is child class reference created on stack memory.

new child(); create object of Child on Heap memory and address ofit is assigned to objch referenece.

class Child
    {
        public Child()
        {
            Console.WriteLine("Child class Constructor");
        }
        
    }

Example program for creating a derived object from base class.

class Program
    {
        static void Main(string[] args)
        {
            Child objC = new Child();
        }
    }
    class Parent
    {
        Child objCh = new Child();
        public Parent()
        {
            Console.WriteLine("Parent Class Constructor");
        }
    }
    class Child:Parent
    {
        public Child()
        {
            Console.WriteLine("Child class Constructor");
        }
        //Parent objP = new Parent();
    }

Output

Process is terminated due to StackOverflowException.

In the above example,

creates an object of child class(derived class) from parent class(base class) then first parent (base) class constructor and then (child class )derived class constructor get called implicitly.

This constructor calling from base class to derived class and derived to base class repeats until stack memory is full.

After reaching stack memory limit, it terminates the process and raise the stack overflow exception

base–>derived–>base–>derived—> …until stack is full.

What is Use of Private Constructor in C# ? Scenarios Example

Private Constructor in C#?

Private constructor is constructor that is preceded by private access specifier. For example, below class has a private constructor.

We know that if we don’t write constructor in the class then by default constructor gets called on object creation which is public. Or if we want to allow object creation of the class then we write public constructor or else we explicitly specify private access specifier on class constructor.

Can we create object of class with private constructor in C#?

No, object of a class having private constructor cannot be instantiated from outside of the class. However, we can create object of the class inside class methods itself.

class A
{
    //private constructor
    private A()
    {
    }
}

class Program
{
    static void Main(string[] args)
    {
        A obj = new A();//Error cannot access private constructor
    }
}

Use of private constructor in C# Sharp Programming:

Following are the scenarios when we can make use of private constructor in C# code.

1)Stop object creation of a class

If we want to stop object creation of a class, then we can make the class constructor private. So, if we try to create an object from the main program or other classes, then compiler will flash an error.

NOTE:

i)To stop object creation of a class completely, you need to make all the overloaded constructors private.

ii)There may be a chance that you need to stop an specific type of object creation. You can do so by making specific constructor private.

For example, you don’t want to allow anyone to create an object of a class with an empty constrictor but all other overloaded constructors. Then, you can make the empty constructor private and rest of the constructors public as shown in below code example.

class A {
    //private constructor
    private A() {
    }

    public A(int a)
    {       
    }
    public A(int a, int b)
    {
    }
}

class Program
{
    static void Main(string[] args)
    {
       // A obj1 = new A();//Error 

        A obj2 = new A(5);// OK

        A obj3 = new A(5, 10);//OK
    }
}

2)Use in Singleton class

We know that singleton class allows only single instance of it throughout the execution of the application. When we design a singleton class, we use private constructor, so, no user can create object of this class to stop multiple object creation. And singleton class itself provide the same object over and over on demand.

You may like reading what is singleton class and how to design a thread safe singleton class in C# software projects.

3)Stop a class to be inherited

If we don’t want a class to be inherited, then we make the class constructor private. So, if we try to derive another class from this class then compiler will flash an error. Why compiler will flash an error? We know the order of execution of constructor in inheritance that when we create an object of a derived class then first constructor of the base call will be called then constructor of derived class. Since, base class constructor is private, hence, derived class will fail to access base class constructor.

In below c sharp code example, compiler flashes error on creation of object of derived class or as soon as you write constructor of derived class.

//base
class B
{
    private B()
    {
    }
}
//Derived
class D : B
{
    public D()
    {
    }
    
}

class Program
{
    static void Main(string[] args)
    {
       D obj = new D();//error
    }
}

How to Create Custom Exception in C# .net program? Use of it?

Custom Exception Class

Custom Exception class is nothing but a user defined class which is derived from System Exception class. Here are steps

  • Derive a Custom class from System Exception class.
  • Create a constructor of custom class with error message parameter and pass it to the base class (System Exception class).
  • Throw and catch custom exception message in try catch block in C# wherever is required.
//custom exception class or user defined Exception class.
    class UnwantedCharException : Exception
    {
        //create custruction and pass a error message to 
        //base class i.e.System exception class
        public UnwantedCharException(String msg) : base(msg) { }
    }

Complete C# Program for Custom Exception

Let’s understand the concept with simple example. Below program will accept a string from user and if the string is alphanumeric, program will be processed or else it will throw a custom exception that “Only Alphanumeric string is allowed”

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace CustomException
{
    //custom exception class or user defined Exception class.
    class UnwantedCharException : Exception
    {
        //create custruction and pass a error message to 
        //base class i.e.System exception class
        public UnwantedCharException(String msg) : base(msg) { }
    }

    //Test Program
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string s = GetInputString();

                //process further if no exception.
                Console.WriteLine(s);

            }
            catch (UnwantedCharException ex)
            {
                //Get custom exception
                Console.WriteLine(ex.Message);

            }

        }

        static string GetInputString()
        {
            string s = Console.ReadLine();
            //User String is not alphnumeric, throw Exception.
            if (!IsAlphaNumeric(s))
            {
                throw new UnwantedCharException("Only Alphanumeric string is allowed");
            }

            return s;
        }
        public static bool IsAlphaNumeric(String strToCheck)
        {
            Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9]");
            return !objAlphaNumericPattern.IsMatch(strToCheck);
        }
    }


}

NOTE:

This custom exception handling in C# interview question can also be asked as how to create user defined exception in C# or why we use custom exception or why do we need it in C# project or how to throw or handle custom run time exception message etc.

Why do we need Custom Exception in C# applications?

There are tons of exceptions available in C# .net framework e.g. FileFormatException, FileNotFoundException and DriveNotFoundException etc. However, sometime we need to write our own custom exception class in an application. For example, let’s say during database processing, error code is thrown for resource is busy or table is full etc.  and since, error code may not be understandable to customer, so we may want to throw meaning full run time exception, so, customer or end user can understand it.

Advantage of Immutable String in C# programming

Here is the scenario,

  • The main() method has a String msg = “Hello World”; and will call the display1() method and then the display2() method.
  • The display1() method will read the string and modify the string to “My World”.
  • The display2() method must read the original “Hello World” string, and not the string modified by display1() method.

Since, C# string is immutable, that is it cannot be modified, hence, the string modified by the display1() method will not be reflected in main() function. And display2() method will read the original string.

Hence, original data is safe!!!

So, conclusion is that, if we pass a string to some method  to read and use only, the method will not be able to modify the original string, because of its immutability. Even though string is changed in the method body. So,if original string is used somewhere in the program that will get expected string value.

C# Program Example – advantage of immutable string

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


    class Program
    {
        static void Main(string[] args)
        {
            String msg = "Hello World";

            //Display1 method will read the string and modify it
            Display1(msg);

            //From here below program will read original
            //string i.e. "Hello World". as string is immutable
            //and cannot be changed by Display1 method.

            Console.WriteLine(msg);//print original string.
  
            //Display2 method will also read original string.
            Display2(msg);

        }

        //Since String is a reference type y will
        //point to the same location where msg is
        //pointing to
        
        //Note that value of string msg is not copied
        //But reference of msg string as String data
        //Type is reference type.
        public static void Display1(String y)
        {
            //It will print the original string
            //Y is having the same reference as msg variable.
            Console.WriteLine(y);
            //but If we try to change the  value of y 
            //it will create another memory and assign "My World"
            //string and it will not modify the memory msg variable
            //is pointing to in Main program.
            y = "My World";
            Console.WriteLine(y);
        }

        //Since String is a reference type y will
        //point to the same location where x is
        //pointing to
        private static void Display2(String y)
        {
            Console.WriteLine(y);
        }       

    }

OUTPUT:

Hello World
My World
Hello World
Hello World

What is method hiding in C# inheritance? Uses with example

Answer: Method hiding occurs in inheritance relationship when base class and derived class both have a method with same name. When we create the object of derived class it will hide the base class method and will call its own method and this is called method hiding or name hiding in C# inheritance.

We use “new” keyword in derived function name to show that implementation of the function in derived class is intentional and derived class no longer want to use base class method.

NOTE: If we do not use “new” keyword then compiler will raise only warning, but, program will work fine.

In below C# program, Base and Derived class both have show() method implementation. On calling show() on derived object will hide the base class show method and call derived class method.

class Base{
    public void show()
    {
        Console.WriteLine("Base...");
    }
}
class Derived : Base
{
    new public void show()
    {
        Console.WriteLine("Derived...");
    }
}
class Program
{
   static void Main(string[] args)
    {

        Derived d = new Derived();
        d.show();        
    }
    
}

Output: Derived…

When to use method hiding in C#?

When to use method hiding in C# program is really an important concept that we need to understand. Does child class, no longer want to use some of the methods implementation of parent class, but, want to implement it for its own? Use C# method hiding also called name hiding feature then. Note that we cannot override the method as it’s not virtual in base class.

When to use method hiding in C#?

When to use method hiding in C# program is really an important concept that we need to understand. Does child class, no longer want to use some of the methods implementation of parent class, but, want to implement it for its own? Use C# method hiding also called name hiding feature then. Note that we cannot override the method as it’s not virtual in base class.

Recommended to read C# method overriding with example.

Let’s understand it by example

In below program, “ApplicationSoftware” (Child) class wants to inherit all operations i.e. update () and install () methods of “Software” (Parent) class. And, ApplicationSoftware class will have one operation i.e. run() method like below program example.

class Software
{
    public void update()
    {
        Console.WriteLine("Base Updating...");
    }
    public void install()
    {
        Console.WriteLine("Base Installing...");
    }
}
class ApplicationSoftware : Software
{
    public void run()
    {
        Console.WriteLine("Child Running...");
    }
}

class Program
{
    static void Main(string[] args)
    {        
        ApplicationSoftware appsoft = new ApplicationSoftware();
        appsoft.update();
        appsoft.install();
        appsoft.run();
    }

}

Output:

Base Updating…
Base Installing…
Child Running…

At some later pointer of time, if child class ApplicationSoftware wants to implements it own behavior for install() method of base class, it will use name hiding feature without disturbing the base class Software.

Note that,We should not delete base class method implementation to avoid method hiding in software projects, as there are chances that base class is being used by some other classes in a complex software project.

class ApplicationSoftware : Software
{
    public void run()
    {
        Console.WriteLine("Child Running...");
    }
    //implement method that will hide the base class method
    new public void install()
    {
        Console.WriteLine("Child Installing...");
    }
}

Here is the output for updated child class.

Output:

Base Updating…
Child Installing…
Child Running…

Conclusion:

Use method hiding in C#

  • If child class want to implement some of methods of base class without disturbing base class.
  • If base class is available in a library that cannot be changed even if we want to do so intentionally. Use name hiding in C# then.

NOTE: If somehow, it is possible to change base class and it will not affect a program a lot, we can make the method virtual and override in derived class.

How to implement two interface with same method in C#?

Answer: If we have two interface with same method name then a class need to implement interface explicitly in a program.

/Interfaces ILoanCustomer & IBankCustomer
//have same method name. That will be implemented
//Explicitely in Customer class
interface ILoanCustomer
{
    void GetCostomerInfo();
}
interface IBankCustomer
{
   void GetCostomerInfo();    
}


class Customer : ILoanCustomer, IBankCustomer
{
    //Explicit implementation of ILoanCustomer interface
    void ILoanCustomer.GetCostomerInfo()
    {
        Console.WriteLine("Loan Customer ...");
        
    }
    //Explicit IBankCustomer of ILoanCustomer interface
    void IBankCustomer.GetCostomerInfo()
    {
        Console.WriteLine("Bank Customer ...");
       
    }
}

//Test
class Program
{
    static void Main(string[] args)
    {
        IBankCustomer bc = new Customer();
        bc.GetCostomerInfo();

        ILoanCustomer lc = new Customer();
        lc.GetCostomerInfo();       
       
    }
}

NOTE:

When a method is explicitly implemented in a class in C#, it cannot be accessed through a class instance if you use class reference, but only through an interface reference pointing to the class instance. For example,

Using interface reference pointing to the Customer class object, class method is accessible.

IBankCustomer bc = new Customer();

bc.GetCostomerInfo();

Using the class reference pointing to the class object, you can’t access the method e.g.

Customer c = new Customer();

c.GetCostomerInfo();