C# Interview Questions Part 2

Give an example of removing an element from the queue?

The dequeue method is used to remove an element from the queue.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoApplication
{
 class Program
 {
  static void Main(string[] args)
  {
   Queue qt = new Queue();
   qt.Enqueue(1);
   qt.Enqueue(2);
   qt.Enqueue(3);

   foreach (Object obj in qt)
   {
    Console.WriteLine(obj);
   }
    Console.WriteLine(); Console.WriteLine();
    Console.WriteLine("The number of elements in the Queue " + qt.Count);
    Console.WriteLine("Does the Queue contain " + qt.Contains(3));
    Console.ReadKey();
   }
 }
}

How is C# different from C?

C is procedural language while C# is a more object-oriented language. The biggest difference is that C# supports automatic garbage collection by Common Language Runtime (CLR) while C does not. C# primarily needs a .NET framework to execute while C is a platform-agnostic language.

What is garbage collection in C#?

Garbage collection is the process of freeing up memory that is captured by unwanted objects.

When you create a class object, automatically some memory space is allocated to the object in the heap memory. Now, after you perform all the actions on the object, the memory space occupied by the object becomes waste. It is necessary to free up memory. Garbage collection usually happens in following cases:

If the occupied memory by the objects exceeds the pre-set threshold value. Or if your system has low physical memory

C# Interview Questions

What is a managed and unmanaged code?

Managed code lets you run the code on a managed CLR runtime environment in the .NET framework.
Managed code runs on the managed runtime environment than the operating system itself.
Benefits: Provides various services like a garbage collector, exception handling, etc.

Unmanaged code is when the code doesn’t run on CLR, it is an unmanaged code that works outside the .NET framework.
They don’t provide services of the high-level languages and therefore, run without them. Such an example is C++.

What is Reflection in C#?

Reflection in C# extracts metadata from the datatypes during runtime.

To add reflection in the .NET framework, simply use System. Reflection namespace in your program to retrieve the type which can be anything from:

Assembly
Module
Enum
Method Info
Constructor Info
Member Info
Parameter Info
Type
Field Info
Event Info
Property Info

Difference between the Equality Operator (==) and Equals() Method in C#?

Although both are used to compare two objects by value, still they both are used differently.

For ex:

int x = 10;
int y = 10;
Console.WriteLine( x == y);
Console.WriteLine(x.Equals(y));


Output:
True
True

Equality operator (==) is a reference type which means that if equality operator is used, it will return true only if both the references point to the same object.

Equals() method: Equals method is used to compare the values carried by the objects. int x=10, int y=10. If x==y is compared then, the values carried by x and y are compared which is equal and therefore they return true.

In short Equality operator(==) compares by value and Equals() compares by reference

Advance C# Interview Questions

What are Properties in C#?

Properties in C# are public members of a class where they provide the ability to access private members of a class. The basic principle of encapsulation lets you hide some sensitive properties from the users by making the variables private. The private members are not accessible otherwise in a class. Therefore, by using properties in C# you can easily access the private members and set their values.

The values can be easily assigned using get and set methods, also known as accessors. While the get method extracts the value, the set method assigns the value to the variables.

What are partial classes in C#?

Partial classes implement the functionality of a single class into multiple files. These multiple files are combined into one during compile time. The partial class can be created using the partial keyword.

public partial Clas_name  
{
       // code
}
You can easily split the functionalities of methods, interfaces, or structures into multiple files. You can even add nested partial classes. 

What are Indexers in C#?

Indexers are called smart arrays that allow access to a member variable. Indexers allow member variables using the features of an array. They are created using the Indexer keyword. Indexers are not static members.

C# Interview Questions

Write a C# program to find if a positive integer is prime or not?

static void Main(string[] args) 
{ 
    if (FindPrime(47)) 
    { 
        Console.WriteLine("Prime"); 
    } 
    else 
    { 
        Console.WriteLine("Not Prime"); 
    } 
    Console.ReadLine(); 
}   
internal static bool FindPrime(int number) 
{ 
    if (number == 1) return false; 
    if (number == 2) return true; 
    if (number % 2 == 0) return false; 
     var squareRoot = (int)Math.Floor(Math.Sqrt(number)); 
     for (int i = 3; i <= squareRoot; i += 2) 
    { 
        if (number % i == 0) return false; 
    } 
     return true; 
}

What is the difference between String and String Builder in C#? Explain with Example.

The major difference between String and String Builder is that String objects are immutable while String Builder creates a mutable string of characters. String Builder will make the changes to the existing object rather than creating a new object.

String Builder simplifies the entire process of making changes to the existing string object. Since the String class is immutable, it is costlier to create a new object every time we need to make a change. So, the String Builder class comes into picture which can be evoked using the System. Text namespace.

In case, a string object will not change throughout the entire program, then use String class or else StringBuilder.

For ex:

string s = string.Empty; 
for (i = 0; i < 1000; i++) 
  { 
    s += i.ToString() + " "; 
  }
//Here, multiple times a string is replaced with new string

//The same can be applied using StringBuilder:

StringBuilder sb = new StringBuilder(); 
for (i = 0; i < 1000; i++) 
 { 
   sb.Append(i); sb.Append(' '); 
 }

//By using StringBuilder here, only one object is being used. 

What is enum in C#?

An Enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an enumeration. It is a primitive data type that is user-defined.

An enum type can be an integer (float, int, byte, double, etc.). But if you use it beside int it has to be cast.

Advance C# Interview Questions

What is the difference between “continue” and “break” statements in C#?

Using break statement, you can ‘jump out of a loop’ whereas by using a continue statement, you can ‘jump over one iteration’ and then resume your loop execution.

 Eg. Break Statement  
using System;  
using System.Collections;  
using System.Linq;  
using System.Text;  
namespace break_example {  
    Class brk_stmt {  
        public static void main(String[] args) {  
            for (int i = 0; i <= 5; i++) {  
                if (i == 4) {  
                    break;  
                }  
                Console.WriteLine("The number is " + i);  
                Console.ReadLine();  
            }  
        }  
    }  
}  
Output 
 
The number is 0; 
 
The number is 1; 
 
The number is 2; 
 
The number is 3;
 
Eg. Continue Statement
using System;  
using System.Collections;  
using System.Linq;  
using System.Text;  
namespace continue_example {  
    Class cntnu_stmt {  
        public static void main(String[] {  
                for (int i = 0; i <= 5; i++) {  
                    if (i == 4) {  
                        continue;  
                    }  
                    Console.WriteLine(“The number is "+ i);   
                        Console.ReadLine();  
                    }  
                }  
            }  
        }  
Output
 
The number is 1;
 
The number is 2;
 
The number is 3;
 
The number is 5;

What is IEnumerable<> in C#?

IEnumerable is the parent interface for all non-generic collections in System. Collections namespace like Array List, Hast Table etc. that can be enumerated.

For the generic version of this interface as IEnumerable which is a parent interface of all generic collections class is System. Collections. Generic namespace like List<> and more.

In System. Collections. Generic. IEnumerable have only a single method which is Get Enumerator() that returns an IEnumerator. IEnumerator provides the power to iterate through the collection by exposing a Current property and Move Next and Reset methods if we don’t have this interface as a parent so we can’t use iteration by for each loop or can’t use that class object in our LINQ query.

What are the differences between IEnumerable and IQueryable?

IEnumerable is the parent interface for all non-generic collections in System.Collections namespace like Array List, Hast Table, etc. that can be enumerated. The generic version of this interface is IEnumerable, which a parent interface of all generic collections class in System. Collections.Generic namespace, like List<> and more.

IQueryable interface is intended for implementation by query providers. It is only supposed to be implemented by providers that also implement IQueryable. If the provider does not also implement IQueryable, the standard query operators cannot be used on the provider’s data source.

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated.

Enumeration causes the expression tree associated with an IQueryable object to be executed. The definition of “executing an expression tree” is specific to a query provider.

For example, it may involve translating the expression tree to an appropriate query language for the underlying data source. Queries that do not return enumerable results are executed when the Execute method is called.

C# Interview Questions

What happens if the inherited interfaces have conflicting method names?

If we implement multiple interfaces in the same class with conflict method names, we don’t need to define all.

In other words, we can say if we have conflict methods in the same class, we can’t implement their body independently in the same class because of the same name and same signature. Therefore, we have to use the interface name before the method name to remove this method confiscation.

Let’s see an example:


interface testInterface1 {  
    void Show();  
}  
interface testInterface2 {  
    void Show();  
}  
class Abc: testInterface1, testInterface2 
   {  
        void testInterface1.Show() {  
            Console.WriteLine("For testInterface1 !!");  
        }  
        void testInterface2.Show() {  
            Console.WriteLine("For testInterface2 !!");  
        }  
    }  
//Now see how to use these in a class:
class Program {  
    static void Main(string[] args) {  
        testInterface1 obj1 = new Abc();  
        testInterface1 obj2 = new Abc();  
        obj1.Show();  
        obj2.Show();  
        Console.ReadLine();  
    }  
}  

What is the Constructor Chaining in C#?

Constructor chaining is a way to connect two or more classes in a relationship as Inheritance.

In Constructor Chaining, every child class constructor is mapped to a parent class Constructor implicitly by base keyword, so when you create an instance of the child class, it will call the parent’s class Constructor. Without it, inheritance is not possible.

What are Singleton Design Patterns and how to implement them in C#?

Singleton Design Patterns ensures a class has only one instance and provides a global point of access to it.
A Singleton is a class that only allows a single instance of itself to be created and usually gives simple access to that instance.
Most commonly, singletons don’t allow any parameters to be specified when creating the instance since the second request of an instance with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter then the factory pattern is more appropriate.)
There are various ways to implement the Singleton Pattern in C#. The following are the common characteristics of a Singleton Pattern.
A single constructor, that is private and parameter less.
The class is sealed.
A static variable that holds a reference to the single created instance, if any.
A public static means of getting the reference to the single created instance, creating one if necessary.
Example of how to write code with Singleton:

namespace Singleton {  
    class Program {  
        static void Main(string[] args) {  
            Calculate.Instance.ValueOne = 10.5;  
            Calculate.Instance.ValueTwo = 5.5;  
            Console.WriteLine("Addition : " + Calculate.Instance.Addition());  
            Console.WriteLine("Subtraction : " + Calculate.Instance.Subtraction());  
            Console.WriteLine("Multiplication : " + Calculate.Instance.Multiplication());  
            Console.WriteLine("Division : " + Calculate.Instance.Division());  
            Console.WriteLine("\n----------------------\n");  
            Calculate.Instance.ValueTwo = 10.5;  
            Console.WriteLine("Addition : " + Calculate.Instance.Addition());  
            Console.WriteLine("Subtraction : " + Calculate.Instance.Subtraction());  
            Console.WriteLine("Multiplication : " + Calculate.Instance.Multiplication());  
            Console.WriteLine("Division : " + Calculate.Instance.Division());  
            Console.ReadLine();  
        }  
    }  
    public sealed class Calculate {  
        private Calculate() {}  
        private static Calculate instance = null;  
        public static Calculate Instance {  
            get {  
                if (instance == null) {  
                    instance = new Calculate();  
                }  
                return instance;  
            }  
        }  
        public double ValueOne {  
            get;  
            set;  
        }  
        public double ValueTwo {  
            get;  
            set;  
        }  
        public double Addition() {  
            return ValueOne + ValueTwo;  
        }  
        public double Subtraction() {  
            return ValueOne - ValueTwo;  
        }  
        public double Multiplication() {  
            return ValueOne * ValueTwo;  
        }  
        public double Division() {  
            return ValueOne / ValueTwo;  
        }  
    }  
}  

Advance C# Interview Questions

Difference between Throw Exception and Throw Clause?

The basic difference is that the Throw exception overwrites the stack trace. This makes it hard to find the original code line number that has thrown the exception.

Throw basically retains the stack information and adds to the stack information in the exception that it is thrown.

Let’s see what it means to better understand the differences. I am using a console application to easily test and see how the usage of the two differ in their functionality.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
namespace TestingThrowExceptions {  
    class Program {  
        public void ExceptionMethod() {  
            throw new Exception("Original Exception occurred in ExceptionMethod");  
        }  
        static void Main(string[] args) {  
            Program p = new Program();  
            try {  
                p.ExceptionMethod();  
            } catch (Exception ex) {  
                throw ex;  
            }  
        }  
    }  

What is a multicast delegate in C#?

Delegate is one of the base types in .NET. Delegate is a class that is used to create and invoke delegates at runtime. A delegate in C# allows developers to treat methods as objects and invoke them from their code. Implement Multicast Delegates Example:

using System;    
using System.Collections.Generic;    
using System.Linq;    
using System.Text;    
delegate void MDelegate();    
class DM {    
    static public void Display() {    
        Console.WriteLine("Meerut");    
    }    
    static public void print() {    
        Console.WriteLine("Roorkee");    
    }    
}    
class MTest {    
    public static void Main() {    
        MDelegate m1 = new MDelegate(DM.Display);    
        MDelegate m2 = new MDelegate(DM.print);    
        MDelegate m3 = m1 + m2;    
        MDelegate m4 = m2 + m1;    
        MDelegate m5 = m3 - m2;    
        m3();    
        m4();    
        m5();    
    }    
}    

What are Different Ways a Method can be Overloaded?

Method overloading is a way to achieve compile-time polymorphism where we can use a method with the same name but different signatures. For example, the following code example has a method volume with three different signatures based on the number and type of parameters and return values.

Example
using System;    
using System.Collections.Generic;    
using System.Linq;    
using System.Text;    
    
namespace Hello_Word {    
    class overloding {    
        public static void Main() {    
            Console.WriteLine(volume(10));    
            Console.WriteLine(volume(2.5F, 8));    
            Console.WriteLine(volume(100L, 75, 15));    
            Console.ReadLine();    
        }    
    
        static int volume(int x) {    
            return (x * x * x);    
        }    
    
        static double volume(float r, int h) {    
            return (3.14 * r * r * h);    
        }    
    
        static long volume(long l, int b, int h) {    
            return (l * b * h);    
        }    
    }    
}    

Note
If we have a method that has two parameter object type and has the same name method with two integer parameters, when we call that method with int value, it will call that method with integer parameters instead of the object type parameters method.

C# Interview Questions

What are Features of Generics in C#?

Generics allow you to delay the specification of the data type of programming elements in a class or a method until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.

You write the specifications for the class or the method, with substitute parameters for data types. When the compiler encounters a constructor for the class or a function call for the method, it generates code to handle the specific data type.

It helps you to maximize code reuse, type safety, and performance.
You can create your own generic interfaces, classes, methods, events, and delegates.
You may create generic classes constrained to enable access to methods on specific data types.
You may get information on the types used in a generic data type at run-time using reflection.

What is a Virtual Method in C#?

A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as derived the class.

It is used when a method’s basic functionality is the same but sometimes more functionality is needed in the derived class. A virtual method is created in the base class that can be overridden in the derived class.

We create a virtual method in the base class using the virtual keyword and that method is overridden in the derived class using the override keyword.

When a method is declared as a virtual method in a base class then that method can be defined in a base class and it is optional for the derived class to override that method. The overriding method also provides more than one form for a method. Hence, it is also an example of polymorphism.

By default, methods are non-virtual. We can’t override a non-virtual method.
We can’t use the virtual modifier with static, abstract, private or override modifiers.

What is Serialization in C#? Give some examples

Serialization in C# is the process of converting an object into a stream of bytes to store the object to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

There are three main types of serialization,
Binary serialization (Save your object data into binary format).
Soap Serialization (Save your object data into binary format; mainly used in network-related communication).
XmlSerialization (Save your object data into an XML file).

Advance C# Interview Questions

How do you use the “using” statement in C#?

There are two ways to use the using keyword in C#. One is as a directive and the other is as a statement. Let’s explain!


using Directive
Generally, we use the using keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces and abstract classes and their methods and properties on the current page. Adding a namespace can be done as following:
Using Name Space Name

There is another way to use the using keyword in C#. It plays a vital role in improving performance in Garbage Collection.

What is Multithreading with .NET?

Multithreading allows a program to run multiple threads concurrently.

The real usage of a thread is not about a single sequential thread, but rather using multiple threads in a single program. Multiple threads running at the same time and performing various tasks are referred to as Multithreading.

A thread is considered to be a lightweight process because it runs within the context of a program and takes advantage of the resources allocated for that program.

A single-threaded process contains only one thread while a multithreaded process contains more than one thread for execution.

What is a Hashtable in C#?

A Hash table is a collection that stores (Keys, Values) pairs. Here, the Keys are used to find the storage location and is immutable and cannot have duplicate entries in a Hash table.

The .Net Framework has provided a Hash Table class that contains all the functionality required to implement a hash table without any additional development.

The hash table is a general-purpose dictionary collection. Each item within the collection is a DictionaryEntry object with two properties: a key object and a value object.

Declaring a Hash table

The Hash table class is generally found in the namespace called System. Collections. So to execute any of the examples, we have to add using System. Collections; to the source code. The declaration for the Hash table is:
Hash table HT = new Hashtable ();

C# Interview Questions

What is LINQ in C#?

LINQ stands for Language Integrated Query. LINQ is a data querying methodology that provides querying capabilities to .NET languages with a syntax similar to a SQL query.

LINQ has a great power of querying on any source of data. The data source could be collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable interface.

Advantages of LINQ
LINQ offers an object-based, language-integrated way to query over data no matter where that data came from. So through LINQ, we can query a database and XML as well as collections.
Compile-time syntax checking.
It allows you to query collections like arrays, enumerable classes, etc… in the native language of your application, like in VB or C# in much the same way you would query a database using SQL.

What is File Handling in C#.Net?

The System.IO namespace provides four classes that allow you to manipulate individual files, as well as interact with a machine directory structure.

The Directory and File directly extend System. Object and supports the creation, copying, moving and deletion of files using various static methods.

They only contain static methods and are never instantiated. The File Info and Directory Info types are derived from the abstract class File System Info type and they are typically employed for obtaining the full details of a file or directory because their members tend to return strongly typed objects. They implement roughly the same public methods as a Directory and a File but they are state full and members of these classes are not static.

Explain the concept of Destructor with an example.

A destructor is a member that works just the opposite of the constructor. Unlike constructors, destructors mainly delete the object. The destructor name must match exactly with the class name just like a constructor. A destructor block always starts with the tilde (~) symbol.

Syntax:

~class_name()
{
//code
}
A destructor is called automatically:

when the program finishes its execution.
Whenever a scope of the program ends that defines a local variable.
Whenever you call the delete operator from your program.

Advance C# Interview Questions

What is a multicast delegate in C#?

A multicast delegate holds the references or addresses to more than one function at a single time. Whenever we invoke the multicast delegate, it will invoke all the other functions that are being referred by that multicast delegate. You should use the complete method signature the same as the delegate to call multiple methods. For example:

namespace MulticastDelegate
{
public class Rectangle
{
public void Area(double Width, double Height)
{
Console.WriteLine(@"Area is {0}", (Width * Height));
}
public void Perimeter(double Width, double Height)
{
Console.WriteLine(@"Perimeter is {0}", (2 * (Width + Height)));
}
static void Main(string[] args)
{
Rectangle rect = new Rectangle();
rect.Area(23.45, 67.89);
rect.Perimeter(23.45, 67.89);
Console.ReadKey();
}
}
}
Here, we created an instance of the Rectangle class and then called the two different methods. Now a single delegate will invoke these two methods Area and Perimeter. These defined methods are having the same signature as the defined delegates that hold the reference to these methods.

Creating multicast delegate:

namespace MulticastDelegateDemo
{
public delegate void RectangleDelete(double Width, double Height);
public class Rectangle
{
public void Area(double Width, double Height)
{
Console.WriteLine(@"Area is {0}", (Width * Height));
}
public void Perimeter(double Width, double Height)
{
Console.WriteLine(@"Perimeter is {0}", (2 * (Width + Height)));
}
static void Main(string[] args)
{
Rectangle rect = new Rectangle();
RectangleDelete rectDelegate = new RectangleDelete(rect.Area);
rectDelegate += rect.Perimeter;
rectDelegate(23.45, 67.89);
Console.WriteLine();
rectDelegate.Invoke(13.45, 76.89);
Console.WriteLine();
//Removing a method from delegate object
rectDelegate -= rect.Perimeter;
rectDelegate.Invoke(13.45, 76.89);
Console.ReadKey();
}
}
}

Explain the concept of thread in C#?

A thread can be defined as the execution flow of any program and defines a unique flow of control.

You can manage these threads’ execution time so that their execution does not overlap the execution of other threads and prevent deadlock or to maintain efficient usage of resources.

Threads are lightweight programs that save the CPU consumption and increase the efficiency of the application. The thread cycle starts with the creation of the object of system. threading. thread class and ends when the thread terminates.

System.threading.thread class allows you to handle multiple threads and the first thread always runs in a process called the main thread. Whenever you run a program in C#, the main thread runs automatically.

Name some of the most common places to look for a Deadlock in C#?

For recognizing deadlocks, one should look for threads that get stuck on one of the following:

.Result, .GetAwaiter().GetResult(), WaitAll(), and WaitAny() (When working with Tasks)
Dispatcher.Invoke() (When working in WPF)
Join() (When working with Threads)
lock statements (In all cases)
WaitOne() methods (When working with AutoResetEvent/EventWaitHandle/Mutex/Semaphore)

C# Interview Questions

Define Serialization and its various types in C#?

The process of converting some code into its binary format is known as Serialization in C#. Doing so allows the code to be stored easily and written to a disk or some other storage device. We use Serialization when there is a strict need for not losing the original form of the code. A class marked with the attribute [Serializable] gets converted to its binary form. A stream that contains the serialized object and the System.Runtime.Serialization namespace can have classes for serialization. Serialization in C# is of three types:

Binary Serialization – Faster and demands less space; it converts any code into its binary form. Serialize and restore public and non-public properties.
SOAP – It produces a complete SOAP compliant envelope that is usable by any system capable of understanding SOAP. The classes about this type of serialization reside in System. Runtime. Serialization.
XML Serialization – Serializes all the public properties to the XML document. In addition to being easy to read, the XML document manipulated in several formats. The classes in this type of serialization reside in System.sml.Serialization.

What can you tell us about the XSD file in C#?

XSD denotes XML Schema Definition. The XML file can have any attributes, elements, and tags if there is no XSD file associated with it. The XSD file gives a structure for the XML file, meaning that it determines what, and also the order of, the elements and properties that should be there in the XML file. Note: – During serialization of C# code, the classes are converted to XSD compliant format by the Xsd.exe tool.

Why do we use Async and Await in C#?

Processes belonging to asynchronous programming run independently of the main or other processes. In C#, using Async and Await keywords for creating asynchronous methods.

Advance C# Interview Questions

What is an Indexer in C#, and how do you create one?

Also known as an indexed property, an indexer is a class property allowing accessing a member variable of some class using features of an array.

Used for treating an object as an array, indexer allows using classes more intuitively. Although not an essential part of the object-oriented programming, indexers are a smart way of using arrays. As such, they are also called smart arrays.

Defining an indexer enables creating classes that act like virtual arrays. Instances of such classes can be accessed using the [] array access operator. The general syntax for creating an indexer in C# is:

< modifier > <return type > this[argument list] {
get {
// the get block code
}
set {
// the set block code
}
}

What is the Race condition in C#?

When two threads access the same resource and try to change it at the same time, we have a race condition. It is almost impossible to predict which thread succeeds in accessing the resource first. When two threads try to write a value to the same resource, the last value written is saved.

What do you understand by Get and Set Accessor properties?

Made using properties, Get and Set are called accessors in C#. A property enables reading and writing to the value of a private field. Accessors are used for accessing such private fields. While we use the Get property for returning the value of a property, use the Set property for setting the value.

C# Interview Questions

What is Singleton Design Patterns in C#? Explain their implementation using an example.

A singleton in C# is a class that allows the creation of only a single instance of itself and provides simple access to that sole instance. Because the second request of an instance with a different parameter can cause problems, singletons typically disallow any parameters to be specified. Following example demonstrates the implementation of Singleton Design Patterns in C#:

namespace Singleton {
class Program {
static void Main(string[] args) {
Calculate.Instance.ValueOne = 10.5;
Calculate.Instance.ValueTwo = 5.5;
Console.WriteLine("Addition : " + Calculate.Instance.Addition());
Console.WriteLine("Subtraction : " + Calculate.Instance.Subtraction());
Console.WriteLine("Multiplication : " + Calculate.Instance.Multiplication());
Console.WriteLine("Division : " + Calculate.Instance.Division());
Console.WriteLine("\n----------------------\n");
Calculate.Instance.ValueTwo = 10.5;
Console.WriteLine("Addition : " + Calculate.Instance.Addition());
Console.WriteLine("Subtraction : " + Calculate.Instance.Subtraction());
Console.WriteLine("Multiplication : " + Calculate.Instance.Multiplication());
Console.WriteLine("Division : " + Calculate.Instance.Division());
Console.ReadLine();
}
}
public sealed class Calculate {
private Calculate() {}
private static Calculate instance = null;
public static Calculate Instance {
get {
if (instance == null) {
instance = new Calculate();
}
return instance;
}
}
public double ValueOne {
get;
set;
}
public double ValueTwo {
get;
set;
}
public double Addition() {
return ValueOne + ValueTwo;
}
public double Subtraction() {
return ValueOne - ValueTwo;
}
public double Multiplication() {
return ValueOne * ValueTwo;
}
public double Division() {
return ValueOne / ValueTwo;
}
}
}
A Singleton Design Pattern ensures that a class has one and only one instance and provides a global point of access to the same. There are numerous ways of implementing the Singleton Design Patterns in C#. Following are the typical characteristics of a Singleton Pattern:

A public static means of getting the reference to the single instance created
A single constructor, private and parameter-less
A static variable holding a reference to the single instance created
The class is sealed

Give a detailed explanation of the differences between ref and out keywords.

In any C# function, there can be three types of parameters, namely in, out and ref. Although both out and ref are treated differently at the run time, they receive the same treatment during the compile time. It is not possible to pass properties as an out or ref parameter. Following are the differences between ref and out keywords:

Initializing the Argument or Parameter – While it is not compulsory to initialize an argument or parameter before passing to an out parameter, the same needs to be initialized before passing it to the ref parameter.
Initializing the Value of the Parameter – Using ref doesn’t necessitate for assigning or initializing the value of a parameter before returning to the calling method. When using out, however, it is mandatory to use a called method for assigning or initializing a value of a parameter before returning to the calling method.
Usefulness – When the called method requires modifying the passed parameter, passing a parameter value by Ref is useful. Declaring a parameter to an out method is appropriate when multiple values are required to be returned from a function or method.
Initializing a Parameter Value in Calling Method – It is a compulsion to initialize a parameter value within the calling method while using out. However, the same is optional while using the ref parameter.
Data Passing – Using out allows for passing data only in a unidirectional way. However, data can be passed in a bidirectional manner when using ref.

What are virtual functions in c#?

When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual function. the virtual function could be implemented differently in different inherited class and the class and the call to these function will be decided at runtime.

Advance C# Interview Questions

How will you create sealed abstract class in c#?

No! it cannot be created as abstract classes cannot be declared sealed.

List down the reason behind the usage of C# language?

There are several reasons for the usage of C# as a programming platform. Some of them are listed below.

Easy to pickup
Component oriented language
Follows a Structured approach
Produces readable and efficient programmers
Once written can be compiled on different platforms
Passing parameters is easy

What are the advantages of using C#?

Following are the advantages of using C#:

Easy to learn
Object-Oriented language
The syntax is easy to grasp
Component oriented
Part of the .NET framework

C# Interview Questions

What are the different states of a Thread?

Different states of a thread are:

Un started – Thread is created.
Running – Thread starts execution.
Wait Sleep Join – Thread calls sleep, calls wait on another object and calls join on another thread.
Suspended – Thread has been suspended.
Aborted – Thread is dead but not changed to state stopped.
Stopped – Thread has stopped.\

What is a Race Condition?

Race condition occurs when two threads access the same resource and are trying to change it at the same time. The thread which will be able to access the resource first cannot be predicted.

If we have two threads, T1 and T2, and they are trying to access a shared resource called X. And if both the threads try to write a value to X, the last value written to X will be saved.

C# Part 1C# Part 3
Back to top