Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

101.

What is a Dictionary collection in C#?

Answer»

DIFFERENT Key-Value pairs are represented using the dictionary collection. This is somewhat SIMILAR to an English dictionary which has different words along with their meanings. The dictionary collection is included in the System.Collections.Generic namespace.

A program that demonstrates the dictionary collection in C# is given as follows:

using System; using System.Collections.Generic; namespace Demo {   CLASS Example   {      static VOID Main(string[] args)      {        Dictionary<int, string> dict = new Dictionary<int, string>(); dict.Add(1,"Apple");               dict.Add(2,"Mango"); dict.Add(3,"Orange"); dict.Add(4,"Guava"); dict.Add(5,"Kiwi");        Console.WriteLine("The dictionary elements are given as follows:");        foreach (KeyValuePair<int, string> i in dict)        {            Console.WriteLine("Key: {0}     Value: {1}", i.Key, i.Value);        }      }   } }

The output of the above program is as follows:

The dictionary elements are given as follows: Key: 1     Value: Apple Key: 2     Value: Mango Key: 3     Value: Orange Key: 4     Value: Guava Key: 5     Value: Kiwi
102.

What are Jagged Arrays in C#?

Answer»

Jagged arrays are arrays of arrays. The different arrays in a jagged array can be of many different sizes. The DECLARATION of elements in a jagged array are given as follows:

int[ ][ ] jaggedArr = new int [5][ ];

In the above initialization, the jagged array is jaggedArr. There are 5 elements in the jagged array and each of these elements are 1-D integer arrays.

A PROGRAM that demonstrates jagged arrays in C# is given as follows:

using System; namespace Demo {   class Example   {      STATIC void Main(string[] args)      {        int[][] jaggedArr = new int[5][];        jaggedArr[0] = new int[ ] { 8, 2, 5, 1 };        jaggedArr[1] = new int[ ] { 2, 4, 8 };        jaggedArr[2] = new int[ ] { 8, 4, 1, 9, 4};        jaggedArr[3] = new int[ ] { 7, 2 };        jaggedArr[4] = new int[ ] { 6, 1, 9, 5 };        for (int i = 0; i &LT; jaggedArr.Length; i++)        {            System.Console.Write("Element {0}: ", i);            for (int j = 0; j < jaggedArr[i].Length; j++)            {                System.Console.Write( jaggedArr[i][j] );                System.Console.Write(" ");            }            System.Console.WriteLine();                    }      }   } }

The OUTPUT of the above program is as follows:

Element 0: 8 2 5 1 Element 1: 2 4 8 Element 2: 8 4 1 9 4 Element 3: 7 2 Element 4: 6 1 9 5
103.

C++ vs C#

Answer»

C# and C++ are both object- oriented programming languages. C# is a general purpose object-oriented programming language with MULTIPLE features such as scalability support, garbage collection, type safety, easier type declarations etc.

Some of the differences between C++ and C# are given as follows:

C++
C#
C++ code can be created for any platform.
C# code is only targeted towards the Windows operating system.
C++ provides quite a fast performance.
The C# performance is slower as compared to C++.
Manual MEMORY management is USED in C++.
Automatic garbage collection is provided in C#.
Almost anything can be coded in C++ if the syntax is correct.
Anything that is not available in the .NET framework is difficult to implement in C# as it is dependent on the .NET framework.
A low level of abstraction is provided by C++.
A high level of abstraction is provided by C#.
C++ is a LIGHT language and can be easily compiled.

C# is interpreted into bytecode and then the Common Language Runtime manages the execution.
C++ is good for using in networking, server-side applications, gaming etc.
C# is good for creating MOBILE, desktop, web applications.
104.

Array vs ArrayList in C#

Answer»

Some of the major differences between an Array and an ARRAYLIST in C# are given as FOLLOWS:

Array
ArrayList
A group of similar type variables that can be referred by a common name is known as an Array.The ArrayList is a COLLECTION that implements the IList Interface and uses an array that is dynamic.
The System.Array namespace contains Arrays.
The System.Collection namespace contains ArrayList.
An Array cannot accept a NULL value.
An ArrayList can accept a null value.
An Array has a fixed SIZE and this size cannot be increased or decreased dynamically.
The size of an ArrayList can be increased or decreased dynamically.
An Array can store data of a single data type such as int, float, char etc.
An ArrayList can store data of different data types.
The insertion and deletion operation in an Array is quite fast.
The insertion and deletion operation in an ArrayList is slower as compared to an Array.
An Array is strongly typed.
An ArrayList is not strongly typed.

A program that demonstrates an Array and ArrayList in C# is given as follows:

using System; using System.Collections; namespace Demo {   class Example   {      static void Main(string[] args)      {         int[] arr = new int[5];         arr[0] = 4;         arr[1] = 7;         arr[2] = 3;         arr[3] = 9;         arr[4] = 1;         Console.Write("Array elements are: ");        for (int i = 0; i < arr.Length; i++)        {            Console.Write(arr[i] + " ");        }         ArrayList arrList = new ArrayList();         arrList.Add(5);         arrList.Add(1);         arrList.Add(9);         arrList.Add(7);         arrList.Add(4);         Console.Write("\nArrayList elements are: ");         foreach (int i in arrList)         {            Console.Write(i + " ");         }      }   } }

The output of the above program is given as follows:

Array elements are: 4 7 3 9 1 ArrayList elements are: 5 1 9 7 4
105.

What is the role of CLR in C#.NET?

Answer»

Common Language RUNTIME (CLR) is defined in the Common Language Infrastructure (CLI).

CLR is the VIRTUAL Machine component managing the execution of PROGRAMS written in languages using .NET Framework. Some of its examples include C#, F#, etc.

The .NET source code is compiled to Common Language Infrastructure (CLI). The code is executed at runtime after the CIL is converted to native code. This is DONE using JIT (Just-In-Compiler) compiler.

C# is designed for the Common Language Infrastructure (CLI), which describes executable code and runtime environment. This allows usage of MULTIPLE high-level languages on various computer platforms and architectures.

106.

How can we use Param Arrays in C#?

Answer»

If you are not sure of the parameters in the arrays, then you can use the param type arrays. The param arrays hold n number of parameters.

The following is an example:

using System; namespace Application {   class Example {      public int Display(PARAMS int[] a) {         int mul = 1;         foreach (int i in a) {            mul *= i;         }         RETURN mul;      }   }   class DEMO {      static void MAIN(string[] args) {         Example ex = new Example();         int mul = ex.Display(3, 4, 5);         Console.WriteLine("Result = {0}", mul);         Console.ReadKey();      }   } }

The OUTPUT:

Result = 60

Here is another example of param arrays in C#:

using System; namespace ArrayDemo {   class Example   {       static int SumOfElements(params int[] p_arr)        {            int sum=0;            foreach (int i in p_arr)            {               sum += i;            }            return sum;        }      static void Main(string[] args)      {            int sum=0;            sum = SumOfElements(4, 8, 7, 3, 1);            Console.WriteLine("Sum of 5 Parameters: {0}", sum);            sum = SumOfElements(5, 7);            Console.WriteLine("Sum of 2 Parameters: {0}", sum);            sum = SumOfElements(10, 7, 9);            Console.WriteLine("Sum of 3 Parameters: {0}", sum);      }   } }

The output of the above program is as follows:

Sum of 5 Parameters: 23 Sum of 2 Parameters: 12 Sum of 3 Parameters: 26
107.

Exception Handling Best Practices in C#

Answer»

The FOLLOWING are the best practices to handle exceptions in C#:

  • Avoid returning error code. Instead throw exceptions to display them completely.
  • Log the exceptions to a logging library. This is done to keep track of the exceptions occurred. Log it to a file using NLog, Serilog, etc.
  • Log exceptions centrally.
  • You can also log exceptions to the database.
  • View and search all exceptions across all applications.
  • While creating your own exception classes, it would be great if you can atleast the THREE common constructors.
  • Windows Event Log is for logging errors and other information from applications.
  • You need to ensure that the metadata for the exceptions is available to code that is executing remotely while creating user-defined exceptions.
  • View and search all exceptions across all servers.
  • Use the VISUAL Studio Debugger to view all exception.
  • Uniquely identify exceptions to easily BIFURCATE them.
108.

What is the base class for all data types in C#.NET?

Answer»

SYSTEM.Object class in the BASE class for all data types in C#.NET. All classes in the .NET Framework are derived from Object. The object types can be assigned values of any other types.

The following DISPLAYS object:

object ob; OBJ= 5;

Let us see an example of comparing objects:

using System; class Example {    static void MAIN()    {        object val = new Object();        Console.WriteLine(val.GetType());    } }

The output:

System.Object
109.

Role of “as” operator in C#

Answer»

The “as” operator in C# is SOMEWHAT similar to the “is” operator. HOWEVER, the “is” operator returns boolean values but the “as” operator returns the object types if they are compatible to the given type, otherwise it returns null.

In other words, it can be SAID that conversions between compatible types are PERFORMED using the “as” operator.

A program that demonstrates the ‘as’ operator in C# is given as follows:

namespace IsAndAsOperators {    CLASS A    {        public int a;    }    class B    {        public int x;        public double y;    }    class Program    {        static void Main(string[] args)        {            A obj1 = new A();            obj1.a = 9;            B obj2 = new B();            obj2.x = 7;            obj2.y = 3.5;            System.Console.WriteLine("The object obj1 is of class A? : {0}", func(obj1));            System.Console.WriteLine("The object obj2 is of class A? : {0}", func(obj2));        }        public static string func(dynamic obj)        {            A tempobj = obj as A;            if (tempobj != null)                return "This is an object of class A with value " + tempobj.a;                return "This is not an object of class A";                 }    } }

The output of the above program is given as follows:

The object obj1 is of class A? : This is an object of class A with value 9 The object obj2 is of class A? : This is not an object of class A
110.

How to empty an array in C#?

Answer»

An array can be emptied using the Array.Clear() method. This method sets the required range of the elements in the array to their default values where the array type may be integer, boolean, CLASS instances etc. To empty the whole array, the range of elements should simply be the length of the whole array.

A program that demonstrates the Array.Clear() method to empty the array is given as follows:

using SYSTEM; PUBLIC class Demo {    public static void Main()    {        int[] arr = new int[] {3, 9, 7, 1, 6};        Console.Write("The original integer array is: ");        foreach (int i in arr)        {            Console.Write(i + " ");        }        Array.Clear(arr, 0, arr.Length);        Console.Write("\nThe modified integer array is: ");        foreach (int i in arr)        {            Console.Write(i + " ");        }    } }

The output of the above program is given as follows:

The original integer array is: 3 9 7 1 6 The modified integer array is: 0 0 0 0 0
111.

What are class instances in C#?

Answer»

An object of a class is a class instance in C#. All the members of the class can be accessed USING the object or instance of the class.

The definition of the class instance starts with the class name that is followed by the name of the instance. Then the new OPERATOR is used to CREATE the new instance.

A program that demonstrates a class instance in C# is given as FOLLOWS:

using System; namespace Demo {   class Sum   {     private int x;     private int y;     public void value(int val1, int val2)     {         x = val1;         y = val2;     }     public int returnSum()     {         return x + y;     }    }    class Test    {      static void Main(string[] args)      {         Sum obj = new Sum();            obj.value(8, 5);         Console.WriteLine("The sum of 8 and 5 is: {0}" , obj.returnSum());      }    } }

The output of the above program is given as follows:

The sum of 8 and 5 is: 13
112.

Why is f required while declaring C# floats?

Answer»

It is a suffix set in C# that is used while DECLARING FLOAT. This is used to INFORM the COMPILER the type of the literal. An example:

float a = 1239f;
113.

Constant vs Readonly in C#

Answer»

The const in C# is faster than readonly, but the performance of const is not better than readonly.

  • Const

A value with const KEYWORD cannot change throughout the LIFE of a program.

A const variable cannot be reassigned.

  • Readonly

A value with Readonly keyword whose value can be initialized during runtime, unlike const.

Let us now see the DIFFERENCE:

Basis
ConstReadonly
Local VariableCan be applied to local variables.Cannot be applied to local variables
MemoryMemory is not allocated.Dynamic memory is allocated for readonly fields.
StaticConst are by-default staticTo make it class member, INCLUDE static keyword before readonly
Ref or outWe cannot pass const field as ref or out parameterThe readonly field can be passed as ref or out parameters in the constructor context.
FasterFaster than readonly.Readonly isn’t faster.
PerformancePerformance isn’t better than readonly.Performance is better than const.
114.

Features of C# 7

Answer»

C#7.3 is the current version of C#. It is a multi-paradigm, generic and OBJECT-oriented programming languages. The following are the features:

  • Positional Arguments

Named arguments can be followed by positional arguments.

Easily reassign ref local variables in C# 7.3

  • Stackalloc Arrays

Use initializers on stackalloc arrays.

  • Dispatch

Implement method dispatch on properties other than the object type.

  • Out Variables

A method’s out parameters can be defined directly in the method in C# 7.

  • Local Functions

You can define a FUNCTION within the scope of another function. This gets local variables into the scope.

  • Deconstruction

This includes deconstruction of tuples into separate variables and creating metadata for the names of tuple elements.

  • Dummy Variables

Discards are dummy variables intentionally unused in application code. The maintainability of the code and make its intent more clear.

  • Digit Separators

These are beneficial in grouping digits in large numeric literals. These provide great readability and no significant downside.

  • Binary Literals

These are literals in binary form. They are identical to hexadecimal literals except they use digits 0 and 1 with base 2. Binary literals are great for educational PURPOSES and are low cost implementations.