C-Sharp Interview Questions

C# is a widely used programming language in the IT industry. It is developed by Microsoft and mostly used for building the desktop applications. If you are looking for making your career in the software industry as a developer, these best interview questions in C sharp will be useful in cracking the interview. Below is a list of most asked C# interview questions and answers. These C# interview questions can be useful for freshers and experienced professionals to clear the interview. Here are the C# basic interview questions that will make you ready to face the interview.

  • 4.5 Rating
  • 20 Question(s)
  • 30 Mins of Read
  • 3319 Reader(s)

Advanced

The System.OutOfMemoryException occurs when enough memory is not allocated.

Let us see an example:

using System;
using System.Text;
namespace Application {
  class Example {
     static void Main(string[] args) {
        try {
           string deptname = "Tom";
           string loc = "North";
           StringBuilder s = new StringBuilder(deptname.Length, deptname.Length);
           s.Append(deptname);
           s.Insert(value: loc, index: deptname.Length - 1, count: 1);
        } catch (System.OutOfMemoryException e) {
           Console.WriteLine("The following is the error:");
           Console.WriteLine(e);
        }
     }
  }
}

The example displays the Out Of Memory Exception:

The following is the error:
System.OutOfMemoryException: Out of memory
 at System.Text.StringBuilder.Insert (System.Int32 index, System.String value, System.Int32 count) [0x00065] in <902ab9e386384bec9c07fa19aa938869>:0
 at Application.Example.Main (System.String[] args) [0x0002f] in <98ee8a52b3134b0799d382272292200f>:0

The SequenceEqual() method is used in C# to check whether two sequences are equal or not.

The following is an example:

using System;
using System.Linq;
class Example
{
   static void Main()
   {
       string[] arr1 = { "one", "two", "three" };
       string[] arr2 = { "one", "four", "five" };
       bool res = arr1.SequenceEqual(arr2);
       Console.WriteLine(res);
   }
}

The output:

False

Let us see another example:

using System;
using System.Linq;
class Example
{
   static void Main()
   {
       string[] arr1 = { "HTML", "CSS", "JavaScript" };
       string[] arr2 = { "HTML", "CSS", "JavaScript" };
       bool res = arr1.SequenceEqual(arr2);
       Console.WriteLine(res);
   }
}

The output:

True

The Main Thread is the first thread that is created and executed inside a process. It is automatically created when the process starts execution.

A program that demonstrates the Main thread is given as follows:

using System;
using System.Threading;
namespace MultithreadingDemo
{
  class Example
  {
     static void Main(string[] args)
     {
        Thread myThread = Thread.CurrentThread;
        myThread.Name = "Main_Thread";
        Console.WriteLine("This thread is the {0}", myThread.Name);
     }
  }
}

The output of the above program is as follows:

This thread is the Main_Thread

Now let us understand the above program.

The CurrentThread property of the Thread class is used to access the Main thread. The name of the thread is specified is Main_Thread. After that, this is displayed. The code snippet for this is given as follows:

Thread myThread = Thread.CurrentThread;
myThread.Name = "Main_Thread";         
Console.WriteLine("This thread is the {0}", myThread.Name);

The Array.SyncRoot property gets an object used to synchronize access to the Array. Use the SyncRoot property to implement their own synchronization. This usage is for classes having arrays.

A default constructor takes no arguments. Each object of the class is initialized with the default values that are specified in the default constructor. Therefore, it is not possible to initialize the different objects with different values.

An example that demonstrates a default constructor is given as follows:

using System;
namespace DefaultConstructorDemo
{
  class Sum
  {
    private int x;
    private int y;
    public Sum()
    {
        x = 5;
        y = 7;
    }
    public int getSum()
    {
        return x + y;
    }  
   }
   class Test
   {
     static void Main(string[] args)
     {
        Sum s = new Sum();   
        Console.WriteLine("Sum: {0}" , s.getSum());
     }
   }
}

The output of the above program is as follows:

Sum: 12

Now let us understand the above program.

First, the class Sum is initialized. It contains two private variables x and y. The default constructor Sum() initializes x and y to 5 and 7 respectively. Then the function getSum() returns the sum of x and y. The code snippet for this is given below:

class Sum
  {
    private int x;
    private int y;
    public Sum()
    {
        x = 5;
        y = 7;
    }
    public int getSum()
    {
        return x + y;
    }
   }

The main() function is in the class Test. It initializes an object s of class Sum. Then the sum of 5 and 7 is displayed using getSum(). The code snippet for this is given below:

class Test
   {
     static void Main(string[] args)
     {
        Sum s = new Sum();   
        Console.WriteLine("Sum: {0}" , s.getSum());
     }
   }

Assign a null value to variable with nullable data types. It was introduced in C# 2.0 for the same purpose as well as assign values other than null. An example: 

int? a = null;

Above, we have assigned a null value to a variable.

A method without a name is Anonymous Method. It is defined using the delegate keyword.

The Anonymous methods can be assigned to a variable of delegate type. It can also be passed as a parameter. Here are some of the features of Anonymous Methods in C#:

  • Anonymous methods are defined using the delegate keyword.
  • Anonymous methods can be used in event handling.
  • Any unsafe codes cannot be accessed inside anonymous methods.
  • Variables declared outside the anonymous methods can be accessed inside them.
  • Variables declared inside the anonymous methods cannot be accessed outside them.
  • Anonymous methods can be passed as parameters.

The following is an example:

using System;
public delegate void DemoDelegate(int value);
public class Example
{
  public static void Display(DemoDelegate one,int a)
   {
       a *= 50;
       one(a);
   }
   public static void Main(string[] args)
   {
       Display(delegate(int a) { Console.WriteLine("Anonymous method = {0}", a); }, 100);
   }
}

The output: 

Anonymous method = 5000 

Let us see another example: 

using System;
namespace AnonymousMethodDemo
{
  class Example {
     public delegate void sum(int x, int y);
     static void Main(string[] args)
     {
        sum s = delegate(int x, int y)
        {
          Console.WriteLine("Inside Anonymous method");
          Console.WriteLine("Sum = {0}",x + y);
        };
        s(7, 12);
     }
  }
}

The output of the above program is as follows:

Inside Anonymous method
Sum = 19

The concept of Mixed arrays is obsolete since .NET 4.0. Since it does not exist now, you can use List collection in C#.

An example is:

Tuple<int, string> t = new Tuple<int, string>(200, "This is fine!"); 

If a Delegate invokes multiple methods, these are called Multicast Delegates.

Let us see an example:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
delegate void DemoDelegate();  
class Example  
{  
   static public void One()  
   {
       Console.WriteLine("One");  
   }
   static public void Two()  
   {
       Console.WriteLine("Two");  
   }
   static public void Three()  
   {
       Console.WriteLine("Three");  
   }
}  
class Demo  
{  
   public static void Main()  
   {
       DemoDelegate d1 = new DemoDelegate(Example.One);  
       DemoDelegate d2 = new DemoDelegate(Example.Two);  
       DemoDelegate d3 = new DemoDelegate(Example.Three);  
       DemoDelegate d4 = d1 + d2 + d3;  
       DemoDelegate d5 = d2 + d3 + d4;  
       DemoDelegate d6 = d3 - d4 + d5;
       d3();
       d4();
       d5();
       d6();
   }
}

The output:

Three

One

Two

Three

Two

Three

One

Two

Three

Two

Three

One

Two

Three

The major difference between Typeof() and GetType() is that while Typeof() obtains the type based on the class, GetType() obtains the type based on the object. Details about both of them in C# are given as follows:

Typeof()

The Typeof() method is used to get the System.Type object for a given type. Also, this method can be used on open generic types but it cannot be overloaded.

A program that demonstrates the Typeof() method in C# is given as follows:

using System;
using System.IO;
class Demo
{
   public static void Main()
   {
       Console.WriteLine(typeof(int));
       Console.WriteLine(typeof(char));
       Console.WriteLine(typeof(double));
       Console.WriteLine(typeof(int[]));
       Console.WriteLine(typeof(Array));
       Console.WriteLine(typeof(Stream));
       Console.WriteLine(typeof(TextWriter));
   }
}

The output of the above program is as follows:

System.Int32
System.Char
System.Double
System.Int32[]
System.Array
System.IO.Stream
System.IO.TextWriter

GetType()

The GetType() method obtains the type of the current object of the class. A program that demonstrates the GetType() method in C# is given as follows:

using System;
class Animal
{
}
class Mammal : Animal
{
}
class Human : Mammal
{
}
class Demo
{
   static void Main()
   {
       Animal obj1 = new Animal();
       Animal obj2 = new Mammal();
       Animal obj3 = new Human();
       Console.WriteLine(obj1.GetType());
       Console.WriteLine(obj2.GetType());
       Console.WriteLine(obj3.GetType());
   }
}

The output of the above program is as follows:
Animal
Mammal
Human

There are no final variables in C# as the keyword final is available in Java and not in C#. The keywords readonly and sealed in C# have the same implementation as final in Java.

Details about readonly and sealed in C# are given as follows:

The readonly keyword

In a field declaration, the readonly keyword specifies that assignment for a field can only occur with declaration or using the constructor of the same class. A program that demonstrates the readonly keyword is given as follows:

using System;
class Student
{
   readonly int rollNo;
   public Student(int rno)
   {
       rollNo = rno;
   }
   public int getRollNumber()
   {
       // rollNo = 7;
       return this.rollNo;
   }
}
public class Demo
{
   public static void Main()
   {
       Student s = new Student(105);
       Console.WriteLine("Roll Number: " + s.getRollNumber());
   }
}

The output of the above program is as follows:

Roll Number: 105

In the above program, the variable rollNo is readonly and so it cannot be assigned a value in method getRollNumber(). So if the comments are removed, an error would be obtained.

The sealed keyword
The sealed keyword is used in classes to restrict inheritance. So sealed classes are those classes that cannot be extended and no class can be derived from them.

A program that demonstrates the sealed keyword in C# is given as follows:

using System;
sealed class A
{   
   int a = 5;
   public int returna()
   {
       return a;
   }
}
class Demo
{
   static void Main(string[] args)
   {
       A obj = new A();
       Console.WriteLine("a = " + obj.returna());
   }
}

The output of the above program is as follows:

a = 5

In the above program, the class A is a sealed class. This means that it cannot be inherited and an error will be generated if any class is derived from the class A.

The rank of an array is the number of dimensions of an array. For example - The rank of a one-dimensional array is 1, the rank of a two dimensional array is 2 and so on. The rank of a jagged array is 1 as it is a one-dimensional array. The rank of any array can be found using the Array.Rank property.

A program that demonstrates the rank of an array in C# is given as follows:

using System;
namespace Demo
{
   class Program
   {
       static void Main(string[] args)
       {
           int[] arr1 = new int[10];
           int[,] arr2 = new int[4, 5];
           int[][] arr3 = new int[5][];
           Console.WriteLine("Rank of Array 1 is: " + arr1.Rank);
           Console.WriteLine("Rank of Array 2 is: " + arr2.Rank);
           Console.WriteLine("Rank of Array 3 is: " + arr3.Rank);
       }
   }
}

The output of the above program is as follows:

Rank of Array 1 is: 1
Rank of Array 2 is: 2
Rank of Array 3 is: 1

C# is a general purpose object-oriented programming language with multiple paradigms. It was designed for Common Language Infrastructure (CLI) in 2000 by Microsoft.

C# has multiple advantages to contribute to the speed of web development solutions. Some of these are  scalability support, garbage collection, type safety, easier type declarations etc.

Best Practices to write better C# code

Some of the best practices that help in writing better C# code are given as follows:

  1. Pascal casing should be used for method names and class names while Camel Casing should be used for local variables and method arguments.
  2. Underscore should not be used in identifiers.
  3. All member variables should be declared at the class top and at the topmost should be static variables.
  4. The class sizes should be small for greater efficiency.
  5. There should be no obsolete comments in the code. They should be updated if required.
  6. The methods should be short.
  7. There should be no unnecessary regions in the class.
  8. The complex expressions should be avoided.
  9. In a particular routine, there should be minimum number of returns.

In method overriding, the parameters are the same. In method overloading, the parameters are different.

To perform Interning of strings, use the Intern() method. Use interning to optimize application’s memory. The common language runtime conserves string storage by maintaining a table, called the intern pool.

The intern() method retrieves the reference to the particular string. The search for a string equal to the particular String is done in Intern Pool.

Unsafe code in general is a keyword that denotes a code section that is not handled by the Common Language Runtime (CLR). Pointers are not supported by default in C# but unsafe keyword allows the use of the pointer variables.

However, extra care is required while handling unsafe code to prevent errors or security risks as pointers are complex and may lead to memory related errors such as stack overflow, overwritten system memory etc.

The following is an example:

using System;
namespace PointerDemo
{
  class Example
  {
     static unsafe void Main(string[] args)
     {
        char val = 'A';
        char* ptr = &val;
        Console.WriteLine("The character value is: {0} ", val);
        Console.WriteLine("Address of the value is: {0}", (int)ptr);
     }
  }
}

The output of the above program is as follows:

The character value is: A
Address of the value is: 220412608

The AssemblyQualifiedName property displays the qualified assembly name associated with a type. The program that demonstrates this property is as follows:

using System;  
using System.Reflection;  
public class Demo  
{  
   public static void Main()  
   {
        Type t = typeof(System.Object);
       Console.WriteLine ("Qualified assembly name:\n   {0}.", t.AssemblyQualifiedName.ToString());
   }
} 

The output of the above program is as follows:

Qualified assembly name:
System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.

Intermediate

Creating a tuple with string and int items:

Tuple<int, string> 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

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.

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

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

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

var t = new Tuple<string, string[], int, int, int>("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

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.

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

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.NullReferenceExceptionHandles 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.

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!

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

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

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.

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

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!");
       }
   }
}

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!");
       }
   }
}

Under Circular References, two or more resources causes the lock condition. These resources are interdependent on each other and these are made unusable.

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

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!

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.

The Union() method performs the union of two collections. The resultant collection contains all the elements from both the collections but there are no duplicates. Also, The namespace System.Linq is required for the Union() method.

A program that demonstrates the union of two lists using the Union() method is given as follows:

using System;
using System.Collections.Generic;
using System.Linq;
class Demo
{
   public static void Main()
   {
       List<int> list1 = new List<int>();
       list1.Add(4);
       list1.Add(1);
       list1.Add(8);
       list1.Add(2);
       list1.Add(3);
       List<int> list2 = new List<int>();
       list2.Add(9);
       list2.Add(1);
       list2.Add(3);
       list2.Add(7);
       list2.Add(2);
       var union = list1.Union(list2);
       Console.WriteLine("The elements in the union of the two lists are:");
       foreach (int i in union)
       {
           Console.WriteLine(i);
       }
   }
}

The output of the above program is as follows:

The elements in the union of the two lists are:
4
1
8
2
3
9
7

Beginner

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.

Ref local variables

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.

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

Const
Readonly
Local Variable
Can be applied to local variables.
Cannot be applied to local variables
.
Memory
Memory is not allocated.
Dynamic memory is allocated for readonly fields.

Static
Const are by-default staticTo make it class member, include static keyword before readonly

Ref or out
We cannot pass const field as ref or out parameter
The readonly field can be passed as ref or out parameters in the constructor context.

Faster
Faster than readonly.
Readonly isn’t faster.

Performance
Performance isn’t better than readonly.
Performance is better than const.

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;

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

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

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

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

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.

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

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.

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

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.


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 < 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

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

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

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.

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

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.

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.

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

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

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.

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

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

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

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!");
}
}
}

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...");
}
}
}

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.

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.

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

Description

C# is a widely used programming language in the IT industry. It is developed by Microsoft and mostly used for building the desktop applications. More recently C# is being used in developing the Windows 8/10 applications.

Based on the survey conducted by Stackoverflow, C# is known as the 4th most popular programming language, with 31% of the developers using it regularly. Since it's demand is rising in the market, it has become a necessity today to have a strong understanding of this language to land any dream job in the software industry.

If you are looking for making your career in the software industry as a developer, these best interview questions in C sharp will be useful in cracking the interview. Below is a list of most asked C# interview questions and answers. These C# interview questions can be useful for freshers and experienced professionals to clear the interview.

Here are the C# basic interview questions that will make you ready to face the interview.

Levels