Google News
logo
C# Interview Questions
C# is an object-oriented, modern programming language that was developed by Microsoft in 2000. It runs on the .NET Framework. C# is very close to C/C++ and Java programming languages. The language is proposed to be a simple, modern, general-purpose, object-oriented programming language.  The language is used for creating software components.
You would always know C being the 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. 
C# is designed for Common Language Infrastructure (CLI). It contains the executable code and runtime environment that makes the users able to use various high-level languages on different computer platforms and architectures.
These are top reasons to use C# language :
 
* Easy to learn
* General purpose and object oriented programming language
* Component oriented
* Structured language
* Can be compiled on variety of computer platforms
* Produces efficient programs
* Part of .net framework
Below listed are the types of comments followed in C# :
 
a. Single line comments
 
// hello, this is a single line comment


b. Multiline comments
 
/* Hello this is a multiline comment
 last line of comment*/


c. XML comments
 
/// Hello this is XML comment
There exist four steps in the process of code compilation :
 
* Compilation of Source code in managed  code
* Clubbing the newly created code into assembly
* Loading the CLR (Common Language Runtime)
* Execution of assembly through CLR
Following are the access modifiers available for general use :
 
Public : When an attribute or method is defined as public it can be accessed from any part of code.
 
Private : A private attribute or method can be accessed from within the class itself.
 
Protected : When a user defines a method or attribute as protected then it can be accessed only within that class and the one inheriting the class.
 
Internal : When an attribute or method is defined as internal then it will be accessed from that class at the current assembly position.
 
Protected Internal : When you define an attribute or method as protected internal, then it’s access restricted to classes within the current project assembly or different types defined by that class.
 
Moving ahead in C# Interview questions, let’s unfold some functionalities used in C#.
Below listed are few IDE’s for C# development :
 
* Visual Studio Express (VCE)
* Visual Studio (VS)
* Visual Web Developer
* MonoDevelop
* browxy
The four fundamental concepts of Object-Oriented Programming are :
 
Encapsulation : Here, the internal representation of an object is hidden from the view outside the object’s definition. Only the required information can be accessed whereas the rest of the data implementation is hidden.

Abstraction : It is a process of identifying the critical behavior and data of an object and eliminating the irrelevant details.

Inheritance : It is the ability to create new classes from another class. It is done by accessing, modifying and extending the behavior of objects in the parent class.

Polymorphism : The name means, one name, many forms. It is achieved by having multiple methods with the same name but different implementations.
The different types of class in C# are:
 
Partial class : It allows its members to be divided or shared with multiple .cs files. It is denoted by the keyword Partial.

Sealed class : It is a class that cannot be inherited. To access the members of a sealed class, we need to create the object of the class.  It is denoted by the keyword Sealed.

Abstract class : It is a class whose object cannot be instantiated. The class can only be inherited. It should contain at least one method.  It is denoted by the keyword abstract.

Static class : It is a class that does not allow inheritance. The members of the class are also static.  It is denoted by the keyword static. This keyword tells the compiler to check for any accidental instances of the static class.
Boxing and Unboxing both are used for type conversions.
 
The process of converting from a value type to a reference type is called boxing. Boxing is an implicit conversion. Here is an example of boxing in C#.
// Boxing  
int anum = 123;  
Object obj = anum;  
Console.WriteLine(anum);  
Console.WriteLine(obj); ​

 

The process of converting from a reference type to a value type is called unboxing. Here is an example of unboxing in C#.
// Unboxing  
Object obj2 = 123;  
int anum2 = (int)obj;  
Console.WriteLine(anum2);  
Console.WriteLine(obj); 
Class and struct are both user-defined data types, but have some major differences :
 
Struct :
* The struct is a value type in C# and it inherits from System.Value Type.
* Struct is usually used for smaller amounts of data.
* Struct can’t be inherited from other types.
* A structure can't be abstract.
* No need to create an object with a new keyword.
* Do not have permission to create any default constructor.

Class :
* The class is a reference type in C# and it inherits from the System.Object Type.
* Classes are usually used for large amounts of data.
* Classes can be inherited from other classes.
* A class can be an abstract type.
* We can create a default constructor.
Here are some of the common differences between an interface and an abstract class in C#.

* A class can implement any number of interfaces but a subclass can at most use only one abstract class.
* An abstract class can have non-abstract methods (concrete methods) while in case of interface, all the methods have to be abstract.
* An abstract class can declare or use any variables while an interface is not allowed to do so.
* In an abstract class, all data members or functions are private by default while in an interface all are public, we can’t change them manually.
* In an abstract class, we need to use abstract keywords to declare abstract methods, while in an interface we don’t need to use that.
* An abstract class can’t be used for multiple inheritance while the interface can be used as multiple inheritance.
* An abstract class use constructor while in an interface we don’t have any type of constructor.
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.
 
An enum is used to create numeric constants in the .NET framework. All the members of enum are enum type. There must be a numeric value for each enum type.
 
The default underlying type of the enumeration element is int. By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1. 

enum Dow {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

Some points about enum :

* Enums are enumerated data types in c#.
* Enums are not for the end-user, they are meant for developers.
* Enums are strongly typed constant. They are strongly typed, i.e. an enum of one type may not be implicitly assigned to an enum of another type  even though the underlying value of their members is the same.
* Enumerations (enums) make your code much more readable and understandable.
* Enum values are fixed. Enum can be displayed as a string and processed as an integer.
* The default type is int, and the approved types are byte, sbyte, short, ushort, uint, long, and ulong.
* Every enum type automatically derives from System.Enum and thus we can use System.Enum methods on enums.
* Enums are value types and are created on the stack and not on the heap.
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 happens in three cases :
 
* If the occupied memory by the objects exceeds the pre-set threshold value.
* If the garbage collection method is called
* If your system has low physical memory
Break Continue
You can use break statements in both switch and loop (for, while, and do-while ) statements. You can use continue statements only in the loop (for, while, do) statements.
The switch or loop statements terminate at the moment the break statement is executed and it ends abruptly from there. You cannot make a continue statement terminate the loop, it carries on the loop to go to the next iteration level without executing the immediate next step.
The loop or switch exits immediately from the inner loop when the compiler encounters a break statement and comes out of the inner loop. A continue that is placed inside a nested loop within a switch causes the next loop iteration.
An exception is a raised problem that may occur during the execution of the program. Handling exceptions offers a simple way to pass the control within the program whenever an exception is raised. C# exceptions are handled by using 4 keywords and those are try, catch, finally, throw.
 
try : a raised exception finds a particular block of code to get handled. There is no limit on the number of catch blocks that you will use in your program to handle different types of exception raised.

catch : you can handle the raised exception within this catch block. You can mention the steps that you want to do to solve the error or you can ignore the error by suppressing it by the code.

Finally : irrespective of the error, if you still want some set of instructions to get displayed then you can use those statements within the finally block and it will display it on the screen.

throw : you can throw an exception using the throw statement. It will display the type of error you are getting.

Syntax :
try {
//exception handling starts with try block
} catch( ExceptionName ea1 ) {
   // errors are handled within the catch block
} catch( ExceptionName e2 ) {
   // more catch block
} catch( ExceptionName eN ) {
   // more catch block to handle multiple exception raised
} finally {
   // last block of the exception handling
} 
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.
C# ref keywords pass arguments by reference and not value. To use the ‘ref’ keyword, you need to explicitly mention ‘ref’. 
void Method(ref int refArgument)
{
   refArgument = refArgument + 10;
}
int number = 1;
Method(ref number);
Console.WriteLine(number);
// Output: 11
 
C# out keywords pass arguments within methods and functions. 
‘out’ keyword is used to pass arguments in a method as a reference to return multiple values. Although it is the same as the ref keyword, the ref keyword needs to be initialised before it is passed. Here, The out and ref keywords are useful when we want to return a value in the same variables that are passed as an argument. 
public static string GetNextFeature(ref int id)  
{  
   string returnText = "Next-" + id.ToString();  
   id += 1;  
   return returnText;  
}  
public static string GetNextFeature(out int id)  
{  
   id = 1;  
   string returnText = "Next-" + id.ToString();  
   return returnText;  
}
Extension methods help to add new methods to the existing ones. The methods that are added are static. At times, when you want to add methods to an existing class but don’t perceive the right to modify that class or don’t hold the rights, you can create a new static class containing the new methods. Once the extended methods are declared, bind this class with the existing one and see the methods will be added to the existing one.
// C# program to illustrate the concept
// of the extension methods
using System;
 
namespace ExtensionMethod {
static class NewMethodClass {
 
   // Method 4
   public static void M4(this Scaler s)
   {
       Console.WriteLine("Method Name: M4");
   }
 
   // Method 5
   public static void M5(this Scaler s, string str)
   {
       Console.WriteLine(str);
   }
}
 
// Now we create a new class in which
// Scaler class access all the five methods
public class IB {
 
   // Main Method
   public static void Main(string[] args)
   {
       Scaler s = new Scaler();
       s.M1();
       s.M2();
       s.M3();
       s.M4();
       s.M5("Method Name: M5");
   }
}
}
Output :
 
Method Name: M1
Method Name: M2
Method Name: M3
Method Name: M4
Method Name: M5
You can control the flow of your set of instructions by using control statements and we majorly focus on if statements. There are a few types of if statements that we consider for making situations to control the flow of execution within a program.
 
These are the 4 types of if statements :
 
* If
* If-else
* Nested if
* If-else-if 

These statements are commonly used within programs.
 
If statements checks for the user given condition to satisfy their programming condition. If it returns true then the set of instructions will be executed.
 
Syntax :
If(any condition)
{
//code to be executed if the condition returns true
}
 
If-else statement checks for the given condition, if the condition turns out to be false then the flow will transfer to the else statement and it will execute the else instructions. In case, the if condition turns out to be true then the if instructions will get executed.
 
Syntax :
If(condition)
{
//code to be run if the condition is true
}
Else
{
//code to be run if the if-condition is false
}
Nested if statement checks for the condition, if the condition is true then it will check for the inner if statement and keeps going on for the last if statement. If any of the conditions are true then it will execute the particular if instructions and stops the if loop there.
 
Syntax :
If (condition to be checked)
{
//code
If(condition 2)
{
//code for if-statement 2
}
}
If else-if checks for the given condition, if the condition is not true then the control will go to the next else condition, if that condition is not true it will keep on checking for next else conditions. If any of the conditions did not pass then the last else instructions will get executed.
 
Syntax :
If(condition 1 to be checked)
{
//code for condition 1
}
Else (condition 2 to be checked)
{
//code for condition 2
}
Else
{
//code will run if no other condition is true
}
Using Clone() method, we creates a new array object containing all the elements in the original Array and using CopyTo() method. All the elements of existing array copies into another existing array. Both methods perform a shallow copy.
Dispose() is called when we want for an object to release any unmanaged resources with them. On the other hand, Finalize() is used for the same purpose, but it doesn’t assure the garbage collection of an object.
Properties are the special type of class members that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and helps to promote the flexibility and safety of methods. Encapsulation and hiding of information can also be achieved using properties. It uses pre-defined methods which are “get” and “set” methods which help to access and modify the properties.
 
Accessors : The block of “set” and “get” is known as “Accessors”. It is very essential to restrict the accessibility of the property. There are two types of accessors i.e. get accessors and set accessors. There are different types of properties based on the “get” and set accessors:
 
Read and Write Properties : When property contains both get and set methods.

Read-Only Properties : When property contains only the get method.

Write Only Properties : When property contains only set method.

Auto Implemented Properties : When there is no additional logic in the property accessors, and it introduces in C# 3.0.
A partial class is a special feature of C#. It provides a special ability to implement the functionality of a single class into multiple files and all these files are combined into a single class file when the application is compiled. A partial class is created by using a partial keyword. This keyword is also useful to split the functionality of methods, interfaces, or structure into multiple files.
public partial Class_name  
{
       // Code 
}
When an object is assigned to an object variable of the specific type, then the C# compiler performs the binding with the help of .NET Framework. C# performs two different types of bindings which are :
 
* Early Binding
* Late Binding or Dynamic Binding

It recognizes and checks the methods, or properties during compile time. In this binding, the compiler already knows about what kind of object it is and what are the methods or properties it holds, here the objects are static objects. The performance of early binding is fast and it is easy to code. It decreases the number of run-time errors.
 
In late binding, the compiler does not know about what kind of object it is and what are the methods or properties it holds, here the objects are dynamic objects. The type of the object is decided on the basis of the data it holds on the right-hand side during run-time. Basically, late binding is achieved by using virtual methods. The performance of late binding is slower than early binding because it requires lookups at run-time.
The main purpose of the catch block is to handle the exception raised in the try block. This block is only going to execute when the exception is raised in the program. In C#, You can use more than one catch block with the try block. Generally, multiple catch block is used to handle different types of exceptions means each catch block is used to handle different type of exception. If you use multiple catch blocks for the same type of exception, then it will give you a compile-time error because C# does not allow you to use multiple catch block for the same type of exception. A catch block is always preceded by the try block.
 
In general, the catch block is checked within the order in which they have occurred in the program. If the given type of exception is matched with the first catch block, then the first catch block executes and the remaining of the catch blocks are ignored. And if the starting catch block is not suitable for the exception type, then the compiler searches for the next catch block.
Method parameters must be different in method overloading whereas it must be same in method overriding.
 
Inheritance is not required in method overloading, it occurs within the same class. But inheritance is required in method overriding.
Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using the sealed keyword. The keyword tells the compiler that the class is sealed, and therefore, cannot be extended. No class can be derived from a sealed class.
 
The following is the syntax of a sealed class :
sealed class class_name
{
    // data members
    // methods
    .
    .
    .

}
A method can also be sealed, and in that case, the method cannot be overridden. However, a method can be sealed in the classes in which they have been inherited. If you want to declare a method as sealed, then it has to be declared as virtual in its base class.
When you have a function defined in a class that you want to be implemented in an inherited class(es), you use virtual functions. The virtual functions could be implemented differently in different inherited class and the call to these functions will be decided at runtime.
The preprocessor directives give instruction to the compiler to preprocess the information before actual compilation starts.
 
All preprocessor directives begin with #, and only white-space characters may appear before a preprocessor directive on a line. Preprocessor directives are not statements, so they do not end with a semicolon (;).
You can use the #if directive to create a conditional directive. Conditional directives are useful for testing a symbol or symbols to check if they evaluate to true. If they do evaluate to true, the compiler evaluates all the code between the #if and the next directive.
A namespace is designed for providing a way to keep one set of names separate from another. The class names declared in one namespace does not conflict with the same class names declared in another.
Regular expression is a template to match a set of input. The pattern can consist of operators, constructs or character literals. Regex is used for string parsing and replacing the character string.
 
For Example :
 
* matches the preceding character zero or more times. So, a*b regex is equivalent to b, ab, aab, aaab and so on.
 
Searching a string using Regex :
static void Main(string[] args)
{
string[] languages = { "C#", "Python", "Java" };
foreach(string s in languages)
{
if(System.Text.RegularExpressions.Regex.IsMatch(s,"Python"))
{
Console.WriteLine("Match found");
}
}
}
The above example searches for “Python” against the set of inputs from the languages array. It uses Regex.IsMatch which returns true in case if the pattern is found in the input. The pattern can be any regular expression representing the input that we want to match.
Different types of Delegates are:
 
Single Delegate : A delegate that can call a single method.

Multicast Delegate :
A delegate that can call multiple methods. + and – operators are used to subscribe and unsubscribe respectively.

Generic Delegate :
It does not require an instance of the delegate to be defined. It is of three types, Action, Funcs and Predicate.
Action : In the above example of delegates and events, we can replace the definition of delegate and event using Action keyword. The Action delegate defines a method that can be called on arguments but does not return a result

Public delegate void deathInfo();
Public event deathInfo deathDate;
//Replacing with Action//
Public event Action deathDate;
 
Action implicitly refers to a delegate.
 
Func :  A Func delegate defines a method that can be called on arguments and returns a result.
Func <int, string, bool> myDel is same as delegate bool myDel(int a, string b);
 
Predicate : Defines a method that can be called on arguments and always returns the bool.
Predicate<string> myDel is same as delegate bool myDel(string s);
Serialization is a process of converting code to its binary format. Once it is converted to bytes, it can be easily stored and written to a disk or any such storage devices. Serializations are mainly useful when we do not want to lose the original form of the code and it can be retrieved anytime in the future.
 
Any class which is marked with the attribute [Serializable] will be converted to its binary form.
 
The reverse process of getting the C# code back from the binary form is called Deserialization.
 
To Serialize an object we need the object to be serialized, a stream that can contain the serialized object and namespace System.Runtime.Serialization can contain classes for serialization.
The different types of Serialization are : 
 
XML serialization : It serializes all the public properties to the XML document. Since the data is in XML format, it can be easily read and manipulated in various formats. The classes reside in System.sml.Serialization.

SOAP : Classes reside in System.Runtime.Serialization. Similar to XML but produces a complete SOAP compliant envelope that can be used by any system that understands SOAP.

Binary Serialization : Allows any code to be converted to its binary form. Can serialize and restore public and non-public properties. It is faster and occupies less space.
An XSD file stands for XML Schema Definition. It gives a structure for the XML file. It means it decides the elements that the XML should have and in what order and what properties should be present. Without an XSD file associated with XML, the XML can have any tags, any attributes, and any elements.
 
Xsd.exe tool converts the files to the XSD format. During Serialization of C# code, the classes are converted to XSD compliant format by xsd.exe.
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.
Thread pool is a collection of threads. These threads can be used to perform tasks without disturbing the primary thread. Once the thread completes the task, the thread returns to the pool.
 
System.Threading.ThreadPool namespace has classes that manage the threads in the pool and its operations.
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(SomeTask));
The above line queues a task. SomeTask methods should have a parameter of type Object.
Lock keyword ensures that only one thread can enter a particular section of the code at any given time. In the above Example, lock(ObjA) means the lock is placed on ObjA until this process releases it, no other thread can access ObjA.
 
Mutex is also like a lock but it can work across multiple processes at a time. WaitOne() is used to lock and ReleaseMutex() is used to release the lock. But Mutex is slower than lock as it takes time to acquire and release it.
 
Monitor.Enter and Monitor.Exit implements lock internally. a lock is a shortcut for Monitors. lock(objA) internally calls.
 
To catch an Exception we make use of try-catch blocks. The catch block has a parameter of the system.Exception type.
 
Example :
try
{
GetAllData();
}
catch(Exception ex){
}
C# consists of System.IO namespace which has classes that compute and perform various operations on files like creating, deleting, opening
and closing etc.
 
Few commonly used I/O classes are listed below :
 
File : Helps in manipulating file.
StreamWriter :  Generally used for writting characters to a stream.
StreamReader : Generally used for reading characters to a stream.
StringWriter : Used for writing a string buffer.
Stringreader : Used for reading a string buffer.
Multicasting of delegate is an extension of the normal delegate(sometimes termed as Single Cast Delegate). It helps the user to point more than one method in a single call.
In C# virtual method is a strategy that can be reclassified in derived classes. We can implement the virtual method in the base class and derived class. It is utilized when a method’s fundamental work is similar but in some cases derived class needed additional functionalities. A virtual method is declared in the parent class that can be overriden in the child class. We make a virtual method in the base class by using the virtual keyword and that method is overriden in the derived class using the Override keyword.  It is not necessary for every derived class to inherit a virtual method, but a virtual method must be created in the base class. Hence the virtual method is also known as Polymorphism.
A Hashtable 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 Hashtable. 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. These are known as Key/Value. When items are added to a hash table, a hash code is generated automatically. This code is hidden from the developer. Access to the table's values is achieved using the key object for identification. As the items in the collection are sorted according to the hidden hash code, the items should be considered to be randomly ordered.
 
The Hashtable Collection
 
The Base Class libraries offer a Hashtable Class that is defined in the System.Collections namespace, so you don't have to code your own hash tables. It processes each key of the hash that you add every time and then uses the hash code to look up the element very quickly. The capacity of a hash table is the number of elements the hash table can hold. As elements are added to a hash table, the capacity is automatically increased as required through reallocation. It is an older .Net Framework type.
 
Declaring a Hashtable
 
The Hashtable 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 Hashtable is:
Hashtable HT = new Hashtable ();  
LINQ is known as Language Integrated Query and it is introduced in .NET 3.5 and Visual Studio 2008. The beauty of LINQ is it provides the ability to .NET languages(like C#, VB.NET, etc.) to generate queries to retrieve data from the data source. For example, a program may get information from the student records or accessing employee records, etc. In, past years, such type of data is stored in a separate database from the application, and you need to learn different types of query language to access such type of data like SQL, XML, etc. And also you cannot create a query using C# language or any other .NET language.
 
To overcome such types of problems Microsoft developed LINQ. It attaches one, more power to the C# or .NET languages to generate a query for any LINQ compatible data source. And the best part is the syntax used to create a query is the same no matter which type of data source is used means the syntax of creating query data in a relational database is the same as that used to create query data stored in an array there is no need to use SQL or any other non-.NET language mechanism. You can also use LINQ with SQL, with XML files, with ADO.NET, with web services, and with any other database.
It provides a way to keep one set of names(like class names) different from other sets of names. The biggest advantage of using namespace is that the class names which are declared in one namespace will not clash with the same class names declared in another namespace. It is also referred as named group of classes having common features.
We can implement a singleton design pattern in C# using :
 
* No Thread Safe Singleton.
* Thread-Safety Singleton.
* Thread-Safety Singleton using Double-Check Locking.
* Thread-safe without a lock.
* Using .NET 4’s Lazy<T> type.
C# includes three keywords that support runtime type identification : is, as, and typeof
 
is operator : We can determine if an object is of a particular type by using the is operator. Its general form is shown here:
 
expr is type
 
Here, expr is an expression that describes an object whose type is being tested against type. If the type of expr is that the same as, or compatible with, type, then the result of this operation is true. Otherwise, it is false. Thus, if the result is true, expr is a  form of type. Because it applies to is, one type is compatible with another if both are the equivalent of type, or if a reference, boxing, or unboxing conversion exists.
 
As operator : Sometimes if we want to try a conversion at runtime, but not throw an exception if the conversion fails (which is the case when a cast is used). To do this, use the as operator, which has this general form:
 
expr as type
 
Here, expr is the expression being converted to type. If the conversion succeeds, then a reference to type is returned. Else, a null reference is returned. The as the operator can be used to perform only reference, boxing, unboxing, or identity conversions. The as operator offers a streamlined alternative to is in some cases.
In C#, an array index starts at zero. That means the first item of an array starts at the 0th position. The position of the last item on an array will total the number of items - 1. So if an array has 10 items, the last 10th item is in the 9th position. 
 
In C#, arrays can be declared as fixed-length or dynamic.
 
A fixed-length array can store a predefined number of items.
 
A dynamic array does not have a predefined size. The size of a dynamic array increases as you add new items to the array. You can declare an array of fixed length or dynamic. You can even change a dynamic array to static after it is defined.
 
Let's take a look at simple declarations of arrays in C#. The following code snippet defines the simplest dynamic array of integer types that do not have a fixed size.
int[] intArray;​
 
As you can see from the above code snippet, the declaration of an array starts with a type of array followed by a square bracket ([]) and the name of the array.
 
The following code snippet declares an array that can store 5 items only starting from index 0 to 4. 
int[] intArray;    
intArray = new int[5];    
The following code snippet declares an array that can store 100 items starting from index 0 to 99. 
int[] intArray;    
intArray = new int[100];  
C# introduces a new concept known as Indexers which are used for treating an object as an array. The indexers are usually known as smart arrays in C#. They are not an essential part of object-oriented programming.
 
Defining an indexer allows you to create classes that act as virtual arrays. Instances of that class can be accessed using the [] array access operator.
 
Creating an Indexer 
< modifier > <    
return type > this[argument list] {    
    get {    
        // your get block code    
    }    
    set {    
        // your set block code    
    }    
} ​
   
In the above code,
 
<modifier>
 
can be private, public, protected or internal.
 
<return type>
 
can be any valid C# types.
Both the == Operator and the Equals() method are used to compare two value type data items or reference type data items. The Equality Operator (==) is the comparison operator and the Equals() method compares the contents of a string. The == Operator compares the reference identity while the Equals() method compares only contents. Let’s see with some examples.
 
In this example, we assigned a string variable to another variable. A string is a reference type and in the following example, a string variable is assigned to another string variable so they are referring to the same identity in the heap and both have the same content so you get True output for both the == Operator and the Equals() method.
using System;    
namespace ComparisionExample {    
    class Program {    
        static void Main(string[] args) {    
            string name = "sandeep";    
            string myName = name;    
            Console.WriteLine("== operator result is {0}", name == myName);    
            Console.WriteLine("Equals method result is {0}", name.Equals(myName));    
            Console.ReadKey();    
        }    
    }    
} 
Reflection in C# extracts metadata from the datatypes during runtime. 
 
To add reflection in the .NET framework, simply use System.Refelction namespace in your program to retrieve the type which can be anything from:
 
* Assembly
* Module
* Enum
* MethodInfo
* ConstructorInfo
* MemberInfo
* ParameterInfo
* Type
* FieldInfo
* EventInfo
* PropertyInfo
A const keyword in C# is used to declare a constant field throughout the program. That means once a variable has been declared const, its value cannot be changed throughout the program. 
 
In C#, a constant is a number, string, null reference, or boolean values. 
 
For example :
class IB {
 
   // Constant fields
   public const int xvar = 20;
   public const string str = "InterviewBit";
 
   // Main method
   static public void Main()
   {
 
       // Display the value of Constant fields
       Console.WriteLine("The value of xvar: {0}", xvar);
       Console.WriteLine("The value of str: {0}", str);
   }
}

Output :

The value of xvar is 20.
The value of string is Interview Bit
On the other hand, with readonly keyword, you can assign the variable only when it is declared or in a constructor of the same class in which it is declared. 
 
Example :
public readonly int xvar1;
   public readonly int yvar2;
 
   // Values of the readonly 
   // variables are assigned
   // Using constructor
   public IB(int b, int c)
   {
 
       xvar1 = b;
       yvar2 = c;
       Console.WriteLine("The value of xvar1 {0}, "+
                       "and yvar2 {1}", xvar1, yvar2);
   }
 
   // Main method
   static public void Main()
   {
     IB obj1 = new IB(50, 60);
   }
}

Output :
The value of xvar1 is 50, and yvar2 is 60
 
* Constants are static by default while readonly should have a value assigned when the constructor is declared. 
* Constants can be declared within functions while readonly modifiers can be used with reference types.
The major difference between String and StringBuilder is that String objects are immutable while StringBuilder creates a mutable string of characters. StringBuilder will make the changes to the existing object rather than creating a new object.
 
StringBuilder 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 StringBuilder 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 example :
string s = string.Empty; 
for (i = 0; i < 1000; i++) 
  { 
    s += i.ToString() + " "; 
  }
 
Here, you’ll need to create 2001 objects out of which 2000 will be of no use.
 
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, you also de-stress the memory allocator.
Whenever you open a file for reading or writing it becomes a stream which is a sequence of bytes travelling from source to destination. The two commonly used streams are input and output. The included namespace is system.IO that includes many classes for file handling. The stream is an abstract class that is the parent class for the file handling process. The file is a static class with many static methods to handle file operation.
 
Below are the used classes : 
 
The following table describes some commonly used classes in the System.IO namespace.

Class Name Description
FileStream This stream read from and write to any location within a file
BinaryReader read primitive data types from a binary stream
DirectoryInfo perform operations on directories
FileInfo perform operations on files
BinaryWriter write primitive data types in binary format
StreamReader to read characters from a byte Stream
StreamWriter write characters to a stream.
StringReader read from a string buffer
StringWriter write into a string buffer
58 .
How to use Nullable<> Types in C#?
A nullable type is a data type is that contains the defined data type or the null value.
 
This nullable type concept is not compatible with "var".
 
Any data type can be declared nullable type with the help of operator "?". 
 
For example, the following code declares the int 'i' as a null.
int? i = null; 

As discussed in the previous section "var" is not compatible with nullable types. So, if you declare the following, you will get an error.
var? i = null;
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)
Async and Await keywords are mostly used for creating asynchronous methods in C#. Usage of the same is shown through an example :
public async Task>CalculateCount()
{
await Task.Delay(2000);
return 1;
}
public async task mytestmethod()
{
Task> count = CalculateCount();
int result = await count;
}
In the above-given code async keyword is used for method declaration. The Count is of a task type int which calls the method CalculateCount(). CalculateCount() starts execution and calculates something.
The F# structure is a data structure which is used to organize data, and it is value types and efficient than class. It does not allow let binding, so you must declare fields by using val keyword.
 
Example : 
type Book = struct  
   val title : string  
   val author: string  
   val price : float  
   new (title, author, price) =           // Constructor  
      {title = title; author = author; price = price;}  
end  
let book = new Book("FSharp Programming", "Chris Smith", 100.0)   // Calling Constructor  
printfn "Title  : %s " book.title  
printfn "Author : %s"  book.author  
printfn "Price  : $%0.2f"  book.price
It is a useful data structure. It helps to store heterogeneous data. The Union is used to represent tree data structures. It provides cases, and each case consists of heterogeneous data.
 
Example : 
type Calcualte =    
    | Add of val1 : int * val2 : int    
    | Multiply of val1 : int * val2 : int    
    
let compute vall =    
   match vall with    
     | Add (val1, val2) -> val1+val2    
     | Multiply (val1, val2)->val1*val2    
    
let addition = compute (Add(10,10))    
let multiplication = compute (Multiply(2,5))    
    
printf "Addition = %d\nMultiplication = %d" addition multiplication