INTERVIEW QUESTIONS


C# Interview Questions for Freshers and experienced....

  • What is sealed class in c#?

    • Generally if we create classes we can inherit the properties of that created class in any class without having any restrictions. In some situation we will get requirement like we don’t want to give permission for the users to derive the classes from it or don’t allow users to inherit the properties from particular class in that situations what we can do? 
      For that purpose we have keyword called “Sealed” in OOPS. When we defined class with keyword “Sealed” then we don’t have a chance to derive that particular class and we don’t have permission to inherit the properties from that particular class.
    • Example to declare class as sealed 

      sealed class Test
      {
      public int Number;
      public string Name;
      }
      If the class declared with an access modifier, the Sealed keyword can appear after or before the public keyword. 
  • What is the difference between array and arraylist in c#?

    • Arrays

      Arrays are strongly typed collection of same datatype and these arrays are fixed length that cannot be changed during runtime. Generally in arrays we will store values with index basis that will start with zero. If we want to access values from arrays we need to pass index values.

      Declaration of Arrays 

      Generally we will declare arrays with fixed length and store values like as shown below


      string[] arr=new string[2];
      arr[0] = "welcome";
      arr[1] = "Aspdotnet-suresh";
      In above code I declared array size 2 that means we can store only 2 string values in array.

      Arraylists
    • Array lists are not strongly type collection. It will store values of different datatypes or same datatype. Array list size will increase or decrease dynamically it can take any size of values from any data type. These Array lists will be accessible with “System.Collections” namespace

      Declaration of Arraylist

      To know how to declare and store values in array lists check below code


      ArrayList strarr = new ArrayList();
      strarr.Add("welcome"); // Add string values
      strarr.Add(10);   // Add integer values
      strarr.Add(10.05); // Add float values
      If you observe above code I haven’t mentioned any size in array list we can add all the required data there is no size limit and we will use add method to bind values to array list.
  • What is using statement in c#?

    • Generally in our applications we will write code like create connection object to handle connectionstring after that open a connection and create command object etc. to interact with database to get data that would be like this 

      SqlConnection con = new SqlConnection(connectionString);
      con.Open();
      SqlCommand cmd = new SqlCommand (commandString, con);
      cmd.ExecuteNonQuery();
      con.Close();
      It’s very easy way to write above code but problem is SqlConnection and SqlCommand objects will create IDISPOSABLE interface that means it could create unmanaged resources in our application to cleanup those objects we need to call Dispose() method at the end of our process otherwise those objects will remain in our application.

      Suppose we use using statement in our applications it will automatically create try / finally blocks for the objects and automatically runs Dispose() method for us no need to create any try/finally block and no need to run any Dispose() method.

      If we use using statement we need to write code will be like this 

      C# Code

      using (SqlConnection con = new SqlConnection(connectionString))
      {
      using (SqlCommand cmd = new SqlCommand (commandString, con))
      {
      con.Open();
      cmd.ExecuteNonQuery();
      }
      }
  • What is the difference between constantand readonly in c#?

    • Const:

            1.    Const can only be initialized at the time of declaration of the field.
            2.    Const values will evaluate at compile time only.
            3.    Const value can’t be changed these will be same at all the time.
            4.    This type of fields are required when one of the field values remains constant throughout the system like Pi will remain same in your Maths Class.

    • Read-only:

           1.    The value will be initialized either declaration time or the constructor of the class allowing you to pass the value at run time.
            2.    Read only values will evaluate at runtime only.
              
      Example

      public class Const_VS_Readonly
      {
      public const int I_CONST_VALUE = 2;
      public readonly int I_RO_VALUE;
      public Const_VS_Readonly()
      {
      I_RO_VALUE = 3;
      }
      }
  • What is the difference between dispose and finalize methods in c#?

    • Dispose() Method

           -  This dispose method will be used to free unmanaged resources like files, database connection etc. 

           -  To clear unmanaged resources we need to write code manually to raise dispose() method. 

           -  This Dispose() method belongs to IDisposable interface.

           -  If we need to implement this method for any custom classes we need to inherit the class from IDisposable interface.

           -  It will not show any effect on performance of website and we can use this method whenever we want to free objects immediately.

      Example


      //Implement Dispose Method.
      public class TestDispose : IDisposable
      {
      private bool disposed = false;

    • /Implement IDisposable.
      public void Dispose()
      {
      Dispose(true);
      }

      protected virtual void Dispose(bool disposing)
      {
      if (!disposed)
      {
      if (disposing)
      {
      // clean unmanged objects
      }
      // clean unmanaged objects).

      disposed = true;
      }
      }
      }

      Finalize() Method

           -  This method also free unmanaged resources like database connections, files etc…

           -  It is automatically raised by garbage collection mechanism whenever the object goes out of scope.

           -  This method belongs to object class.

           -  We need to implement this method whenever we have unmanaged resources in our code and make sure these resources will be freed when garbage collection process done.

           -  It will show effect on performance of website and it will not suitable to free objects immediately.     

      Example


      // Implementing Finalize method
      public class Sample
      {
      //At runtime destructor automatically Converted to Finalize method.
      ~Sample()
      {
      // your clean up code
      }
      }
  • What is the difference between ref and out parameters in c#?

    • Ref Parameter

      If you want to pass a variable as ref parameter you need to initialize it before you pass it as ref parameter to method. Ref keyword will pass parameter as a reference this means when the value of parameter is changed in called method it get reflected in calling method also.

      Declaration of Ref Parameter 

      Generally we will use ref parameters like as shown below


      int i=3; // variable need to be initialized
      Refsample(ref i);
      If you observe above code first we declared variable and initialized with value 3 before it pass a ref parameter to Refsample method

      Example


      class Program
      {
      static void Main() 
      {
      int i; // variable need to be initialized
      i = 3;
      Refsample(ref i);
      Console.WriteLine(i);
      }
      public static void Refsample(ref int val1)
      {
      val1 += 10;
      }
      }
      When we run above code we will get like as shown below
    • Output

      13
      As we discussed if ref parameter value changed in called method that parameter value reflected in calling method also

      Out Parameter

      If you want to pass a variable as out parameter you don’t need to initialize it before you pass it as out parameter to method. Out keyword also will pass parameter as a reference but here out parameter must be initialized in called method before it return value to calling method.

      Declaration of Out Parameter 

      Generally we will use out parameters like as shown below


      int i,j; // No need to initialize variable
      Outsample(out i, out j);
      If you observe above code first we declared variable and we it pass a out parameter to Outsamplemethod without initialize the values to variables

      Example


      class Program
      {
      static void Main()
      {
      int i,j; // No need to initialize variable
      Outsample(out i, out j);
      Console.WriteLine(i);
      Console.WriteLine(j);
      }
      public static int Outsample(out int val1, out int val2)
      {
      val1 = 5;
      val2 = 10;
      return 0;
      }
      }
      If we observe code we implemented as per our discussion like out parameter values must be initialized in called method before it return values to calling method

      When we run above code we will get like as shown below

      Output

      5
      10
  • What is the difference between string and stringbuilder in c#?

    • String

      String is immutable. Immutable means once we create string object we cannot modify. Any operation like insert, replace or append happened to change string simply it will discard the old value and it will create new instance in memory to hold the new value.

      Example


      string str = "hi";
      // create a new string instance instead of changing the old one
      str += "test";
      str += "help";
      String Builder

      String builder is mutable it means once we create string builder object we can perform any operation like insert, replace or append without creating new instance for every time.
    • Example


      StringBuilder sb = new StringBuilder("");
      sb.Append("hi");
      sb.Append("test ");
      string str = sb.ToString();
      Differences 

      String
      StringBuilder
      It’s an immutable
      It’s mutable
      Performance wise string is slow because every time it will create new instance
      Performance wise stringbuilder is high because it will use same instance of object to perform any action
      In string we don’t have append keyword
      In StringBuilder we can use append keyword
      String belongs to System namespace
      Stringbuilder belongs to System.Text namespace
  • What is the difference between throw and throw ex in c#?

    • Throw

      In Throw, the original exception stack trace will be retained. To keep the original stack trace information, the correct syntax is 'throw' without specifying an exception.

      Declaration of throw


      try
      {
      // do some operation that can fail
      }
      catch (Exception ex)
      {
      // do some local cleanup
      throw;
      }

    • Throw ex
    • In Throw ex, the original stack trace information will get override and you will lose the original exception stack trace. I.e. 'throw ex' resets the stack trace.

      Declaration of throw ex


      try
      {
      // do some operation that can fail
      }
      catch (Exception ex)
      {
      // do some local cleanup
      throw ex;
      }
      }
  • What is destructor in c#?

    • To create destructor we need to create method in a class with same name as class preceded with ~ operator.

      Syntax of Destructor


      class SampleA
      {
      public SampleA()
      {
      // Constructor
      }
      ~SampleA()
      {
      // Destructor
      }
      }
    • Example of Destructor
    • In below example I created a class with one constructor and one destructor. An instance of class is created within a main function. As the instance is created within the function, it will be local to the function and its life time will be expired immediately after execution of the function was completed.


      using System;
      namespace ConsoleApplication3
      {
      class SampleA
      {
      // Constructor
      public SampleA()
      {
      Console.WriteLine("An  Instance  Created");
      }
      // Destructor
      ~SampleA()
      {
      Console.WriteLine("An  Instance  Destroyed");
      }
      }

      class Program
      {
      public static void Test()
      {
      SampleA T = new SampleA(); // Created instance of class
      }
      static void Main(string[] args)
      {
      Test();
      GC.Collect();
      Console.ReadLine();
      }
      }
      }
      When we run above program it will show output like as shown below 

      Output


      An instance created
      An instance destroyed
  • What is constructor in c#?

    • Constructor is a special method of a class which will invoke automatically whenever instance or object of class is created. Constructors are responsible for object initialization and memory allocation of its class. If we create any class without constructor, the compiler will automatically create one default constructor for that class. There is always at least one constructor in every class.

      Here you need to remember that a class can have any number of constructors and constructors don’t have any return type, not even void and within a class we can create only one static constructor.

      Generally constructor name should be same as class name. If we want to create constructor in a class we need to create a constructor method name same as class name check below sample method for constructor


      class SampleA
      {
      public SampleA()
      {
      Console.WriteLine("Sample A Test Method");
      }
      }

      Types of Constructors

      Basically constructors are 5 types those are

           1.    Default Constructor
           2.    Parameterized Constructor
           3.    Copy Constructor
           4.    Static Constructor
           5.    Private Constructor

      Default Constructor

      A constructor without having any parameters called default constructor. In this constructor every instance of the class will be initialized without any parameter values like as shown below


      using System;
      namespace ConsoleApplication3
      {
      class Sample
      {
      public string param1, param2;
      public Sample()     // Default Constructor
      {
      param1 = "Welcome";
      param2 = "C# .Net Code";
      }
      }
      class Program
      {
      static void Main(string[] args)
      {
      Sample obj=new Sample();   // Once object of class created automatically constructor will be called
      Console.WriteLine(obj.param1);
      Console.WriteLine(obj.param2);
      Console.ReadLine();
      }
      }
      }
      When we run above program it will show output like as shown below

      Output


      Welcome
      C# .Net Code

      Parameterized Constructors

      A constructor with at least one parameter is called as parameterized constructor. In parameterized constructor we can initialize each instance of the class to different values like as shown below


      using System;
      namespace ConsoleApplication3
      {
      class Sample
      {
      public string param1, param2;
      public Sample(string x, string y)     // Declaring Parameterized constructor with Parameters
      {
      param1 = x;
      param2 = y;
      }
      }
      class Program
      {
      static void Main(string[] args)
      {
      Sample obj=new Sample("Welcome","C# .Net Code");   // Parameterized Constructor Called
      Console.WriteLine(obj.param1 +" to "+ obj.param2);
      Console.ReadLine();
      }
      }
      }
      When we run above program it will show output like as shown below

      Output


      Welcome to C# .Net Code

      Constructor Overloading

      In c# we can overload constructor by creating another constructor with same method name and different parameters like as shown below


      using System;
      namespace ConsoleApplication3
      {
      class Sample
      {
      public string param1, param2;

      public Sample()     // Default Constructor
      {
      param1 = "Hi";
      param2 = "I am Default Constructor";
      }
      public Sample(string x, string y)     // Declaring Parameterized constructor with Parameters
      {
      param1 = x;
      param2 = y;
      }
      }
      class Program
      {
      static void Main(string[] args)
      {
      Sample obj = new Sample();   // Default Constructor will Called
      Sample obj1=new Sample("Welcome","C# .Net Code");   // Parameterized Constructor will Called
      Console.WriteLine(obj.param1 + ", "+obj.param2);
      Console.WriteLine(obj1.param1 +" to " + obj1.param2);
      Console.ReadLine();
      }
      }
      When we run above program it will show output like as shown below


      Output


      Hi, I am Default Constructor
      Welcome to C# .Net Code

      Copy Constructor

      A parameterized constructor that contains a parameter of same class type is called as copy constructor. Main purpose of copy constructor is to initialize new instance to the values of an existing instance. Check below example for this


      using System;
      namespace ConsoleApplication3
      {
      class Sample
      {
      public string param1, param2;
      public Sample(string x, string y)
      {
      param1 = x;
      param2 = y;
      }
      public Sample(Sample obj)     // Copy Constructor
      {
      param1 = obj.param1;
      param2 = obj.param2;
      }
      }
      class Program
      {
      static void Main(string[] args)
      {
      Sample obj = new Sample("Welcome", "C# .Net Code");  // Create instance to class Sample
      Sample obj1=new Sample(obj); // Here obj details will copied to obj1
      Console.WriteLine(obj1.param1 +" to " + obj1.param2);
      Console.ReadLine();
      }
      }
      }
      When we run above program it will show output like as shown below

      Output


      Welcome to C# .Net Code

      Static Constructor

      When we declared constructor as static it will be invoked only once for any number of instances of the class and it’s during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.


      using System;
      namespace ConsoleApplication3
      {
      class Sample
      {
      public string param1, param2;
      static Sample()
      {
      Console.WriteLine("Static Constructor");
      }
      public Sample()
      {
      param1 = "Sample";
      param2 = "Instance Constructor";
      }
      }
      class Program
      {
      static void Main(string[] args)
      {
      // Here Both Static and instance constructors are invoked for first instance
      Sample obj=new Sample();
      Console.WriteLine(obj.param1 + " " + obj.param2);
      // Here only instance constructor will be invoked
      Sample obj1 = new Sample();
      Console.WriteLine(obj1.param1 +" " + obj1.param2);
      Console.ReadLine();
      }
      }
      }
      When we run above program we will get output like as shown below

      Output


      Static Constructor
      Sample Instance Constructor
      Sample Instance Constructor
      Importance points of static constructor

      -      Static constructor will not accept any parameters because it is automatically called by CLR.
      -      Static constructor will not have any access modifiers.
      -      Static constructor will execute automatically whenever we create first instance of class
      -      Only one static constructor will allowed.

      Private Constructor

      Private constructor is a special instance constructor used in a class that contains static member only. If a class has one or more private constructor and no public constructor then other classes is not allowed to create instance of this class this mean we can neither create the object of the class nor it can be inherit by other class. The main purpose of creating private constructor is used to restrict the class from being instantiated when it contains every member as static.


      using System;
      namespace ConsoleApplication3
      {
      public class Sample
      {
      public string param1, param2;
      public Sample(string a,string b)
      {
      param1 = a;
      param2 = b;
      }
      private Sample()  // Private Constructor Declaration
      {
      Console.WriteLine("Private Constructor with no prameters");
      }
      }
      class Program
      {
      static void Main(string[] args)
      {
      // Here we don't have chance to create instace for private constructor
      Sample obj = new Sample("Welcome","to C# .Net Code");
      Console.WriteLine(obj.param1 +" " + obj.param2);
      Console.ReadLine();
      }
      }
      }

      Output


      Welcome to C# .Net Code

      In above method we can create object of class with parameters will work fine. If create object of class without parameters it will not allow us create.


      // it will works fine
      Sample obj = new Sample("Welcome","to C# .Net Code");
      // it will not work because of inaccessability
      Sample obj=new Sample();
      Important points of private constructor

      -      One use of private construct is when we have only static member.
      -      Once we provide a constructor that is either private or public or any, the compiler will not allow us to add public constructor without parameters to the class.
      -      If we want to create object of class even if we have private constructors then we need to have public constructor along with private constructor.
  • What is the difference between array and arraylist in c#?

  • What is the difference between array and arraylist in c#?

  • What is the difference between array and arraylist in c#?

  • What is the difference between array and arraylist in c#?

  • What is the difference between array and arraylist in c#?

  • What is the difference between array and arraylist in c#?

  • What is the difference between array and arraylist in c#?

No comments:

Post a Comment

Join US Our Community
×