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.

51.

Scope of Variables in C#

Answer»

The scope of variables specifies the program parts where the variable is accessible. There are mainly three categories for the scope of variables. These are given as follows:

Class Level Scope

The variables with class level scope are accessible ANYWHERE in the class. These variables are those that were declared INSIDE the class but outside any method.

A program that demonstrates the variables with class level scope is given as follows:

using System; class A {    int a = 10;    public void printa()    {        Console.WriteLine("a = " + a);    } } class Demo {    public static void Main()    {        A obj = new A();        obj.printa();    } }

The output of the above program is as follows:

a=10

In the above program, the scope of the variable a is class level scope.

Method Level Scope

The variables with method level scope are accessible in the method only and not outside it. These variables are those that were declared inside the method.

A program that demonstrates the variables with method level scope is given as follows:

using System; class Demo {       public void printb()    {        int b = 20;        Console.WriteLine("b = " + b);    }    public static void Main()    {        Demo obj = new Demo();        obj.printb();    } }

The output of the above program is as follows:

b=20

In the above program, the scope of the variable b is method level scope.

Block Level Scope

The variables with block level scope are accessible in the block only and not outside it. These variables are normally declared in loops such as for loop, while loop etc.

A program that demonstrates the variables with block level scope is given as follows:

using System; class Demo {       public static void Main()    {        for (int i = 1; i <= 5; i++)        {            Console.Write(i + " ");        }    } }

The output of the above program is as follows:

1 2 3 4 5

In the above program, the scope of the variable i is block level scope as it is only accessible inside the for loop.

52.

How to check if a file exists in C#

Answer»

The File.EXISTS() method is used in C# to check if a file exists or not.

In the parameter, set the name and path of the file you want to check exist or not.

File.Exists(@"C:\One.txt")

The following is an example:

using SYSTEM; using System.IO; class Example {   STATIC void Main() {      if (File.Exists(@"C:\One.txt")) {         Console.WriteLine("File exists!");      } ELSE {         Console.WriteLine("File does not exist!");      }   } }

The output:

File foes not exist!
53.

Role of nameof keyword in C#

Answer»

The unqualified string name of a variable, MEMBER TYPE ETC. can be obtained using the nameof keyword. While renaming the definitions, the code can be kept valid using the nameof keyword. This is a compile-time feature.

A program that demonstrates the nameof keyword in C# is given as FOLLOWS:

using System; class Demo {    public static void Main()    {        int number = 60;        Console.WriteLine(nameof(number));        Console.WriteLine(number);        var FRUIT = "cherry";        Console.WriteLine(nameof(fruit));        Console.WriteLine(fruit);    } }

The output of the above program is as follows:

number 60 fruit cherry
54.

Why do we use Circular References in C#?

Answer»

Under CIRCULAR References, two or more RESOURCES CAUSES the lock condition. These resources are INTERDEPENDENT on each other and these are made UNUSABLE.

55.

How to check whether a file exist in C#?

Answer»

C# already provides Exists() method to CHECK the existence of a file in a directory. LET us see the code in C#

USING System; using System.IO; public class Example {    public static void Main()    {             if (File.Exists(@"C:\jacob.txt"))        {            Console.WriteLine("File do exist!");        }       ELSE        {            Console.WriteLine("File does not exist!");        }    } }
56.

Why index out of range exception occur in C#?

Answer»

IndexOutOfRangeException occurs when an element is tried to access with an index, which is outside the bounds of the array.

The following error MESSAGE is visible:

System.IndexOutOfRangeException: Index was outside the bounds of the array

An example displays the same exception that occurs because we are trying to access an element with an index outside the bounds of the array:

using System; namespace Example {   class One {      static void MAIN(string[] ARGS) {          try {                 int i;                 int [] val = new int[2] {97, 49};                 for (i = 0; i < 5; i++ ) {                    Console.WriteLine(val[i]);                 }           }           catch (System.IndexOutOfRangeException indexException)            {                Console.WriteLine(indexException);            }      }   } }

It displays the same error as output:

97 49 System.IndexOutOfRangeException: Index was outside the bounds of the array
57.

Convert a string to int in C#

Answer»

A string can be converted to an integer USING the int.TryParse() method. This method returns false if the string cannot be converted into an integer.

A program that demonstrates the int.TryParse() method to convert a string into int in C# is given as follows:

using System.IO; using System; class Demo {   public static void Main()   {      int num1, NUM2;      string str1 = "20";      string STR2 = "apple";      if (int.TryParse(str1, out num1))        Console.WriteLine("The string 1 in int form is: " + num1);      else        Console.WriteLine("String 1 could not be PARSED.");      if (int.TryParse(str2, out num2))        Console.WriteLine("The string 2 in int form is: " + num2);      else        Console.WriteLine("String 2 could not be parsed.");   } }

The output of the above program is given as follows:

The string 1 in int form is: 20 String 2 could not be parsed.

In the above program, the string str1 is converted into int and stored in num1. However, the string str2 cannot be converted into int as the string is not of a valid format.

58.

Check whether a node is in a Linked List or not

Answer»

To check whether a node is in a Linked List or not, the best way is to use the Contains() method.

The Contains() method has a parameter that is the value you are SEARCHING for in a Linked List:

Contains(Value)

The method RETURNS a Boolean Value. If a node is found in the Linked List, TRUE is returned.

Let us see an example:

using System; using System.Collections.Generic; CLASS Demo {    static VOID Main()    {        string [] devices = {"Smartphones","Smartwatches"};        LinkedList<string> myList = new LinkedList<string>(devices);                         foreach (var d in myList)          {            Console.WriteLine(d);          }        Console.WriteLine("Smartphones in the list?: "+myList.Contains("Smartphones"));    } }

The OUTPUT:

Smartphones Smartwatches Smartphones in the list?: True
59.

How to fetch the last 3 characters from a string in C#?

Answer»

To GET the last three characters, use the String Substring() method. The parameter to be set under it should be “Length - 3” i.e. the last three characters. A program that obtains the last 3 characters from a string is given as follows:

USING System; public class Demo { public static VOID Main() {     string STR = "This is an example";     string resultStr = str.Substring(str.Length - 3);     Console.WriteLine("Original string: {0}", str);     Console.WriteLine("Resultant string: {0}", resultStr); } }

The output of the above program is as follows:

Original string: This is an example Resultant string: ple
60.

Can I display multiline String in C#?

Answer»

Yes, in C#, you can easily display a MULTILINE string. For that, use @.

using SYSTEM; namespace Application {   class Example {      STATIC void Main(string[] args) {         string s = @"Jack,         What an amazing WORK         EFFICIENCY!";         Console.WriteLine("Multi-line string = "+s);      }   } }

The output:

Multi-line string = Jack,         What an amazing work         efficiency!
61.

What are the Built-in Exceptions in C#?

Answer»

Exceptions in C# are REPRESENTED by classes. The System.Exception class has all the classes to handle exceptions.

Let us see some of the classes under the System.Exception class:

  • System.IO.IOException: Handles I/O errors.
  • System.IndexOutOfRangeException: Handles errors generated when a method refers to an array index out of range.
  • System.ArrayTypeMismatchException: Handles errors generated when TYPE is mismatched with the array type.
  • System.NullReferenceException: Handles errors generated from referencing a null object.
  • System.DivideByZeroException: Handles errors generated from DIVIDING a dividend with zero.
  • System.InvalidCastException: Handles errors generated during typecasting.
  • System.OutOfMemoryException: Handles errors generated from insufficient free MEMORY.
62.

How to create a Quadruple Tuple in C#?

Answer»

To create a Quadruple TUPLE, you need to create a tuple with 4 items. The Tuple.Create() method is used for this purpose:

var t = Tuple.Create(5, 10, 15, 20);

The following is an EXAMPLE:

using System; public CLASS Example {   public static void MAIN() {      var t = Tuple.Create(5, 10, 15, 20);      Console.WriteLine("Item1 = "+ t.Item1);      Console.WriteLine("Item2 = "+ t.Item2);      Console.WriteLine("Item3 = "+ t.Item3);      Console.WriteLine("Item4 = "+ t.Item4);   } }

The output:

Item1 = 100 Item2 = 200 Item3 = 300 Item4 = 400
63.

Dispose() vs finalize() methods in C#?

Answer»

The dispose() method is called to free unmanaged resources. An example of these resources is FILES. However, finalize() method called by GARBAGE collector to free unmanaged resources. An example of these resource is files. The dispose() method is called IMPLICITLY, whereas the finalize() method called explicitly.

64.

How to set 5-item tuple in C#?

Answer»

To set 5-item tuple in C#, set it like this:

var t = new Tuple&LT;string, string[], int, int, int&GT;("laptop",      new string[] { "memoy CARD", "pen drive" },      30,      40,      50);

Above, the tuple has string, string array, and three integer tuples. Therefore, MAKING it a 5-item tuple.

The following is an example:

using System; class Example {   STATIC void Main() {      var t = new Tuple<string, string[], int, int, int>("laptop",      new string[] { "memoy card", "pen drive" },      30,      40,      50);      Console.WriteLine("Tuple Item 1 = "+t.Item1);      Console.WriteLine("Tuple Item 4 = "+t.Item4);      Console.WriteLine("Tuple Item 5 = "+t.Item5);   } }

The output:

Tuple Item 1 = laptop Tuple Item 4 = 40 Tuple Item 5 = 50
65.

Can we display all the files in the Directory in C#?

Answer»

Yes, we can display all the files in a specific DIRECTORY in C#. We have to use the DirectoryInfo class. Within that set the directory from where you WANT to fetch all the files:

DirectoryInfo d = new DirectoryInfo(@"D:\SID");

The GetFiles() method is then used to get all the files in an array:

FileInfo [] fileInfo = d.GetFiles(); foreach (FileInfo f in fileInfo) {   Console.WriteLine("File Name: ", f.Name); }

The following is an example:

using SYSTEM; using System.IO; namespace Application {   class Example {      static void Main(string[] args) {         DirectoryInfo d = new DirectoryInfo(@"D:\sid");         FileInfo [] fileInfo = d.GetFiles();         foreach (FileInfo f in fileInfo) {            Console.WriteLine("File Name: ", f.Name);         }         Console.ReadKey();      }   } }

The output displays the files in the “sid” directory:

NewOne NewTwo NewThree NewFour
66.

Ref vs Out Keyword in C#

Answer»

Before passing a ref parameter, you must assign it to a value. However, before passing an out parameter, you don't need to assign it to a value.

  • Ref Parameter

A reference to a memory location of a variable. DECLARE the reference parameters using the ref keyword. A ref parameter is passed as a reference, not a value.

  • Out Parameter

With the out parameter, you can return two values from a function.

The following is an example of ref parameter:

using System; class Example {    static void Main()    {        string str1 = "one";        string str2 = "two";        string str3 = "three";        DISPLAY(ref str1);        Display(ref str2);        Display(ref str3);        Console.WriteLine(str1);        Console.WriteLine(str2);        Console.WriteLine(str3);    }    static void Display(ref string a)    {        if (a == "two")        {            a = null;        }        if (a == "three")        {            a = null;        }    } }

The output:

one

The following is an example of out parameter:

using System; class Example {    static bool DEMO(out int a)    {        a = 5;        return a >= 5;    }    static void Main()    {        if (Demo(out int a))        {            Console.WriteLine(a);        }    } }

The output WOULD be visible correctly on .NET 4.7 and above:

5
67.

Managed and Unmanaged code in C#

Answer»

Managed Code is managed by the CLR. The managed code compiles into MACHINE code. Applications under the CONTROL of CLR is managed code.

The code outside the .NET Framework is CALLED UNMANAGED code. Wrapper classes are used to execute the unmanaged code. Applications not under the control of CLR is managed code.

The unmanaged code is the unsafe code that use a pointer variable.

68.

How to create a tuple with string and int items in C#

Answer»

Creating a tuple with STRING and INT items:

Tuple<int, string&GT; t = new Tuple<int, string>(100, "john");

The following is an example:

using System; class Example {    STATIC void Main()    {        Tuple<int, string> t = new Tuple<int, string>(100, "john");        if (t.Item1 == 100)        {            Console.WriteLine(t.Item1);        }        if (t.Item2 == "john")        {            Console.WriteLine(t.Item2);        }    } }

The output:

100 John
69.

What is difference between Class and Struct?

Answer»
  • Class

A class is a user-defined blueprint or PROTOTYPE from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit.

Example:

public class Author { // Data members of class public string name; public string language; public int article_no; public int improv_no; // Method of class public void Details(string name, string language, int article_no, int improv_no) { this.name = name; this.language = language; this.article_no = article_no; this.improv_no = improv_no; Console.WriteLine("The name of the author is : " + name + "\nThe name of language is : " + language + "\nTotal number of article published " + article_no + "\nTotal number of Improvements:" +" done by author is : " + improv_no); } }
  • Structure

A structure is a collection of variables of different data TYPES under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types.

// Defining structure public struct Car { // Declaring different data types public string BRAND; public string Model; public string Color; }

Difference between Class and Structure

ClassStructure
Classes are of reference types.Structs are of value types
All the reference types are allocated on heap memory.All the value types are allocated on STACK memory.
Allocation of LARGE reference type is cheaper than allocation of large value type.Allocation and de-allocation is cheaper in value type as compare to reference type.
Class has limitless features.Struct has limited features.
Classes can contain constructor or destructor.Structure does not contain constructor or destructor.
Classes used new keyword for creating instances.Struct can create an instance, without new keyword
A Class can inherit from another classA Struct is not allowed to inherit from another struct or class
Function member of the class can be virtual or abstract.Function member of the struct cannot be virtual or abstract.
Two variable of class can contain the reference of the same object and any operation on one variable can affect another variable.Each variable in struct contains its own copy of data(except in ref and out parameter variable) and any operation on one variable can not effect another variable.
70.

What is Data Reader and how we bind data to DataReader?

Answer»

DataReader Object in ADO.NET is a stream-based , forward-only, read-only retrieval of query results from the Data Sources , which do not update the data. The DataReader cannot be created directly from code, they can created only by calling the EXECUTEREADER method of a Command Object.

SqlDataReader sqlReader = sqlCmd.ExecuteReader();

The DataReader Object provides a connection oriented data access to the Data Sources. A Connection Object can contain only one DataReader at a time and the connection in the DataReader REMAINS open, also it cannot be used for any other purpose while data is being accessed. When we started to read from a DataReader it should always be open and POSITIONED prior to the first record. The Read() method in the DataReader is used to read the rows from DataReader and it always moves forward to a new valid row, if any row exist .

DataReader.Raed();

Below is the sample code on how to bind data to DataReader:

public partial class Form1 : Form    {        public Form1()        {            INITIALIZECOMPONENT();        }        private void button1_Click(object sender, EventArgs e)        {            string connetionString = null;            SqlConnection sqlCnn ;            SqlCommand sqlCmd ;            string sql = null;            connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;USER ID=UserName;Password=Password";            sql = "Your SQL Statement Here , like Select * from product";            sqlCnn = new SqlConnection(connetionString);            try            {                sqlCnn.Open();                sqlCmd = new SqlCommand(sql, sqlCnn);                SqlDataReader sqlReader = sqlCmd.ExecuteReader();                while (sqlReader.Read())                {                    MessageBox.Show(sqlReader.GetValue(0) + " - " + sqlReader.GetValue(1) + " - " + sqlReader.GetValue(2));                }                sqlReader.Close();                sqlCmd.Dispose();                sqlCnn.Close();            }            catch (Exception ex)            {                MessageBox.Show("Can not open connection ! ");            }        }    }
71.

What is Reflection?

Answer»

Reflection is a process by which a computer program can monitor and modify its own structure and behavior. It is a way to explore the structure of assemblies at run time (CLASSES, resources, methods). Reflection is the capability to find out the information about objects, metadata, and application details (assemblies) at run-time. We need to INCLUDE System.Reflection namespace to perform reflections in C#.

Exmaple:

PUBLIC class MyClass {    public virtual int Add(int numb1, int numb2)    {                     return numb1 + numb2;    }    public virtual int Subtract(int numb1, int numb2)    {        return numb1 - numb2;    } } static void Main(string[] args) {    MyClass oMyClass = new MyClass();    //Type information.    Type oMyType = oMyClass.GetType();    //Method information.    MethodInfo oMyMethodInfo = oMyType.GetMethod("Subtract");    Console.WriteLine("\nType information:" + oMyType.FullName);    Console.WriteLine("\nMethod info:" + oMyMethodInfo.Name);                Console.Read(); }

Why we need Reflection

We need reflection for the following purposes:

  • To view attribute information at run time
  • To view the structure of assemblies at run time (classes, resources, methods)
  • It ALLOWS dynamic/late BINDING to methods and properties
  • In serialization, it is used to serialize and de-serialize objects
  • In web service, it is used to create and consume SOAP messages and also to generate     WSDL
  • Debugging tools can use reflection to examine the state of an object
72.

What is the difference between ByRef and ByVal?

Answer»
  • ByVal

ByVal means passing direct value to the method, which means that any change to that parameter that TAKES place inside that method have no affect on ORIGINAL data stored in ARGUMENT variable.

  • ByRef

ByRef VARIABLES does not contains the data directly, it contains a reference to its data, so if the value is changed inside the method, then the same reflects in the argument variable.

73.

What is the difference between compile time polymorphism and run-time polymorphism?

Answer»

Compile time POLYMORPHISM MEANS we will declare methods with same NAME but different signatures because of this we will perform different tasks with same method name. This compile time polymorphism also called as early binding or method overloading

What is the difference between compile time polymorphism and run-time polymorphism?

Example: 

public class MyClass   {    public int Add(int a, int b)    {      return a + b;    }  public int Add(int a, int b, int c)    {      return a + b + c;    } }

Run time polymorphism also called as late binding or method overriding or DYNAMIC polymorphism. Run time polymorphism or method overriding means same method names with same signatures.

In this run time polymorphism or method overriding we can override a method in base class by creating similar function in derived class this can be achieved by using inheritance principle and using “virtual & override” keywords.

Example: 

public class Bclass { public virtual void Sample1() { Console.WriteLine("Base Class"); } } public class DClass : Bclass { public override void Sample1() { Console.WriteLine("Derived Class"); } } class Program { static void Main(string[] args) { DClass objDc = NEW DClass(); objDc.Sample1(); Bclass objBc = new DClass(); objBc.Sample1(); } }
74.

UnionWith() method in C#

Answer»

The UnionWith() method is used to get the union of two collections. This MEANS that all the elements in both the collections are displayed without any duplicates using the UnionWith() method.

A program that demonstrates the UnionWith() method using two DICTIONARIES is given as follows:

using System; using System.Collections.Generic; public class Program {   public static void Main()   {      Dictionary < string, int > D1 = new Dictionary < string, int > ();      d1.Add("Apple", 1);      d1.Add("MANGO", 2);      d1.Add("Guava", 3);      Dictionary < string, int > d2 = new Dictionary < string, int > ();      d2.Add("Peach", 4);      d2.Add("Apple", 5);      HashSet < string > h = new HashSet  <string > (d1.Keys);      h.UnionWith(d2.Keys);      Console.WriteLine("The union of two Dictionaries is:");      foreach(string i in h)      {         Console.WriteLine(i);      }   } }

The output of the above program is as follows:

The union of two Dictionaries is: Apple Mango Guava Peach
75.

What are virtual functions in C#?

Answer»

A virtual function is redefined in derived classes. It is usually used when more than the basic functionality of the function is required in the derived classes. So the virtual function has an implementation in the base class as well as in the derived classes as well. The virtual modifier cannot be used with the abstract, static, private and override modifiers.

The virtual keyword is used in the base class to CREATE a virtual function. The override keyword is used in the derived classes to override the function.

A program that demonstrates virtual FUNCTIONS in C# is given as follows:

using System; namespace Demo {    class Shape    {      public virtual double area()      {          return 0;      }    }    class Square: Shape    {      private double side;      public Square( double s)      {         side = s;      }      public override double area ()      {         return (side * side);      }    }     class Rectangle: Shape    {      private double length;      private double breath;      public Rectangle( double l, double b)      {         length = l;         breath = b;      }      public override double area ()      {         return (length * breath);      }   }       class Circle: Shape    {      private double RADIUS;      public Circle( double R)      {         radius = r;      }      public override double area ()      {         return (3.14 * radius * radius);      }    }    class Test    {      static void MAIN(string[] args)      {         Square s = new Square(3.5);         Console.WriteLine("Area of Square = {0}", s.area());         Rectangle r = new Rectangle(7.0, 2.0);         Console.WriteLine("Area of Rectangle = {0}", r.area());         Circle c = new Circle(4.0);         Console.WriteLine("Area of Circle = {0}", c.area());      }    } }

The output of the above program is as follows:

Area of Square = 12.25 Area of Rectangle = 14 Area of Circle = 50.24
76.

Why to use #region directive in C#?

Answer»

The #region direction in C# ALLOWS you to specify a BLOCK of code that can be EXPANDED and collapsed.

You can easily use it to collapse or hide regions. This can be DONE to focus only on the sections of the code you are working on.

77.

Why Nullables are used in C#?

Answer»

Nullable are special data types that can be assigned normal data VALUES and null values as well. For example: Nullable<Int32> can be assigned an integer value and it can also be assigned null.

The syntax for a nullable declaration in C# is given as follows:

DataType? NameOfVariable = DataValue;

In the above syntax, DataType is the data type such as int,char, float ETC. followed by ?. NameOfVariable is the variable name and the DataValue is the value assigned to the variable which can be null or any value of the specified data type.

A program that demonstrates Nullables in C# is given as follows:

using SYSTEM; namespace DEMO {   class Example   {      static void Main(string[] args)      {         int? NUM1 = 4;         int? num2 = null;         Console.WriteLine("Value of num1 is: {0}", num1);         Console.WriteLine("Value of num2 is: {0}", num2);      }   } }

The output of the above program is as follows:

Value of num1 is: 4 Value of num2 is:
78.

Usage of HashTable Collections in C#

Answer»

The HashTable Collection in C# is a collection of key-value pairs. These pairs are organised using the hash code of the KEYS. This means that when the elements need to be accessed in the HashTable, this can be DONE using keys.

A program that demonstrates the HashTable Collection in C# is given as follows:

using System; using System.Collections; namespace Demo {   class Program   {      static void Main(string[] args)      {         Hashtable h = new Hashtable();         h.Add("1", "Apple");         h.Add("2", "Mango");         h.Add("3", "Orange");         h.Add("4", "Guava");         h.Add("5", "Peach");         h.Add("6", "Melon");         h.Add("7", "Lychee");         h.Add("8", "Cherry");         ICollection allKeys = h.Keys;         foreach (string key in allKeys)         {            Console.WriteLine(key + ": " + h[key]);         }      }   } }

The output of the above program is given as follows:

1: Apple 6: Melon 7: Lychee 4: Guava 5: Peach 8: Cherry 2: Mango 3: Orange
79.

Accessibility Modifiers in C#

Answer»

The ACCESSIBILITY of a member or a TYPE is specified using ACCESS modifiers. The four main access modifiers are given as follows:

1. public

The members that are public can be accessed without restrictions. So this is the most permissive accessibility modifier.

2. protected

The members that are protected can be accessed in the class in which they were declared or from any derived classes that were derived from the class that declared the member in question.

3. internal

The members that are internal can only be accessed from the files that are in the same assembly. Any class or a class member can be declared as internal.

4. private

The members that are private can only be accessed in the class or structure in which they were declared and not outside. So, this is the LEAST permissive accessibility modifier.

There are six accessibility levels that can be specified from the above access modifiers. These are given as follows:

  • public

There is unrestricted access.

  • protected

The access is restricted to the containing class or the various classes and types that are derived from the containing class.

  • internal

The access is restricted to the files that are in the same assembly.

  • protected internal

The access is restricted to the various classes and types that are derived from the containing class and the files that are in the same assembly.

  • private

The access is restricted to the containing class or type.

  • private protected

The access is restricted to the containing class and types that are derived from the containing class in the same assembly.

80.

What are Chained Exceptions in C#?

Answer»

A chain of try-catch statements to HANDLE exceptions are CHAINED Exceptions in C#. To CREATE a chain of exceptions i.e. chained exceptions:

81.

Which class acts as a base class for all exceptions in C#?

Answer»

The base class for all exceptions is the System.EXCEPTION class. All of the exception CLASSES in C# are mainly derived from the System.Exception class whether DIRECTLY or INDIRECTLY. Some of the classes that are derived from the System.Exception class are System.ApplicationException and System.SystemException classes.

A program that demonstrates exception handling in C# is given as follows:

using System; namespace Demo {   class Program   {      static void Main(string[] args)      {          int ans = 0;          int num1 = 17;          int num2 = 0;          try         {            ans = num1 / num2;         }         catch (DivideByZeroException)         {            Console.WriteLine("An Exception Occured");         }         finally         {            Console.WriteLine("Answer: {0}", ans);         }      }   } }

The OUTPUT of the above program is given as follows:

An Exception Occured Answer: 0
82.

What are the main parts of a C# program?

Answer»

The MAIN parts of a C# program are given as follows:

  1. Namespace declaration
  2. Class
  3. Class methods
  4. Class attributes
  5. Main method
  6. Expressions and statements
  7. Comments

A BASIC program that DEMONSTRATES all these parts is given as follows:

using System; namespace Demo {   class Program   {      static void Main(string[] args)      {         // This program finds the sum of two NUMBERS         int a = 5, b = 9, c;         c = a + b;         Console.WriteLine("Sum of {0} and {1} is {2}", a, b, c);      }   } }

The output of the above program is given as follows:

Sum of 5 and 9 is 14

Now, the various parts of the program are explained as follows:

  1. The System namespace is included in the above program with the using keyword.
  2. Then a namespace Demo is declared.
  3. Next, the class Program is declared.
  4. After that the Main() method is provided. This method is the entry point of all the C# programs.
  5. In the Main() method, a comment is provided. This is ignored by the compiler.
  6. After that, there are various statements that find the sum of two numbers.
  7. Then the sum is printed using the Console.WriteLine().
83.

MultiLevel Inheritance in C#

Answer»

The functionality of a class can be inherited by another class USING inheritance. The original class is known as the base class and the class which inherits the functionality of the base class is known as the derived class.

Multilevel inheritance involves a class that inherits from a derived class. This derived class may have inherited from the base class or from another derived class and so on.

A PROGRAM that demonstrates multilevel inheritance in C# is given as follows:

using System; namespace Demo {     class ClassX     {         public INT x;         public ClassX()         {            x = 23;         }     }     class ClassY: ClassX     {         public int y;         public ClassY()         {             y = 91;         }     }      class ClassZ: ClassY     {         public int z;         public ClassZ()         {             z = 67;         }     }    class Test    {      static void Main(string[] args)      {         ClassZ OBJ = new ClassZ();         Console.WriteLine("x = {0}", obj.x);         Console.WriteLine("y = {0}", obj.y);         Console.WriteLine("z = {0}", obj.z);      }    } }

The output of the above program is as follows:

x = 23 y = 91 z = 67
84.

Abstraction in C#

Answer»

Abstraction means that only the information required is visible to the USER and the rest of the information is hidden from the user. This is an important part of object-oriented programming.

Abstract classes are used to implement abstraction in C#. Abstract classes are base classes that have a partial implementation. These classes have abstract methods that are inherited by other classes that provide more functionality to the methods.

A PROGRAM that demonstrates abstraction is given as follows:

using System; namespace Demo {    abstract class Shape    {      public abstract double AREA();    }    class Rectangle: Shape    {      private double length;      private double breath;      public Rectangle( double l, double b)      {         length = l;         breath = b;      }      public override double area ()      {         return (length*breath);      }    }     class Triangle: Shape    {      private double baseT;      private double heightT;      public Triangle( double b, double h)      {         baseT = b;         heightT = h;      }      public override double area ()      {         return (0.5*baseT*heightT);      }   }    class Test    {      static VOID Main(string[] args)      {         Rectangle r = new Rectangle(8.0, 3.0);         Console.WriteLine("Area of Rectangle = {0}", r.area());         Triangle t = new Triangle(2.0, 5.0);         Console.WriteLine("Area of Triangle = {0}", t.area());      }    } }

The output of the above program is as follows:

Area of Rectangle = 24 Area of Triangle = 5
85.

What is an object in C#?

Answer»

An object in C# is a dynamically created instance of the class that is also known as a RUNTIME entity since it is created at runtime. All the members of the class can be accessed using the object.

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

The syntax of the object definition is given as follows:

ClassName ObjectName = new ClassName();

In the above syntax, ClassName is the name of the class followed by the ObjectName which is the name of the object.

A program that demonstrates an object in C# is given as follows:

using System; NAMESPACE DEMO {   class Product   {     private int x;     private int y;     public void value(int val1, int val2)     {         x = val1;         y = val2;     }     public int returnProduct()     {         return x * y;     }    }    class Test    {      static void Main(string[] args)      {         Product obj = new Product();            obj.value(7, 3);         Console.WriteLine("The product of 7 and 3 is: {0}" , obj.returnProduct());      }    } }

The output of the above program is given as follows:

The product of 7 and 3 is: 21
86.

C# vs Java

Answer»

C# and Java are both general purpose programming languages. There are a lot of similarities as well as differences between these TWO languages and so choosing the correct LANGUAGE depends on the programmer’s need.

Differences between C# and Java

Some of the differences between C# are Java are GIVEN as follows:

  1. C# is a part of the Microsoft .NET framework and is used to develop for Microsoft platforms. Java is designed by Sun Microsystems and is widely used in open-source projects.
  2. C# uses type safe METHOD pointers known as delegates that are used to implement event handling. Java does not contain the concept of delegates.
  3. Generics are implemented in the CLI in C# and the type information is available at runtime. Java implements generics using erasures.
  4. Common Language Runtime is used in C# while Java uses Java Virtual Machine.
  5. The enum is a list of NAMED constants in C#. In Java, enum is the named instance of a type.
  6. The concept of class properties is only used in C# and is not supported in Java.
  7. The switch operator in C# supports string as well as constant types. On the other hand, the switch operator in Java refers to the integral or enumerated type.
  8. Operator overloading is supported in C# while it is is not supported in Java.
  9. Polymorphism is implemented in C# by using the virtual and override keywords in base class and derived class. Java implements polymorphism by default.
87.

Need of C#

Answer»

C# is a general-purpose OBJECT-oriented programming language which contains multiple PARADIGMS. There are various reasons why C# is needed as a programming language..

Some of these are given as follows:

1. Object Oriented Language

C# is an object-oriented language so the development is easier if there are LONG codes in large projects as compared to procedure-oriented programming languages.

2. Popularity

C# is arguably one of the most popular languages in modern times. It is used for web development, mobile development etc. Also, UWP, WPF, WinForms etc. can be used to create various Windows applications. Moreover, various applications such as Android, IOS apps can be built using the C# mobile development.

3. Structured programming language

The programs in C# can be broken into smaller parts using functions and thus structured. This makes the program easier to understand and makes C# a structured programming language.

4. Ease of Learning

C# is easy to learn and can also be easily understood. It can be mastered in a relatively short time. This is even more true for those who already have some experience with programming languages.

5. Scalable language

C# is an automatically scalable as well as updatable language. This means that the old files are regularly updated and replaced with new ones.

88.

Why do we use #warning directives in C#?

Answer»

The #warning DIRECTIVE generates a level one warning from a PARTICULAR location in the code. An example is displayed here:

USING System;

namespace Example { class One { public static void Main(string[] ARGS) { #if (!A)     #warning A is undefined #endif     Console.WriteLine("A warning..."); } } }
89.

Why do we use #error directives in C#?

Answer»

The #error directive is used in C# to GENERATE an error from a particular location in the code.

An example DISPLAYS the same:

using System; namespace Example { CLASS Demo { public static VOID Main(string[] args) { #if (!A)    #error A is undefined #endif Console.WriteLine("A custom error!"); } } }
90.

How to compare two arrays in C#

Answer»

Two arrays can be COMPARED USING the SequenceEqual() method in C#. This method returns TRUE if the two arrays are exactly the same i.e. if they are equal. Otherwise it returns false.

A program that demonstrates the comparison of two arrays using the SequenceEqual() method in C# is given as FOLLOWS:

using System; using System.Linq; namespace Demo {   public class Program   {      public STATIC void Main(string[] args)      {        int[] arr1 = new int[] {9, 5, 1, 7, 3};        int[] arr2 = new int[] {9, 5, 1, 7, 3};        Console.Write("Array 1: ");        foreach(int i in arr1)        {            Console.Write(i + " ");        }        Console.Write("\nArray 2: ");        foreach(int i in arr2)        {            Console.Write(i + " ");        }        Console.Write("\nBoth arrays are equal? " + arr1.SequenceEqual(arr2));      }   } }

The output of the above program is given as follows:

Array 1: 9 5 1 7 3 Array 2: 9 5 1 7 3 Both arrays are equal? True
91.

How to work with Interfaces in C#

Answer»

The definitions for different functionalities that classes can inherit are contained in INTERFACES in C#. All the interface members are only declared in the interface and they need to be defined in the class that derives them.

The keyword interface is used for interface definition. Usually the interface names BEGIN with a capital I because of common convention. Since multiple inheritance is not allowed in C#, interfaces are quite useful when a class needs to inherit functionalities from multiple sources.

A program that demonstrates working with interfaces in C# is given as follows:

using System; namespace Demo {    public interface IEmployee    {      void display();    }    public class Employee: IEmployee    {        private int empno;        private string name;        public Employee(int e, string n)        {            empno = e;            name = n;        }        public void display()        {            Console.WriteLine("Employee Number = {0}", empno);            Console.WriteLine("Name = {0}", name);            Console.WriteLine();        }    }    class Test    {      static void MAIN(string[] args)      {         Employee e1 = new Employee(101, "James");         Employee e2 = new Employee(102, "Susan");         Employee e3 = new Employee(103, "Bella");         e1.display();         e2.display();         e3.display();      }    } }

The output of the above program is given as follows:

Employee Number = 101 Name = James Employee Number = 102 Name = Susan Employee Number = 103 Name = Bella
92.

How to use ‘is’ operator in C#?

Answer»

The ‘is’ operator in C# is used to check if the given object is compatible with the given TYPE DYNAMICALLY. This operator returns true if the object is compatible with the type and false otherwise i.e. it returns boolean VALUES. If there are null objects, then ‘is’ operator returns false.

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

namespace Demo {    class A    {        public int a;    }    class B    {        public int b;    }    class Program    {        public static void Main(string[] args)        {            A obj1 = NEW A();            obj1.a = 5;            B obj2 = new B();            obj2.b = 9;            bool flag1 = (obj1 is A);            System.Console.WriteLine("The object obj1 is of class A ? " + flag1.ToString());            bool flag2 = (obj2 is A);            System.Console.WriteLine("The object obj2 is of class A ? " + flag2.ToString());        }    } }

The output of the above program is given as follows:

The object obj1 is of class A ? True The object obj2 is of class A ? False
93.

Check whether a list is empty or not in C#

Answer»

The Count property can be used to check if a list is empty or not. This property GETS the number of elements in the list. So, if the Count property gives 0 for a list, this means that the list is empty.

A program that checks if the list is empty or not using the Count property in C# is given as follows:

using System; using System.Collections.Generic; CLASS Demo {    public static void Main()    {        List<INT> list1 = new List<int>();        List<int> list2 = new List<int>();        list1.Add(7);        list1.Add(1);        list1.Add(5);        list1.Add(9);        list1.Add(3);        if (list1.Count == 0)        {            Console.WriteLine("List 1 is empty");        }        else        {            Console.WriteLine("The elements in List 1 are:");            foreach (int i in list1)            {                Console.WriteLine(i);            }        }        if (list2.Count == 0)        {            Console.WriteLine("List 2 is empty");        }        else        {            Console.WriteLine("The elements in List 2 are:");            foreach (int i in list2)            {                Console.WriteLine(i);            }        }    } }

The output of the above program is as follows:

The elements in List 1 are: 7 1 5 9 3 List 2 is empty

In the above program, if the list is empty then that is printed. Otherwise all the list elements are printed.

94.

Role of “this” in C#

Answer»

The current instance of the class is REFERRED using the “this” keyword. Also “this” keyword can be used to access data members from constructors, instance methods etc. Another CONSTRUCTOR can also be called from a constructor in the same class using the “this” keyword.

A program that demonstrates the usage of the “this” keyword in C# is given as follows:

using SYSTEM; namespace Demo {  class Student  {    private int rollNo;    private string name;      PUBLIC Student(int rollNo, string name)    {         this.rollNo = rollNo;         this.name = name;      }    public int returnRollNo()    {        RETURN rollNo;    }    public string returnName()    {        return name;    } } class program {      public static void Main()    {        Student s = new Student(1202, "Harry Smith");        Console.WriteLine("Roll Number: " + s.returnRollNo());        Console.WriteLine("Name: " + s.returnName());    } } }

The output of the above program is as follows:

Roll Number: 1202 Name: Harry Smith
95.

How to iterate over a dictionary 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.

The FOREACH loop can be used to iterate over the dictionary in C#. A program that demonstrates this 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,"James"); dict.Add(2,"Amy"); dict.Add(3,"Adam"); dict.Add(4,"Peter"); dict.Add(5,"Susan");        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: James Key: 2     Value: Amy Key: 3     Value: Adam Key: 4     Value: Peter Key: 5     Value: Susan
96.

States of a Thread in C#

Answer»

The thread life cycle in Java CONTAINS 5 states and the thread can be in any of these 5 states at a given time. These 5 states constitute the thread life cycle and this life cycle is started when an instance of the CLASS System.Threading.Thread is created.

The 5 states in a thread life cycle are:

1. Unstarted

When an instance of the thread class has been created, then the thread is in the unstarted state.

2. Runnable

When the start() METHOD is called but the thread SCHEDULER has not selected the thread for execution, at that time the thread is in the runnable state.

3. Running

If the thread scheduler has selected a thread and it is currently running, then it is in the running state.

4. Blocked (Non-runnable)

When a thread is not eligible to run but still ALIVE, then it is in the blocked state.

5. Terminated

The thread is in the terminated state after it has completed its execution.

97.

Late Binding vs Early Binding in C#

Answer»

Details about Late Binding as well as Early Binding are given as follows:

  • Early Binding

The linking of a function with an object during compile TIME is HANDLED by early binding. Function overloading and operator overloading are the two main techniques that implement early binding.

  • Function Overloading

There are multiple definitions for the same function name in function overloading. All these definitions can differ by the number of arguments they contain or the TYPE of these arguments. The number and type of arguments passed are checked by the compiler at the compile time and on that basis a function is called. If there is no function that matches the parameter list at compile time, then an error is produced.

  • Operator Overloading

Many of the operators in C# can be overloaded such as unary operators (+, -, !, ++, --) , binary operators(+, -, *, /, %) etc. The functions that contain the keyword operator before the operator that is being overloaded are overloaded operators.

  • Late Binding

The linking of a function with an object during run time is handled by late binding. Late binding is implemented using abstract classes and virtual functions.

  • Abstract Classes

The base classes with PARTIAL implementation are known as abstract classes. These classes have virtual functions that are inherited by other classes to PROVIDE more functionality. The abstract methods in the abstract classes are implemented only in the derived classes. Also abstract classes cannot be instantiated.

  • Virtual Functions

Virtual functions are implemented in a different manner for different inherited classes i.e. they are redefined for the derived classes. The call to these virtual functions is decided at run time.

98.

Why Reflection introduced in C#?

Answer»

Reflection provides METADATA information on types, modules, assemblies etc. at runtime. It is also useful in MULTIPLE situations and this is the reason it was introduced in C#.

Some of the situations when reflections are useful in C# are given as follows:

  1. For late binding to methods and properties, reflections are quite useful.
  2. Types can be examined and instantiated in an assembly using Reflection.
  3. New types can be created at runtime using Reflections.
  4. Reflection can be used with the program metadata attributes.

A program that demonstrates the usage of System.Reflection using the GetType() METHOD in C# is given as follows:

using System;   using System.Reflection;   public class Demo   {      public static void Main()      {        TYPE type1 = typeof(object[]);        Type type2 = "this is a string".GetType();        Type type3 = 50.GetType();          Console.WriteLine(type1);        Console.WriteLine(type1.Name);        Console.WriteLine(type2);        Console.WriteLine(type2.Name);        Console.WriteLine(type3);          Console.WriteLine(type3.Name);    } }

The output of the above program is as follows:

System.Object[] Object[] System.String String System.Int32 Int32
99.

Difference between a class and structure in C#

Answer»

A class is a DATA structure in C# that combines data variables as well as functions into a single unit. Instances of the class are known as objects. The keyword class is used to create the classes.

A structure is a data structure in C# that combines different data variables into a single unit. The keyword struct is used to create the structures. Structures are similar to classes but can be called as lighter versions of them.

Some of the differences between classes and structures are given as follows:

Classes
Structures
Classes are data structures that combine data variables as well as functions into a single unit.
Structures are data structures that combine different data variables into a single unit.
There is support for inheritance in classes.
There is no support for inheritance in structures.
Classes support constructors and can have default constructors, parameterized constructors, copy constructors etc
Structures have default and non PARAMETER constructors that can be replaced by the user
Classes are STORED on a heap.
Structures are EITHER stored in a stack or they are inline.
Classes require the new OPERATOR for instantiation.
Structurescan be instantiated without using the new operator.
Classes are a data type in C# that are of reference type.
Structures are a data type in C# that are of value type.
Classes are used for complex data or data that is intended to be modified after the class is created.
Structures are used for small data that is not intended to be modified after the structure is created.
There are abstract classes that are used in inheritance.
There cannot be abstract structures.
100.

What is a BitArray class in C#?

Answer»

The BitArray class in C# manages a COMPACT array of BIT VALUES which are represented as boolean values where true indicates 1 (the bit is on) and false indicates 0(the bit is off).

The BitArray class is usually used if the number of bits that need to be used are not known in advance but bits are required. The bits are indexed using an integer index that STARTS from 0 and can be accessed using this index.

A program that demonstrates the BitArray class in C# is given as follows:

using System; using System.Collections; namespace BitArrayDemo {   class Example   {      static void Main(string[] args)      {        BitArray ba1 = new BitArray(5);        BitArray BA2 = new BitArray(5);        ba1.Set(0, true);        ba1.Set(1, true);        ba1.Set(2, false);        ba1.Set(3, true);        ba1.Set(4, false);        ba2.Set(0, false);        ba2.Set(1, true);        ba2.Set(2, false);        ba2.Set(3, true);        ba2.Set(4, false);        Console.Write("BitArray 1 is: ");        for (int i = 0; i < ba1.Count; i++)        {            Console.Write(ba1[i] + " ");        }        Console.Write("\nBitArray 2 is: ");        for (int i = 0; i < ba2.Count; i++)        {            Console.Write(ba2[i] + " ");        }        ba1.And(ba2);        Console.Write("\nBitArray after AND operation is: ");        for (int i = 0; i < ba1.Count; i++)        {            Console.Write(ba1[i] + " ");        }      }   } }

The output of the above program is as follows:

BitArray 1 is: True True False True False BitArray 2 is: False True False True False BitArray after AND operation is: False True False True False