Top C# Technical Questions

Collated by:            Muthukumar S
Last Updated On: 26 March 2019


Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/


    Types
  • What is Value Type and Reference type?  (Beginner)

  • A value type stores its value within its own memory allocation (at stack). The following types are value types: 
    • all primitive types like int, float, date, char, bool etc
    • enum 
    • struct 
  • A reference type stores a reference/ pointer to another memory location (in heap) that holds the data. The following types are reference types: 
    • string
    • array
    • class 
    • delegate
    • object
  • What is immutable type?  (Beginner)
            Immutable types are the types that once initialized through the constructor cannot change their internal state. For example, DateTime and String types which are part of .Net framework are immutable types. 
  • What are the advantages and disadvantages of immutable type?  (Beginner)
  •   Advantages: 
    •  Since immutable types cannot be changed, it cannot be altered by the developers accidentally which would not lead to undesirable effects.
    •  Since immutable types cannot be changed, it is thread safe. They can’t be changed by another thread, which makes them safe to be shared.
  • Disadvantages:
    • The main drawback of immutable type is bad performance. The overhead generated by creating new objects would have an impact on the application performance.
  • What is nullable type? (Beginner)
         A Nullable type allows the developer to assign null value to the value types.

        For example:
                 Nullable<int> length;
            int breadth;
            length = 100; breadth = 200;
            length = null;      // valid since length is nullable type.
     breadth = null;     // compilation error since breadth is value type.

          The nullable type can also be declared as follows:
            int? length;        // int? is shorthand of Nullable<int>

  • What is anonymous Types (Beginner)
              Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type does not have a name in the source code but the name is created implicitly by the compiler.
        They make use of  implicitly typed variable declaration, the new operator and object initialization syntax for creating the objects as follows:

var passport = new { Number = "PRT10201", IssuedAt = "Chennai" };
System.Console.WriteLine("Passport number, {passport.Number} issued at {passport.IssuedAt}");
           
               Here, an anonymous type (which don't have name) is created with the two properties (Number and IssuedAt) and an instance of it is created by the name 'passport' with the property values, "PRT10201" and "Chennai".
  • The anonymous type does not have a name to be referred in the source code.
  • The anonymous type is a reference type.
  • The anonymous types contain one or more public read-only properties. 
  • The anonymous type cannot have methods or events
  • The scope of an anonymous type is local to the method where it is defined.
  • The base class of anonymous type is object.
  • The anonymous type  cannot be cast to any other type except object. 
  • The anonymous types are widely used in the select clause of a query expression to return a subset of the properties from each object in the source sequence.
  • The value that is used to initialize a property in anonymous type cannot be null
  • A method cannot take an anonymous type as formal parameter or can return an anonymous type.
  • What is Implicitly typed local variables (Beginner)
          An Implicitly typed local variable is a variable which is declared without any type specified explicitly but the type is inferred by the compiler automatically based on the type of value assigned to it. The implicitly type local variables are declared using var keyword as follows:

                     var firstName = "John";      // firstName is declared as string
            var age = 25;             // age is declared as integer
            var interestRate = 15.5;     // interestRate is declared as double
            var sizes = new[] { 1, 7, 5, 2 }; // sizes is declared as int array
            var programmer = new Employee(); // programmer is declared as Employee object
   
  • The var variables can be declared only as local variables. Fields of a class cannot be declared using var.
  • The var variables should have value assigned to it in the same statement where it is declared.
  • The null value cannot be assigned to var variable at the time of declaration.
  • What is a tuple?  (Beginner)
          A Tuple is a data structure, which consists of an ordered, heterogeneous collection of elements. The elements in a tuple can either be of the same type or even can be of different types.

  • What is Dynamic datatype? (Beginner)
            The dynamic data type helps to hold values of any datatype or class and can be used to invoke the methods associated with class without any compile time checking.
              For example:
                 dynamic dyn = new Employee();
            dyn.FindById(120);
            dyn = new BankAccount(700);
            double balance = dyn.GetBalance();

               In the above example, the dynamic variable dyn points to Employee object first and points to BankAccount object later.
               The methods FindById and GetBalance are bound to the dyn object at runtime instead of compilation type. As a result the compiler ignores the type checking against the dyn object.


  • How to initialize a variable to default value based on its type?
              The default literal expression can be assigned to a variable to initialize it with the default value based on its type.
             For example:
                   int a = default;   // initializes the variable with 0
           bool b = default// initializes the variable with false
           Employee c = default;   // initializes the variable with null
           T d = default;   // initializes the generic variable as per its type (int, bool or Reference type)

  • What is ValueTuple?
          A ValueTuple is the value type representation of Tuple. It can be created and initialized using parentheses () and specifying the values between them.

          For example:

(string Number, string IssuedAt, bool IsValid) passport = ("AGX1020", "Chennai", true);

           Here we have created a tuple called passport which consists of the elements, Number, IssuedAt and IsValid.

             The individual elements in the tuple can be accessed as below:

                     Console.WriteLine(passport.Number);             // Displays AGX1020
            Console.WriteLine(passport.IssuedAt);           // Displays Chennai
            Console.WriteLine(passport.IsValid.ToString()); // Displays true

The tuple in the above example also be created using any of the below syntax:

             1. var passport = (Number: "AGX1020", IssuedAt: "Chennai", IsValid: true);
         2. var passport = ("AGX1020", "Chennai", true);
         3. ValueTuple<string, string, bool> passport = ("AGX1020", "Chennai", true);
  4. (string, string, bool) passport = ("AGX1020", "Chennai", true);

When the syntax that does not have element name is used (#2, 3 and 4 in the above examples), the individual element can be referred as:

Console.WriteLine(passport.Item1);       // Displays AGX1020
       Console.WriteLine(passport.Item2);       // Displays Chennai
       Console.WriteLine(passport.Item3);      // Displays true

    Literals and Expressions
  • What is the purpose of ?? operator in C#?  (Beginner)
                The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.     
               For example, the following code displays the value of passportNumber if it is not null. It shows the string, 'Not Specified' if it is null:

             Console.WriteLine(passportNumber ?? "Not Specified");
     
  • What is Null-conditional operators?  (Beginner)
              The null conditional operator provides concise syntax for null checks.
For example, the following code assigns PassportNumber only if employee object is not null. It assigns null, otherwise:

              string passportNmber = employee?.PassportNumber;

  • What is String Interpolation?  (Beginner)
             The string interpolation is used to embed the expressions within the strings. The expressions are embedded using pair of curly braces {}. Also, the string is prefixed with $ as below:

              string fullName = $"{Name} {Surname}";

         The above line makes the runtime to substitute the value of  the variables, 'Name' and 'SurName' in the respective expression placeholders and assign it to the variable, 'fullName'.

          Even the expression can be a method as below:

       Console.WriteLine($"The Total Insurance amount is {policy.CalculateInsurance()}");

  • What is Verbatim string? (Beginner)
              The Verbatim string is used to represent a long string with line breaks in C# code. It also used to ignore the escape sequences in the string. A string literal should be prefixed with '@' character to make it a verbatim string.
              For example:
           
        longString =  "This is a long string
                       spans to multiple lines

                       in the code";            // Compiler throws error

        longString = @"This is a verbatim string
                      spans to multiple lines

                     in the code without any compilation error."//  compiles successfully

          string filePath;
      filePath = "C:\Test\Sample.txt"; // throws error as \T and \S are treated as escape sequences.
      filePath = "C:\\Test\\Sample.txt"// Compiles successfully as \\ escape sequence is used.
      filePath = @"C:\Test\Sample.txt"// Compiles as it is verbatim string that ignore escape sequences

  • What is lambda expression ? (Advanced)
         A lambda expression is a code block (an expression or a statement block) that can be passed as parameter to methods or can be returned from the methods.
         A lambda expression consists of a lambda declaration operator,  =>. It separates the lambda's parameter list and the executable code. In order to create a lambda expression, we specify input parameters,  if any, on the left side of the lambda operator, and we put the expression or statement block on the right side.

        For example:
                 Func<int, int, int> area = ( l, b) => l * b;
                 System.Write( area(2, 5) ); // Writes the area as 10

      In the above example, (l,b) are the lambda parameters and l * b is the executable code. The lambda expression is assigned to a delegate that takes two integer parameters  and return an integer value.

       The Lambda expressions are code that can be represented either as a delegate, or as an expression tree that compiles to a delegate.

        The lambda expressions are used extensively in LINQ as below:

              IEnumerable<string> query = cities.Where(city => city.Length < 6)
                                                      .Select((city, index) =>
                                                         new { city, city.Length } ) );

In the above query, where and Select method takes lambda expression as a parameter.

  • What is the difference between directing casting and  'as' operator ? (Beginner)
               The direct casting will throw InvalidCastException in case if the casting fails whereas 'as' operator never throws any exception if the casting fails. Instead it returns null. So, it is necessary to perform null check before using the converted object.

               For example:
                        long lngVar = 100;
                        int intVar  = (int) lngVar;     // No exception as 100 can be stored in int variable.

                        lngVar = 1000000000000000;
                        intVar = (int) lngVar;           // throws InvalidCastException as the number cannot be stored with int variable as it is very large.

                        IEnumerable<Employee> enumerObj = new List();
                        List<Employee) lstObj = enumerObj as List;
                   
                       if (lstObj != null) {
                                   lstObj.Add(new Employee());
                       }

               The direct casting can be used both for value types and reference types whereas 'as' operator can be used to convert only the reference types.

                       long lngVar = 100;
                       int intVar = lngVar as int;  // throws compilation error

  • What is purpose of 'is' operator ? (Beginner)
                The 'is' operator is used to compare an object with the given type and returns true if
  • If an object is an instance of the given class
  • If an object is an instance of the child class derived from the given base class
  • If an object is an instance of a class which implements the given interface.
For example:

                public class Employee : IEmployee {}
                public class ContractEmployee : Employee {}

                object e1 = new ContractEmployee();
                object e2 = "This is a string";

             if( e1 is ContractEmployee)      // evaluates to true
             {
                     // yes, e1 is ContractEmployee
              }



             if( e1 is Employee)      // evaluates to true
             {
                     // yes, e1 is Employee because ContractEmployee is child class of Employee
              }

              
             if( e2 is Employee)      // evaluates to false
             {
                 
              }
              else
              {
                          // No , e2 is Not Employee because e2 is a string
               }


  • What is nameof operator ? (Beginner)
               The nameof operator is used to get the name of variable, class or a property as the string constant.
               For example:
                      public float InterestRate
                      {
                             set
                             {
                                       if(value <= 0)
                                       {
                                             throw new Exception($"{nameof(InterestRate)} cannot be zero or negative");
                                        }
                                        _interestRate = value
                              }

                      }
           The usage of nameof(InterestRate) is better than hard-wiring value, "InterestRate" as below:
                              throw new Exception("InterestRate cannot be zero or negative");

           In case, the InterestRate property is renamed to something else in the future, developer might miss to change the hard-wired value, but he cannot miss the nameof operator as it would throw compilation error.


  • How to represent binary and hexadecimal literals in C# ? (Beginner)
          The binary literals are prefixed with 0b and hexadecimal literals are prefixed with 0x.

          For example:

            int hexaLiteral = 0x3F;
            int binaryLiteral = 0b10100001;


  • How to improve the readability of literals with more number of digits in C# ? (Beginner)
       The digits in the literals (decimal, hexadecimal or binary) can be separated by underscore character (_) to improve the readability. The underscore character is usually provided as thousand separators in decimal literals.

            For example:

            int decimalLiteral = 1_402_120;   // same as 1402120
            int binaryLiteral = 0b1010_0001; // same as 0b10100001

  • What is short circuiting logical operators ? (Advanced)
       The logical operators || (OR) and && (AND) are short circuiting logical operators because
  • If the left side expression of || is evaluated to true, the right side expression of the operator is never evaluated. This is due to the reason that if one of the expression is true, the whole logical OR expression results in true.
  • If the left side expression of && is evaluated to false, the right side expression of the operator is never evaluated. This is due to the reason that if one of the expression is false, the whole logical AND expression results in false.

      For example:

            if( isEligible() || isInActive() ) // the method, isInActive is not called if isEligible() returns true. The whole expression becomes true.

           if(isMale() && isKid() ) // the method, isKid() is not called if isMale() returns false. The whole expression becomes false.

  • What is discard? (Beginner)
       A discard is a write-only variable whose name is _ (the underscore character). All the values which are intended to be discard can be assigned to discard variable. The discard variable can't be used in the code other than in the assignment statement.
The discard can be be used when discarding the some of the values while deconstructing tuples. Also, the discard can be used when we want to discard an output parameter while calling the method.

For example:
  public class Maths
{
private void FindSumAndAverage(int []elements, out int sum, out int average)
{
foreach(int element in elements)
{
sum += element;
}
average = sum/ elements.length;
}
public void Find()
{
int [] elements1 = {4,1,7, 9};
int [] elements2 = {3,8,2, 5};
int [] elements3 = {2,1,6};

FindSumAndAverage(elements1, out int sum, out int avg); // Gets both sum and average as the output
FindSumAndAverage(elements1, out _, out int avg); // Gets average but discards sum
FindSumAndAverage(elements1, out int sum, out _); // Gets sum but discards avg
}
}

   In the above example, the unwanted output variable is discarded/ ignored when calling the method. The only required variable (sum or avg) is passed and discarding the other variable.


    Class
  • What is the difference between struct and class?  (Beginner)
  • A class is a reference type whereas struct is a value type.
  • Since class is reference type it can hold null values whereas struct cannot hold null.
  • When access modifier is not mentioned, the property or methods are by default private in class whereas they are public by default in struct.
  • The class can inherit another class whereas struct cannot inherit another struct
  • Since class supports inheritance it can have abstract, virtual and sealed methods, can have protected access modifier. They are not applicable to struct as it does not support inheritance.
  • The struct is always sealed whereas class is not. 
  • The class can have explicit parameter-less constructor whereas struct cannot have.
  • The class can have destructors whereas struct cannot have destructors.
  • The new operator has to be used to create instance for the class, whereas the new operator is not required to create the instance for the struct. The new operator still can be used with the struct to initialize its members with the default values.     
  • What are the common features between struct and class?  (Beginner)
  • They both can have nested types like enum, class or struct.
  • They both can have constants, fields, properties, methods, events, indexers and static members 
  • They both can implement interfaces
  • They both support constructor and operator overloading.
  • They both support generics
  • They both can be declared as partial.
  • They both support this operator in the methods to refer the members.
  • What are different access specifier available in C#?  (Beginner)
  • private   - The member accessible only within the class where it is defined.
  • public - The member accessible every where.
  • protected - The member accessible only to the derived classes.
  • internal - The member is accessible to all the classes of same assembly.
  • protected internal - The member is accessible to all the classes of same assembly and all the derived classes (which may be defined in the other assemblies)
  • private protected - The member is accessible to all the derived classes of same assembly but not accessible from the derived classes defined in other assemblies.
  • What is the difference between protected internal and private protected access specifier ?  (Beginner)

The differences can be explained through the following example:

namespace Assembly1
{
       public class A1
      {
              protected internal int X  ;  
              private protected int Y;

            void method()
            {
                  // X is accessible
                 // Y is accessible
             }
      }

       public class A2 : A1
      {
            void method()
           {
                  // X is accessible
                 // Y is accessible
           }
      }

       public class A3 
      {
            void method()
           {
                  // X is accessible
                 // Y is NOT accessible
           }
      }
}

namespace Assembly2
{
       public class B2: A1
      {
            void method()
           {
                  // X is accessible
                 // Y is NOT accessible
           }
      }

       public class B3 
      {
            void method()
           {
                  // X is NOT accessible
                 // Y is NOT accessible
           }
      }
}
  • What is the difference between abstract and sealed class?  (Beginner)
  •  An abstract class is meant to be inherited by child classes.   A sealed class is to prevent a class from being used as a base class. 
  • We are not allowed to create instances of abstract classes. Instances can be created with sealed class. 
  •  The Abstract class can have abstract and/ or virtual methods. A sealed class cannot define a virtual  method and abstract methods.
  • What is the difference between static and abstract class?  (Beginner)
            Though both static and abstract classes cannot be instantiated, the following are the differences:
  • The static class cannot be inherited whereas abstract classes are created for the other classes to inherit.
  • The static class can contain only static fields and methods. It cannot have non-static, abstract or virtual methods.  Abstract classes consists of one or more abstract methods. It can also have virtual, static and non-static methods.
  • What is an abstract class?  (Beginner)
               An abstract class is a kind of class which cannot be instantiated and can be used to have the common functionalities of the sub classes.
           It can have one or more abstract methods and virtual methods. The abstract and virtual methods are supposed to be implemented/ overridden in the sub classes.
          The abstract classes can have concrete methods as well to represent the common functionalities of the sub classes.
              For example:
                        public abstract class Vehicle
                         {

                                   private int _noOfWheels;  // Common property of all the sub classes
                                   public void StartIgnition()
                                   {
                                              // This is a concrete method to have common functionalities.
                                    }
             
                                  abstract void Accelerate();  // This is an abstract method. The sub class should                                                                                  //implement this method

                                  public virtual void PullUp()
                                  {
                                          // This is a virtual method. It can be overridden in the sub classes
                                  }
                         }


  • What is attribute  ? (Beginner)
             An attribute allows the developers to associate meta data with code entities like assembly, class, method, property or event. The attributes are specified using a name enclosed within the pair of square parenthesis along with the optional parameter values.

For example:

     [Authorize(Roles = "Admin")]
    public class AdminController : Controller
    {
    }
         
             In the above example, Authorize is an attribute specified to the class, 'AdminController' along with the parameter, 'Roles'. The developer specifies to the ASP.NET Runtime that only users with 'Admin' role should be allowed to access the action methods defined within AdminController.

             The attributes associated with the code entities are queried using the Reflection (by the ASP.NET runtime in the above example)

             The following are some of the applications of attribute:
  •    Attribute can be used to specify which class members can be serialized for persistence.
  •    Attribute can be used to specify the title, version, description, or trademark for an assembly.
  •    Attribute can be used to specify the security requirements for methods.
  •    Attribute can be used to specify the validation requirements for model properties
          
    Fields and Properties
  • What is auto implemented property?  (Beginner)
                   An auto implemented property is a concise way of defining a property which does not  have any logic for setters and getters other than assigning and reading from the backing field.

                 For example:

                            public class Employee
                           {
                                  private string _firstName;
                                  private string _lastName;
                              
                                  public string FirstName { get { return _firstName} set {_firstName = value}}
                                  public string LastName { get { return _lastName} set {_lastName = value}}
                           }

                      In the above example, two properties FirstName and LastName does not have any logic other than assigning and returning value from the respective backing fields, _firstName and _lastName.  Such properties can be defined using concise syntax as follows:

                            public class Employee
                           {
                                  public string FirstName { get; set; }
                                  public string LastName { get; set; }
                           }         

  • What is the difference between const, readonly and static readonly fields?  (Beginner)
  • The const variables - They are internally static and the value assigned to it cannot be changed anywhere in the application. The value can be assigned only where the variable is declared.
  • The readonly variables- The value can be assigned to the readonly variable either where the variable is declared or in the constructor of the class
  • The static readonly variables - The value can be assigned to the readonly variable either where the variable is declared or in the static constructor of the class.
  • What is read-only auto-properties? what is the advantage of it?  (Beginner)
            An auto property defined just with get accessor is called read-only auto-properties.
 For example:
              class Point
              {
                  public int X  {get; }
                  public int Y {get; }
              }

           These properties  cannot be modified in any of the methods except the constructors:

              Point (int x, int y)
              {
                         X = x;         // No compilation error
                         Y = y;         // No compilation error     

              }

            int  GetDistance()
            {
                       X = 5;          // throws compilation error as X cannot be changed.
            }


            A read-only auto-properties provide a more concise syntax to create immutable types.

  • What is an indexer? (Beginner)
           Indexers are useful to the class which represents multiple elements like List and Dictionary. It is used to set or get the element of the object using index. The index can be an integer or a key/ string.

          For example:

                   public class TemperatureReading
                    {
                              public int Day;  // can take 1 - 30
                              public string Time;    // can store time like 12:00PM
                              public float Reading;   // can store temp in Celsius

                    }
                    public  class RoomTemperature
                    {
                            private List<TemperatureReading> TempReading 
                                         = new List<TemperatureReading>();   

                             public float this[int day, string time]            // indexer
                             {
                                         get
                                         {
                                                  return Find(day, time) 
                                         }
                                         set
                                         {
                                                   AddOrEdit(day, time, value); 
                                         }
                            }

                            private float Find(int day, string time)
                            {
                                           // code to retrieve the temperature at the given day and time
                             }


                            private void AddOrEdit(int day, string time, float value)
                            {
                                         // code to add or edit the temperature at the given day and time.
                             }
                    }

                  The above code defines an indexer that takes two indexes: day and time. The indexer can be called as below:
              RoomTemperature  roomTemp = new RoomTemperature();

              roomTemp[1, "06:00AM"] = 31;      // setter is called. 1 as passed as day ,"06:00AM" is passed as time and 31 is passed as the value
              roomTemp[1, "12:00PM"] = 35;
              roomTemp[1, "07:00PM"] = 32;
              roomTemp[2, "00:00AM"] = 28;

             float timeAtMorning = roomTemp[1, "06:00AM"] ; // assigns 31 to the variable.

  • What is the difference between a property and indexer? (Beginner)
  • Property can be accessed through a name whereas indexer can be accessed through an index.
  • Property can be static or instance member whereas indexer cannot be static member. It can be only defined as instance member
  • Property can be defined concisely with auto-implemented property syntax whereas indexer does not support auto-implemented syntax
  • What is expression bodied function member? (Beginner)
        Expression bodied function member is a concise way of defining a method or read only property with single statement/ expression.

             For example:

                        public class Point
                        {
                                   public int X (get;}
                                   public int Y{get;}

                                   public override string ToString()
                                   {
                                           return X.ToString() + "-" + Y.ToString();
                                    }
                        }

          Since the ToString() method has only single expression statement, it can be rewritten in concise way as expression bodied function:

                        public class Point
                        {
                                   public int X (get;}
                                   public int Y{get;}

                                   public override string ToString() => $"{X.ToString()} + "-" + {Y.ToString()}";

                        }

         A property also can be written as expression bodied function as below:

                public string LastName {get; set;}
                public string FirstName {get; set;}

                public string EmployeeName  => $"{LastName}, {FirstName}"
          
    In the above example, EmployeeName is defined as the ready only property which is a concatenation of LastName and FirstName properties. It is written concisely using expression bodied function.
    Method

  • What is an abstract method?  (Beginner)
  • An abstract method will not have body/ implementation. It is overridden/ implemented in the derived classes.
    • For example:
                     public abstract class A
                     {
                             public abstract void method();

                     }
                     public class B : A
                     {
                              public override void method()
                               {
                                       Console.WriteLine("abstract method of base class is overriden in this class");
                               }  
                     }
  • The abstract method is implicitly a virtual method.
  • The abstract methods can be declared only in abstract classes.
  • The abstract method cannot be static.
  • What is a sealed method?  (Beginner)
  • A sealed method cannot be overridden in the child classes.
    • For example: 
          public class A 
          {
               public virtual void method()
              {
              }
         }
          public class B : A 
         {
                 public sealed override void method()
               {
                            // sealed method which cannot be overridden in the sub classes.
               }
         }

          public class C : B 
         {
                 public override void method()
                {
                         // this method does not compile as it is sealed in the parent class and not meant to be                            // overridden. 
                }
         }
  • The sealed method must be part of a derived class and should be always used with override.

  • What is the difference between static and non static method?  (Beginner)
  • The static method can access only the static fields whereas non-static method can access both static and non-static field.
  • The static method can be called only using the class name as the prefix whereas non-static method can be called only using an object.
  • The static method can be defined in static or non-static class whereas the non-static method can be defined only in non-static class and cannot be defined in static class.
  • What is the method overloading  (Beginner)
           Defining more than one method with the same name within a class  but different signatures is called method overloading. The overloaded methods should have
  • different number of parameters or
  • different data types of parameters or
  • parameters of same types but in different order
The methods cannot be overloaded by having just different type of value they return.

for example:
                public class KeyValueList
                {
                        int Find(string key)
                       {
                               // Finds element by key
                       }

                       string Find(int value)
                       {
                              // Finds key by passing the value
                      }
              }
                   
             The Find method in the above class is overloaded by having the same number but different data type of parameter.
                           
  • What is the difference between method overloading  and method overriding? (Beginner)
               Defining more than one method with the same name within a same class or class hierarchy but different method signatures is called method overloading.
              Defining more than one method with the same name and same signature within each class of an hierarchy is called method overriding.


  • What is virtual method ?  (Beginner)
            A virtual method specifies that the method can be overridden or redefined in the derived class if the method should be implemented differently in the derived class. 
            For example:
                              public class Car
                              {
                                           public virtual void Pullup()
                                           {

                                           }
                               }

                              public class SportsCar : Car
                              {
                                           public override void Pullup()
                                           {
                                              // brakes are different in Sports car, so it requires different Pullup process

                                           }
                               }
               In the above example, Pullup method is defined as virtual method (using virtual modifier). It means the derived classes like SportsCar, the method can be overriden/ redefined using override modifier.
           The corresponding methods are called when the method is invoked from the respective objects:

                   Car car = new Car();
                   SportsCar sportsCar = new SportsCar();

                   car.Pullup();       // calls the method of Car class
                   sportsCar.Pullup();       //  calls the method of SportsCar class

                 Virtual modifier cannot be used with static, abstract and override modifiers.
A private method cannot be a virtual method.
            
  • What is the difference between abstract method and virtual method ?  (Beginner)
  • The abstract method does not have body/ implementation whereas virtual method would have method body like any other methods.
  • The abstract method must be overridden in the derived classes whereas virtual method may or may not be overridden in the derived class.
  • The abstract method must be declared in abstract class whereas virtual method may not may not be defined in abstract class.
  • What is an anonymous method? (Beginner)
           An anonymous method is a method which is defined without a name. It is created using the delegate keyword. It is usually used in one of the below scenarios:
  • Anonymous method can be assigned  to a delegate reference, so that the anonymous method can be called later through the delegate reference.
                   For example:
                          public delegate bool CompareLogic(int x, int y);
                          CompareLogic  compareLogic = delegate(int x, int y)
                         {
                                // This is an anonymous method
                                  return (x >= y)? true: false;
                        }

  • Anonymous method can be passed as a parameter to an another method which takes delegate as the parameter.
                    void Sort(int [] list, CompareLogic compareLogic)
                    {
                                 compareLogic(list[0], list[1] ); 

                    }

                    Sort(list, delegate(int x, int y)
                         {
                                // This is an anonymous method
                                  return (x >= y)? true: false;
                        }
                      );

  • What is an extension method? (Beginner)
            The extension method enables to add a new method to an existing class without modifying the original class or without creating a new sub class.
             For example, the following Left method is an extension method of string class:
namespace ClassExtensions
{
     public static class StringExtensions
     {
             public static Left(this string originalString, int noOfCharacters)
            {
                         return originalString.Subtring(1, noOfCharacters);
            }
     }
}

             As there is no predefined Left method available in .net framework for strings, it is possible to create our own extension method without the changing the string class.

  • How to define and call the extension methods? (Beginner)
            The following are the rules for creating extension methods:
  • The extension methods should be defined as static method.
  • The extension methods should be defined within a static class
  • The first parameter of the method should be of the type/ class which you are going to extend.    
  • The first parameter should be prefixed with 'this' keyword.
  • The name and signature of the extension method should not be same as an another method which is defined as part of the original class.
  • In order to call the extension method in an another class, the namespace of the extension class should be referred through 'using' statement as follows:        
           using ClassExtensions;
           namespace CallingNamespace
           {
                   public class CallingClass
                   {
                           public void CallingMethod()
                           {
                                        string str1 = "Hello World";
                                        string str2 = str1.Left(7);  // assigns "Hello W" to str2
                            }
                    }
           }
  • What is Local Function?  (Beginner)
            Local function is a method which is defined within an another method, constructors, property accessors or an another local function. The local function can be called only from the containing method and are not accessible outside the containing method.
            The local function as the following advantages:
  • It makes the reader of the code very clear that the method is called only from the containing method and thus improves the readability of the code.
  • It disallows the programmer to call the method accidentally from the methods other than containing methods.             
For example:
            public  void GetAverage(int [] numbers) 
          { 
  
                 return GetSum(numbers) / numbers.length;
                
               int GetSum(int [] numbers) 
               { 
                       int sum = 0;
                       foreach(int element in numbers)
                       {
                                sum += element;
                       }
                        return sum;
                } 
    } 
In the above example, GetSum is a local function defined within GetAverage() method. It can be called only from GetAverage();



  • What is this pointer ? (Beginner)
            The 'this' keyword is used to define indexers and extension methods. Apart from these usages, this keyword can also be used in the methods to refer the current instance of the class.
For example:

            public class Car
           {
                 private Engine _engine;
                  public void SetEngine(Engine engine)
                  {
                             _engine = engine;
                  }

            }
            public class Engine
            {

                 public void AttachToCar(Car car)
                 {
                         car.SetEngine(this);
                 }

             }

            public class MainDemo {
                    public void Main ()
                   {
                        Engine powerfulEngine;
                        Car raceCar;
                        powerfulEngine.AttachToCar(car); // powerfulEngine object is attached to raceCar object
                   }

              }

        In the above example, AttachToCar method of Engine, attaches itself to the  'car' object  passed as the parameter.
         The 'this' keyword can also be used to refer the members of the same of the class as below:
                 class Laptop
                {
                           Keypad kpad;
                           Mouse mouse;
                           RAM ram;

                          public Laptop(Keypad k, Mouse m, RAM r)
                          {
                                       this.kpad = k;    // kpad object of the same class.
                                       this.mouse = m;
                                       this.ram = r;

                          }
                     
                           public void Reboot()
                          {
                                  this.SwitchOn();   // SwitchOn method of the same class is called
                                  this.SwitchOff();
                           }
                          public void SwitchOn() {}
                          public void SwitchOff() {}


                 }
   
        In the above example, 'this' keyword is optional. It is just used to improve the readability of the members like method call or fields reference.
      As the static methods are not associated with any object, 'this' pointer cannot be used within static methods.
    Delegates
  • What is a Delegate?  (Beginner)
             A delegate is a reference type used to hold the reference of a C# method. It is similar to the function pointer in C/ C++.
  • Delegates can hold the reference of  static or instance methods.
  • Delegate can be used to define callback methods.
  • Methods can be defined to have delegate type as the parameter. This means the reference of a method can be passed as the parameter to an another method.
             For example:
                      public delegate bool CompareLogic(int x, int y);

            The above statement creates a delegate type by the name CompareLogic which can hold the reference/ pointer of any methods that takes two integer parameters and returns bool.
            For example, reference of the following method,
                    public class IntegerCompare
                    {
                            public static bool Compare(int x, int y)
                           {
                                  if( x >= y)
                                  {
                                           return true;
                                  }
                                  else
                                  {
                                           return false;
                                  }
                           }
                     }
                 can be assigned to an instance of CompareLogic delegate type as follow:

                 CompareLogic  compareLogic = new CompareLogic( IntegerCompare.Compare);

           Now the compareLogic object can be used to call IntegerCompare.Compare method as follows:
                    bool isGreaterOrSame  =   compareLogic(2, 5); 


  • What is multicast delegate ? (Beginner)
           A multicast delegate is a delegate which holds the references of more than one method.The method signatures can be added to a delegate using '+' operator. Similarly, the method signatures can be removed from a delegate using '- ' operator.
           When the multicast delegate is called, all the methods which are added to it are invoked one after the other (in the same order of addition).
           For example:


                 delegate void OnCompletedCallback(bool isSuccess);
                 public class MulticastDelegateDemo
                 {

                 public void PerformTasks(OnCompletedCallback callback)
                 {
                               try
                               {
                                 // do tasks
                                callback(true); // task is successful, invoke the callback method
                               }
                               catch
                              {
                                      callback(false); // task is failed, invoke the callback method
                               }
                 }

                 private void callbackWhenSuccess(bool isSuccess)
                 {
                            if(isSuccess)
                            {
                                  System.Console.WriteLine("Task is Success");
                                  // Perform  Success tasks
                           }
                 }

                 private void callbackWhenFailure(bool isSuccess)
                 {
                            if(!isSuccess)
                            {
                                  System.Console.WriteLine("Task is Failed");
                                  // Perform  Failure related tasks
                           }
                 }

                   public void main()
                   {
                         OnCompletedCallback  callback;
                         callback= callbackWhenSuccess;
                     
                         callback = callback + callbackWhenFailure; // delegate is now multicast
                   
                          PerformTasks(callback);

                   }

               }

             In the above example, 'callback' is a multicast delegate which holds the reference of both callbackWhenSuccess and callbackWhenFailure methods.
             The 'callback' delegate is passed to PerformTasks() method. It calls both the methods assigned to the 'callback' delegate.
  • What is an event?  (Beginner)
              Events enable a class or object to notify other classes or objects when something of interest occurs.
            For example: A class called Account can raise an event called Overdraft whenever balance of the account goes below zero. The event Overdraft can be handled by an another class to perform some action(s).  Please see below the code:

          public delegate void OverdraftEventHandler (object sender,
                              NumberReachedEventArgs e);

           public class Account
           {
                     private double _balance;
                     public event OverdraftEventHandler Overdraft;

                     public void Credit(double amount)
                     {
                                _balance += amount;
                     }

                     public void Debit(double amount)
                     {
                                _balance -= amount;
                                 if(_balance < 0)
                                 {
                                        if(Overdraft != null)
                                        {
                                              OnOverdraft(this, new eventArgs());
                                        }
                                }       
                     }
                   protected virtual void OnOverdraft(EventArgs e)
                   {
                        if(Overdraft!= null)
                        {
                               Overdraft(this, e);//Raise the event
                        }
                  }
         }



  • What is Func, Action and Predicate delegate  ? (Advanced)
     The Func, Action and Predicate are built-in generic delegate types included as part of System namespace for the common requirements, so that the developers can make use of them instead of creating their own custom delegates.

Func:   The Func delegate can be used to point to any method that takes 0 to 16 parameters and one return value.
          For example, the following are some of the built-in Func delegates available in C#:
            public delegate TResult  Func<out TResult>(); // method that returns a value, of type,TResult but does not take any parameters.

            public delegate TResult  Func<in, T1,  out TResult>(T1 arg1); // method that returns a value of type TResult, and takes one parameter of type T1

            public delegate TResult  Func<in, T1, in T2, out TResult>(T1 arg1, T2 arg2); // method that returns a value of type TResult, and takes twp parameters of type T1 and T2

Action:  The Action delegate can be used to refer any methods that take 1 to 16 parameters and does not return any value.
           For example, the following are some of the built-in Action delegates available in C#:

            public delegate void  Action<in, T1>(T1 arg1); // method that does not return a value and takes one parameter of type T1

            public delegate void  Action<in, T1, in T2>(T1 arg1, T2 arg2); // method that does not return a value  and takes two parameters of type T1 and T2

Predicate: The predicate delegate can be used to refer any method that take one parameter and returns a bool value as below:

public delegate bool Predicate<in T>(T obj);

  • What is covariance and contravariance with respect to delegate  ? (Advanced)
             Covariance allow the developer to assign a method that returns child class to a delegate that returns a base class.
             For example:
                  public class Vehicle {
                          public void SetVehicle(Vehicle obj) {}

               }
                  public class Car : Vehicle {

                            public Car GetCar() {}
                }
                  public  Vehicle delegate GetVehicle();
             
                 GetVehicle vehicleGetter = GetCar; // covariance


In the above example, the delegate vehcileGetter which is of type GetVehicle that returns Vehicle can be assigned with the method that returns Car because Car is the child class of Vehicle.

          Contravariance allow the developer to assign a method that takes base class object as a parameter to a delegate takes child class as the parameter.

           For example:
                    public void delegate SetCar(Car obj);
                    SetCar carSetter = SetVehicle;  // Contravariance

In the above example, the delegate carSetter which is of type SetCar  takes Car as the parameter. The carSetter can be assigned with a method, SetVehicle that takes Vehicle as the parameter because Vehicle is the base class of Car.
             




    Constructor & Destructor
  • What is  static constructor ?  (Beginner)
  • static constructor is used to initialize the static fields of the class. For example, a static constructor can have code to read a configuration file and assign to a static members of the class.
  • static constructor is called only once before the static members of the class is referred in the code or before the first object of the class is instantiated.
  • static constructor cannot be called directly.
  • static constructor cannot take parameters
  • static constructor cannot have access specifiers.
  • What is the difference between constructor (non-static) and  static constructor ?  (Beginner)

  • Constructor is used initialize the concrete members of the class whereas static constructor is used to initialize the static members of the class.
  • Constructors are called explicitly using the new operator whereas static constructor are called automatically whenever the static members have to be initialized.
  • Constructor is called  whenever an object of a class is created whereas static constructor is called only once in the life time of the application.
  • Constructor can have parameters whereas static constructor cannot have parameters.
  • Constructor can have access specifiers whereas static constructor cannot have access specifiers.
  • What is a Destructor? (Beginner)
              Destructor are methods which are called by Garbage collector to release the un-managed objects used by the class.
              Destructors are named in the same name of the class prefixed with tilde (~) character as follows:
       public class EmployeeRepository
       {
                 private SqlConnection _connection;

               ~EmployeeRepository()
                 {
                                if(_connection != null)
                                {
                                         connection.Dispose();
                                 }
                 }
         }

  • Destructor does not take parameter nor return any type. Hence, it cannot be overloaded.
  • Destructor cannot be overridden and cannot have any modifiers. 
  • It can be defined only in class and cannot be defined within a struct.
  • It cannot be called explicitly, it is called automatically by Garbage collector.
  • Programmer does not have a control of the time when the destructor is called. 
  • Destructor calls the base class's destructor before it terminates. This means the destructors are called in the reverse order of constructors in the class hierarchy. The derived class destructors are called followed by the base class constructors.


  • What is Dispose pattern  ? (Beginner)
The dispose pattern helps the class author to provide a way to the class consumers to cleanup the un-managed objects used by the class.
       The IDisposable interface is defined as part of .Net framework for the class authors to implement the Dispose method in their classes. The IDisposable class requires class authors to implement only one method called Dispose() in their method.
      The Dispose method can be used to clean-up the managed objects as well if

  •    the managed objects used by the class implements IDisposable interface (or)
  •    the managed object consumes large memory and it would be good to dispose them instead of waiting for Garbage collector to clean-up those resources.
See below an example of IDisposable implementation:

     class DerivedClass : BaseClass

{
   // Flag: Has Dispose already been called?
   bool disposed = false;

 // Public implementation of Dispose pattern callable by consumers.
   public void Dispose()
   { 
      Dispose(true); // dispose both managed and unmanaged objects
      GC.SuppressFinalize(this);      // there is no need for GC to clean unamanaged object as it is already done,  now.     
   }

   // Protected implementation of Dispose pattern.
   protected override void Dispose(bool disposing)
   {
      if (disposed) // if it is already disposed, exit silently
         return; 
      
      if (disposing)         // If this method is called from Dispose() method, clean-up managed object. Otherwise, this method is called from Destructor.
     {
         // Free managed objects here.
         
      }
      
      // Free unmanaged objects here.
      
      disposed = true; // The objects are now disposed, so that it should be tried to dispose again if called once again by mistake

      // Call base class implementation.
      base.Dispose(disposing); // Call the base class  dispose method (if any)
   }
 ~BaseClass()
   {
      Dispose(false); // Dispose only the unmanaged objects
   }
}
   

  • What is using statement ? (Beginner)
              The using statement ensures that Dispose method is called properly when the IDisposable object goes out of scope or whenever the exception is raised.
             For example:
                  using(SqlConnection connection = new SqlConnection)
                  {
                             //database operations

                  }

In the above example, connection object is created within the using statement and disposed at the end of the block. The using statement also ensures that the dispose method is called in case if any exception is thrown within the using statement.
             The compiler internally transforms the using statement as below:

              try
               {
                             SqlConnection connection = new SqlConnection();
                             // database operations
               }
               finally
               {
                               if(connection != null)
                               {
                                        connection.Dispose();
                               }
               }

    Variables & Parameters


  • How to pass value type variable to a method by reference? (Beginner)
        Value type variables (int, char, float, bool etc) are always passed to a method 'by value' instead of  'by reference'. This means, when the variable is modified within the method, the changes are not reflected in the calling method.
        To pass the value type variables 'by reference' to a method, 'ref' keyword has to be used as below:

             public class   RefDemo
            {
                     public void SwapByValue(int x, int y)
                     {

                          int temp = x;
                          x = y;
                          y =  x;
                    }

                      public void SwapByRef(ref int x, ref int y)
                     {
                          int temp = x;
                          x = y;
                          y =  x;
                    }

                    void Demo()
                    {
                           int x = 2 ;
                           int y = 4;

                           System.Console.WriteLine($"x = {x}  y = {y}" ); // shows 2, 4

                           SwapByValue(x, y);
                           System.Console.WriteLine($"x = {x}  y = {y}" );  // shows 2, 4 as the values are not actually swapped

                           SwapByRef(ref x, ref y);
                           System.Console.WriteLine($"x = {x}  y = {y}" ); // shows 4, 2 as the values are swapped.


                   }

            }



  • What is the difference between in and ref parameters ? (Beginner)
             The 'in' parameter is used to pass the value type variables (like large struct variables) to a method by reference to improve the performance but disallow the variable value to be changed inside the called method       

            Though, both 'in' and 'ref'  are used to pass the parameters by reference, the ref parameter can be modified inside the method so that the modified value is reflected in the calling method whereas the 'in' parameter cannot be modified inside the method. The code that modifies the 'in' parameter within a method results in a compilation error.
 

For example:
           public class RefInDemo
           {

                     void calledMethod(ref int x, in int y)
                      {

                                 x = 4;
                                 // y = 4; // un-commenting this line throws compilation error as y is in parameter

                       }
               
                      void callingMethod()
                       {
                                    int x = 2;
                                    int y = 2;
                       
                                    callingMethod(ref x, in y);

                                     System.Console.WriteLine($"x = {x}  y = {y}" ); // Shows 4, 2

                         }
           }

.
  • What is ref locals ? (Beginner)
            The local value type variable that can have reference of an another value type variable is ref local variable.
            For example:
                     int x = 4;
                     ref int y = ref x;
                     y = 2;       // assigns 2 to x
                     System.Console.WriteLine($"x = {x}  y = {y}" ); // Shows 2, 2
               
In the above example, y is the ref local which stores the reference of variable, x. Here the variable y acts as an alias of x. Hence, when a value is assigned to y, actually it is assigned to x.

  • What is ref returns ? (Beginner)
              The ref  return allows a method to return a reference of a variable instead of value to the caller.
          For example:

               public class RefReturnDemo
               {

                            public ref int FindMax(int [] elements)
                            {
                                         int maxIndex;
                                         int maxValue = 0;
                                         for(int index; index < elements.length; index++)
                                         {
                                                 if( element > max)
                                                  {
                                                            maxIndex = index;
                                                            maxValue = element;
                                                   }

                                         }
                                         return ref element[maxIndex] ;                                   
                                 
                             }

                             public void Demo()
                             {
                                           int [] elements = {5, 2, 7, 9, 8, 4};

                                           ref maxElement = FindMax(elements);

                                            System.Console.WriteLine($"elements[3] = {elements[3]" ); // Shows 9

                                            maxElement = 10;

                                            System.Console.WriteLine($"elements[3] = {elements[3]" ); // Shows 10

                              }

                  }

The ref returns are mainly useful to improve the performance when large struct variable is to be returned from a method.


  • What is an out variable?  (Beginner)
         The variable which is both declared and passed as the output argument to a method is called a out variable.

             For example:
                  if (int.TryParse(input, out int result))
                         Console.WriteLine(result);
                  else
                         Console.WriteLine("Could not parse input");

              In the above example, the 'result' is the out variable. It is declared in the argument list of the TryParse method. The TryParse method assigns the output value to the result variable.

              The above code can also be written as follows without out variable as below:

                   int result;        // declare the variable separately
                   if (int.TryParse(input, out result))
                         Console.WriteLine(result);
                  else
                         Console.WriteLine("Could not parse input");

         The following are the advantages of out variable: 
    •   It improves the readability of the code as the out variable is declared where we use it, not on a separate line.
    •   It prevents the developer to use the variable before it is getting assigned.       
    General

  • What is the difference between Stack and Heap memory?  (Beginner)
  • Value variables are allocated in Stack whereas Object References  are allocated in Heap.
  • The memory for the method parameters and local variables are allocated in Stack whereas the object reference declared within a method or class are allocated in Heap.
  • The stack is attached to a thread, so when the thread exits the stack is reclaimed. The heap is typically allocated at application startup by the runtime, and is reclaimed when the application  exits.
  • The stack is faster because all free memory is always contiguous. No list needs to be maintained of all the segments of free memory, just a single pointer to the current top of the stack while the heap has much more complex bookkeeping involved in an allocation or deallocation.
  • In a stack, the allocation and deallocation is done by CPU and is automatic whereas, in heap, it needs to be done by the programmer manually.
  • Stack is not flexible, the memory size allotted cannot be changed. On the other hand, a heap is flexible, and the allotted memory can be altered.

  • What is boxing and unboxing?  (Beginner)
  • The concept of boxing and unboxing is based on the C# unified principles of the type system in which a value of any type can be treated as an object.
  • Boxing is the process of converting a value type to the object type. When the dot net run-time boxes a value type, it copies the value inside a System.Object and stores it on the heap memory.  For example:
                      int valueType = 120;
                      object referenceType = valueType;
  • Unboxing is the process of extracting the value type from the object on the heap memory.  Unboxing requires explicit typecasting from the object type to a value type. For example:
                   int valueType = (int) referenceType;


  • What is Generics?  (Beginner)
Generics allows us to design classes that would have common operations/ methods across multiple types without compromising on the type safety. The type on which the class operates need not specified when the class is defined.  The type is specified only when the class is instantiated.

For example:
           The list/ collection operations like Add object to the list, Remove an object from the list, find an object in the list etc are common across types like string, int or any reference type like Employee or Department. Instead of creating a collection classes for each types, it is possible to create a generic class to support all the types as below:
          public class List<T>
          {
                      void Add(T object);
                      bool Remove(T object);
                      bool Contains(T object);
         }
        In the above example, List is a generic class which operates on any type T. The Add, Remove and Contains operations are common operations which can work for any type T. The type which List will operate on not specified explicitly while creating the class instead it is specified while creating the instance as follows:

                 List<string> strings = new List<string>();          // Collection of strings
                 List<Employee> employees = new List<Employee>();  // Collection of employees

                 strings.Add("an element");
                 employees.Add(new Employee());

Generics avoid redundant code. Without generics, we might end-up with writing redundant code for each type required to be supported. 


  • What is Reflection  ? (Beginner)
                Reflection is a .net framework library (defined as System.Reflection) which would allow the developer 
  •      to examine the program entities like class, field, properties, methods, events etc defined as part of an assembly
  •      to find out the attributes declared on the program entities.
  •      to instantiate the objects of classes and call methods dynamically at runtime.
  •      to create new types/ classes at run time and perform programming tasks on the types.

  • What is LINQ  ? (Beginner)
             LINQ stands for Language INtegrated Query available part of C# language to query various data sources like array/ collection of objects, database or XML.

for example:
            int [] elements = { 2, 4, 7, 9, 3 }
            var evenElements = from element in elements
                                where (element / 2.0) == Math.Truncate (element/ 2.0)
                                order by element descending
                                select element ;

             foreach(int evenElement in evenElements
            {
                    System.WriteLine(evenElement);
            }

The above Linq query gets all the even numbers from the array, 'elements' after sorting the numbers by descending order.


  • What is the difference between IEnumerable and IQueryable interfaces  ? (Advanced)
  • IEnumerable is suitable for querying in-memory objects like array and collections whereas IQueryable is suitable for querying objects like SQL tables which resides outside the memory.
  • In case, if operations like Where, Take, Skip or group function (like sum or avg) are used in the query, IEnumerable fetches all the data (from array/ collection) and then performs the operation. Whereas, IQueryable generates a equivalent SQL (with WHERE, TOP, SUM or AVG clauses) and the operations are applied at the database level and then the filtered data is fetched.
  • IEnumerable is part of System.Collections namespace whereas IQueryable is part of System.Linq namespace.
  • IEnumerable is used in LINQ to Objects and LINQ to XML whereas IQueryable is used in LINQ to SQL.
  • IEnumerable takes Func<T> for any operators that require predicates or anonymous function whereas IQueryable takes Expression<Func<T>>
      
  • What is using static directive ? (Beginner)
The using static directive is used to refer the static members of a class without the class name in the code.
For example:
                  using static System.Console;
                  public class Demo
                  {

                         static void main()
                        {

                                   WriteLine("This method is called without System.Console");
                        }
                  }
   
In the above example, since System.Console is used with 'using static' directive, WriteLine method can be called without 'System.Console' prefix.


     
  • What is difference of throw and throw ex ? (Beginner)
     The throw statement without exception object re-throws the same original exception to the caller without resetting the Stack trace. It preserves the original error stack. The throw statement called with exception objects throws a new exception object to the caller. The call stack trace is here replaced with the new stack trace starting at the new re-throw point.

For example:

        static void Main(string[] args)
         {
                   try {
                          RethrowTheSameException();
                        }
                        catch (Exception x)
                       {
                             Console.WriteLine(x.StackTrace);
                       }
                      try
                     {
                             ThrowTheNewException();
                     }
                     catch (Exception x)
                    {
                            Console.WriteLine(x.StackTrace);
                    }
       }

      private static void RethrowTheSameException()
    {
            try
           {
                  DivByZero();
           }
           catch
          {
                 throw;
         }
  }
   private static void ThrowTheNewException()
    {
            try
           {   int a = 5, b = 0;
                 int c = Divide(a, b);
           }
           catch (Exception ex)
          {
                 throw ex;
         }
 }

private static int Divide(int a, int b)
{
        return a / b;
}

In the above example, the RethrowTheSameException() method preserves the method Divide() in the call stack trace. But the method ThrowTheNewException() method, hides the method Divide() in the call stack trace.


  • How to implement asynchronous programming in C#? (Beginner)
      The asynchronous code can be implemented in C# using async and await keywords. The code that does IO operations (like reading/writing a file) or does network operations (like web request to an another server) are more suitable for asynchronous programming.
      The asynchronous code are implemented as  asynchronous methods which are defined using async keyword. The async method returns Task <T> object which represents the state of the async code.
for example:
                      public Task<string> async GetUserName(int userId)
                      {
                                  string userName;

                                    // does a database operation to fetch user name of the given user Id

                                   return userName;
                       }

        The asynchronous method is called as below:

                 Task<string> getUserNameTask;
                 Task<Invoice> getInvoiceTask;

                 getUserNameTask = GetUserId(userId);
                 getInvoiceTask = GetInvoice(invoiceId);
               
                int userName = await getUserNameTask;
                Invoice invoice = await getInvoiceTask;
             
In the above example, two async methods GetUserId and GetInvoice are called. The GetUserId returns a Task that represents the method call of GetUserId. Immediately the second method GetInvoice is called which returns as Task that represents GetInvoice call.
               The await keyword makes the code to wait till the awaited task is completed and return the output of the method. The Tasks, getUserNameTask and getInvoiceTasks are awaited in the above example to return the output, userName and invoice.


    .Net Framework Core
  • What is Common Language Specification (CLS)? (Beginner)
          CLS defines a set of features/ specifications that are required to be supported by
.net languages  so that any common software applications can be developed using multiple .net languages (such as C# and F#) and can be compatible with each other. It establishes a framework for cross-language execution.
          For example, a software application can be made up of multiple functional modules and each
module can be developed using different .net languages. Each modules can inter-operate
each other (C# code can call F# class) without any incompatibility.

  • What is Common Type System (CTS)? (Beginner)
            CTS defines a set of rules that all .net languages must follow when it comes to working
with types. It also provide a library that contains the basic primitive types that are required to be used in the software application development such as int, char, float, boolean etc
            CTS defines several categories of types:
                 Classes, structures, enums, interfaces, Delegates etc
            It also defines the other properties of the types, such as access modifiers, what are valid type members, how inheritance and overloading works and so on

  • What is Common Intermediate Language(CIL)? (Beginner)
            CIL is set of instructions generated by compilers when the source code of .net languages such
as C# and F# is compiled.
          The CIL instructions are platform independent. It can be executed by .Net Core Runtime (Common Language Runtime -CLR) available in multiple platforms like windows, Linux and iOS

  • What is Common Language Runtime (CLR)? (Beginner)
          The CLR is the virtual machine component of .Net framework which is used to execute Common Intermediate Language (CIL) code.The CLR converts CIL to machine instructions and runs the instructions understandable by the CPU.
          The CLR provides following services:
  •   Memory management
  • Thread management
  • Type Safety
  • Exception handling
  • Security
  • Garbage collection.
           As the CLR is developed specifically to a particular platform: Windows, Linux or iOS, it can convert the CIL generated by .Net language compilers to the respective platform specific code.
          The .Net Core equivalent of CLR is called CoreCLR

  • What is Just in Time (JIT) Compiler? (Beginner)
                JIT is part of Common Language Runtime (CLR) which compiles Common Intermediate Language(CIL) to CPU specific/ Platform specific native code.
               The compiler is called 'Just in time' because it compiles  CIL code during execution as needed to native code rather than converting all the CIL to native code. The compiled CIL is stored in the cache memory so that it is reused for subsequent calls if required.
             
               
  • What is Managed and Unmanaged code? (Beginner)
             The code that runs within the Common Language Runtime (CLR) is called managed code whereas the code that is executed outside the CLR directly by the operating system is unmanaged code.
             The managed code is developed using .Net languages like C#, VB.Net or F#. The unmanaged code is developed using the languages like C or C++
             The managed code can make use of the services provided by CLR like memory allocation, Garbage collection, Type checking etc. The developer who writes the unmanaged code should take care of memory deallocation and type checking by himself in the code.
            As the managed code runs in the restricted environment of CLR, the code is safe and clean. As the unmanaged code provides low level access to the programmer, the code might results in memory leaks, memory buffer overflow etc if the programmer does not follow the best practices.


  • What are some of the features of .Net Core? (Beginner)
  • .Net Core supports cross-platform - runs on Windows, macOS and Linux Operating systems.
  • It is open source but supported by Microsoft.
  • It is compatible with .Net Framework, Xamarin and Mono
  • Supports C#, Visual Basic and F# languages
  • Supports ASP.NET MVC, WPF and Windows Forms app models. It does not support ASP.NET  web forms.

  • What is Run-time Package Store in .Net Core? (Beginner)
The Run-time package store is the repository of packages that are installed in a Server/ PC so that the .net core application can just make use of  the required packages without deploying the packages along with the application.
The advantages of Run-time package store are :
  • The application can be deployed fast as the packages are not required to be bundled with the application
  • The application takes less space in the deployed machine as the dependent packages are not required to be stored along with the application.
         For example, Newtonsoft or Moq packages are common and if used by more than one .net core applications, the packages can be stored in the Run-time package store and can be referred by the .net core applications.
The Run-time package store packages are stored in the physical folder, %ProgramFiles%/dotnet/store in Windows


  • What are the different ways of deploying .Net Core applications? (Beginner)
           There are three ways of deploying .net core applications:

1.Framework dependent deployment (FDD):
In FDD, we package and deploy only our application without .net core framework. The application will use the version of .net core framework that is present in the target system. The application will be in the form of DLL file and will be executed using 'dotnet' executable.
For example, dotnet app.dll runs an application called 'app'.
2.Framework-dependent executables (FDE):
FDE is same as FDD. As the deployment generates EXE file, the application is executed without invoking 'dotnet' utility.
3.Self-contained deployment (SCD):
In SCD, the .net Core framework is packaged and deployed along with the application.

  • What is the advantage of Framework dependent deployment over Self-contained deployment? (Beginner)

  • The size of the deployment package is small in case of FDD as only the application and its dependencies are packaged  and  not the .NET Core framework.
  • Multiple applications run on the same .NET Core framework on the target system. So, FDD  reduces both disk space and memory usage on the target system.
  • No need define the target operating systems that the application will run on in advance. The CoreCLR runs executable of the application in any operation system as the application is compiled as PE file.
  • FDD allows the application to use the latest patched version of the .NET Core runtime in the target system.

  • What is a satellite assembly? (Beginner)
          A satellite assembly consists of culture (language and locale) specific resources (like strings, images, audio). It does not consist of any code.
        It is developed as part of the application which supports multiple cultures like US English or Mexican's Spanish. One satellite assembly is created for each culture, the application has to support.
The resources pertaining to specific culture are defined in *.resx files. For example, MyApp.fr-CA.resx is created for Canadian french. (fr-CA stands for Canadian french). It is an XML file which is converted to MyApp.fr-CA.resource file (Binary format) using Resource file generator (Resgen.exe) Utitilty. The assembly linker (AI.EXE) is then used to compile MyApp.fr-CA.resources to the satellite assembly called MyApp.resources.DLL
        The satellite assemblies are not named using culture specific code (like en-US or fr-CA). All the satellite assemblies are named same but moved to culture specific folders (named en-GB or fr-CA) created under the root folder of the application.


  • What is Garbage Collector (GC) ? (Beginner)
           Garbage Collector (GC) serves as the automatic memory manager within CLR to allocate and deallocate memory for objects.
           The following are the responsibilities of GC:

  • Allocates objects on the managed heap efficiently.
  • Frees the memory of objects that are no longer being used, make it available for future allocations.
  • Provides memory safety by making sure that an object cannot use the content of another object.

           The developer need not write to code in class constructors to initialize each data field. The GC automatically get clean memory for the objects to start with. Also, the developers need not write code to free-up the allocated memory.
            The GC is run whenever the system has low physical memory or whenever GC.Collect() method is called by the developer to clean the memory.
           The GC is run in a separate thread by the .net CLR.
       

  • What is the purpose of having 3 generations of heap memory ? (Beginner)
              The managed heap memory are segmented into three generation - 0, 1 and 2.
              The short lived objects (like local variable, method parameters etc) are allocated in generation-0 area.And the long lived objects (like static variables) and very large objects (in size) are allocated in generation-1 area. The generation-1 is a generation in-between. It is the buffer between generation-0 and generation-2 area.
              Whenever the GC has to run, it finds out all the dead objects (or the objects that are not referred by any other objects) in generation-0 and frees the memory occupied by the dead objects. The live objects which are still used by the application are said to be survived and moved/ promoted to generation-1 area.
               The GC runs the most on generation- 0, less on generation-1 and even less often on generation-2. The objects which are survived when the GC is run on generation-1 are promoted to generation-2 area. The objects which are in generation-2 are a kind of permanent objects usually freed at the end of the application life time.


  • What is the difference between Base Class Library (BCL) and Framework Class Library (FCL) ? (Beginner)
           The core set of data structures and classes like foundational types (int, float, bool, string, Array, List etc) and utility classes (like HttpClient, XDocument, StreamReader etc) are part of the BCL. They are base for all other .net class libraries.
           The complete set of classes that are available for the other functional areas like data access (ADO.NET, Entity framework, LINQ), Web development (ASP.NET), mobile development (Xamarin), API development (WCF)  etc are called FCL. FCL is the superset of BCL.


  • What is a .Net Assembly? (Beginner)
          The .net assemblies are building blocks of .net applications.An assembly is a collection of types/classes and resources that are built to work together to implement a logical unit of application functionality. an assembly is the lowest fundamental unit of deployment, version control, reuse  and security permissions. An assembly can be made-up of single file or multiple files.

  • What are the different types of assemblies available in .Net based on the content? (Beginner)
           The .net assemblies can be classified into two, based on their content: 
  • CLI assembly:  The common language infrastructure (CLI) assemblies consist of Common Intermediate language (CIL) code.
  • Satellite assembly: It consists of language and locale specific resources like strings, images, audio etc

  • What are the different types of assemblies available in .Net based on the location where it is deployed? (Beginner)
           The .net assemblies can be classified into two, based on their location of deployment: 
  • Private assembly: The private assemblies are deployed in the application folder. It is private to a application. It cannot be used by the other applications running in the same machine. The application folder can consists of only one version of the assembly.
  • Shared assembly:  The shared assemblies are deployed in Global Assembly Cache (GAC). They can be shared by more than one applications in the same machine. Multiple versions of the same assembly can be setup in GAC as each application can refer different version of the assembly.

  • What are the different types of assemblies available in .Net based on the assembly format? (Beginner)
       The .net assemblies can be classified into two, based on their formats:
  • Process Assembly (EXE) - The process assembly runs in its own process space of operating system. It does not require any host program and it usually refers one or more Library assemblies. 
  • Library Assembly (DLL) - The library assembly requires a host (an another process assembly) and runs in the process space of the host assembly. The main purpose of library assembly is re- usability. The classes defined inside the library assembly can be reused across the different applications by referring the library assembly in the different applications.

  • What a .net assembly consists of ? (Beginner)
            A .net assembly consists of four elements:

  • The assembly manifest - The metadata of the assembly like name, version etc 
  • Type Metadata - Details of the classes implemented by the assembly (not applicable to satellite assembly)
  • MSIL Code that implements the classes (not applicable to satellite assembly)
  • A set of Resources - Strings, images, etc (applicable only to the satellite assembly)

  • What a .net assembly manifest? (Beginner)
       The .net assembly manifest consists of metadata of the assembly. The assembly manifest
It consists of the following meta data:

  • Name of the assembly
  • Version number - Major, Minor, Revision and Build number
  • Culture - the language/ locale the assembly supports - Applicable only to satellite assembly.    
  • Strong Name - Public key from the publisher
  • List of all files in the assembly - The list of files (name and hash) that make-up the assembly
  • Type reference Info - The details of the classes that are exported by the assembly
  • Referenced Assemblies info - The details of the assemblies that are referenced in this assembly. 
For an assembly with one associated file, the manifest is incorporated into the PE file to form a single-file assembly. You can create a multi file assembly with a standalone manifest file or with the manifest incorporated into one of the PE files in the assembly.


  • What is side by side execution? (Beginner)
            Side-by-side execution is the ability to deploy and run more than one version of an
application, component/assembly or common language run time on the same machine.

  • What is Application Domain? (Beginner)
        Application domains  are the containers that helps to isolate multiple .net applications running within a operation system process.  A process might contain more than one application domains and each application domain can run a .net application independently without impacting an another .net application running within an another application domain.
        An application within a domain can be stopped without affecting the state of another domain in the same process. A fault or exception in one domain does not affect an application in another domain or crash the entire process that hosts the domains. Code in one domain cannot directly access code in another.
       The runtime host creates a process and a default application domain, and runs managed code inside it. Runtime hosts include ASP.NET, Microsoft Internet Explorer, and the Windows shell.
       For most applications, you do not need to create your own application domain; the runtime host creates any necessary application domains for you. However, you can create and configure additional application domains if your application needs to isolate code or to use and unload DLLs.

  • What is Kestrel?  (Beginner)
            Kestrel is a cross-platform web server for ASP.NET Core. 
          Kestrel can be used alone or  along with a reverse proxy server, such as Internet Information Services (IIS), Nginx, or Apache. When it is used with a reverse proxy server, the reverse proxy server receives HTTP requests from the network and forwards them to Kestrel.


  • What is a Strong-named assembly?  (Beginner)
           A strong name is given to an assembly to identify it uniquely. A strong name consists of the following:
  • Text Name
  • Version
  • Culture (optional)
  • Digital Signature (Public/ Private key pair)
          The public key and private key pair is generated using the strong name tool (SN.Exe). The key pair is  assigned to an assembly using Assembly linker (AI.Exe).
        An assembly should be strong-named if it has to be deployed to Global Assembly Cache (GAC).  If an assembly is to be made strong-named, the assemblies which it refers all should be strong-named too.


  • What is delay signing or Partial signing of an assembly?  (Beginner)
              An assembly is  delayed signed or partially signed in the development phase using the public key. The private key is usually protected from the developers and kept secret by the senior management of the organization that develops the assembly. This enables the developers to deploy the assembly to the GAC and continue the development of the others assemblies which depend on the partially signed assembly. This process enables developers to work with shared assemblies as if they were strongly named. The partially signed assembly is later signed using the private key when the development is completed and ready to be shipped.



  • What is Code Access Security (CAS)?  (Beginner)
          Code Access Security is the part of the .NET security model that determines whether or not the code is allowed to run, and what resources it can use when it is running. An administrator can configure Code Access Security policy to restrict the resource types that code can access and the other privileged operations it can perform. The Code Access Security can also help minimize the damage that can result from security vulnerabilities in your code.


Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/