Q) Explain few string Methods in C#?

A)There are several predefined methods that are used for various operations like comparison, appending , inserting , copying, indexing, joining, etc.
Copy()–It is used copy string
Compare()–used to compare two strings
IndexOf()–It is get the position of first occurrence of sub-string
Equals()–It is used to check if two strings are equal
Remove()–It is used to delete characters from string.
Split()–It is used to split the string
Replace()–It is used to replace all instances of character with a new character


Q) What is StringBuilder? And what is the difference between string and StringBuilder?

A)StringBuilder is a class which is used to represent a mutable string of characters and it is an object of System.
The difference between string and StringBuilder is string is immutable and StringBuilder is mutable.


Q) Explain structs in C#

A)A struct in C# is a way of packing multiple types of data together. Structs are declared using the struct keyword. Below is the example of struct

struct Fruit
{
public string FruitName;
public string FruitColor;
public double FruitPrice;
}

Q) What is the difference between structs and classes?(Here the interviewer also want to know the benefits of class over struct)

A)The following is the difference between struct and class:
Classes are of reference type
Structs are value type

classes support inheritance
structs don’t support inheritance

Assignment in classes copies the reference instead of value
Assignment in structs copies the values


Q) What is enumeration in C#?

A)An enumeration is user defined integer type which provides a way of attaching names to numbers. enum keyword is used to define an enumaration. The below is an example of enumeration:

enum vehicle
{
Car,
Truck,
Van
}

Q) Explain access modifiers in C#

A)There are five access modifiers in C#. The following is their brief description:
private: Members are accessible only within the class when this specifier is used.
public: Members are accessible from anywhere
protected: Members are visible only to its own class and its derived class
internal: Members are accessible for same component or same assembly
protected internal: Members are accessible in assembly or in derived class


Q)What is a delegate in C#?

A)A delegate is similar to pointer function. It allows the user to encapsulate a reference to a method inside a delegate object.
A delegate declaration defines a class using System.Delegate as a base class.


Q)Give a sample program using delegate

A)Below is sample program with methods having same name but different datatypes. The delegate x is initialized with reference to second method because that method exactly matches the signature and return type of ColorDelegate

delegate int ColorDelegate(int p,int q);
class delegateSample
{
static double Color(double a,double b)
{
return (a*b);
}
static int Color(int a,int b)
{
return (a*b);
}

ColorDelegate x=new ColorDelegate(Color);
}

Q) What is an event in C#?(If you are experienced programmer make sure you explain the flow of event)

A)An event is a delegate type class member that is used to provide notification to other object that an event is raised. Delegates and events are tightly coupled because event handling requires delegate implementation.


Q)What is the difference between events and delegates in C#?

A)The main difference between event and delegate is that event will provide one more layer of abstraction over delegates. We cannot create an event without delegate.


Q)What are the uses of delegates in C#?

A)Below are a few uses of delegates in C#:

Asynchronous Processing

Abstract and Encapsulate method

Callback Mechanism

Multicasting


Q)What are Multicast Delegates C#?

A)A delegate with multiple handlers are called as multicast delegate. The example to demonstrate the same is given below

public delegate void Calculate(int x, int y);
int x = 100;
int y = 200;
Calculate addNumbers = new Calculate(AddNumbersMethod);
Calculate multiplyNumbers = new Calculate(MultiplyNumbersMethod);
Calculate multiCastDel = (Calculate)Delegate.Combine (addMyNumbers, multiplyMyNumbers);
multiCastDel.Invoke(a,b);

Q)Can we use delegates for asynchronous method calls in C#?

A)Yes. We can use delegates for asynchronous method calls.


Q)What are the types of Errors in C#?

A)Errors may be broadly classified into two types:
Compile time errors: All syntax errors which are displayed by compiler are called Compile time errors
Run time errors: All the logical errors occurred while executing program after successful compilation are known as run time errors.


Q) What is exception handling in C#?(This is one of interviews most important question)

A) whenever there are logical errors like divide by zero. The compiler will display message and terminates the program. To prevent this termination we can handle these exceptions through try and catch blocks. This process is known as exception handling.


Q) What is inner exception in C#?

A)Inner exception is a property of exception class which will give us a brief insight of the exception i.e, parent exception and child exception details.


Q) Can we have only “try” block without “catch” block in C#?

A)Yes we can have only try block without catch block but we have to have finally block.


Q) Can multiple catch blocks be executed in C#?

A)No. Multiple catch blocks can’t be executed. Once the proper catch code executed, the control is transferred to the finally block.


Q) Syntax of exception handling or try catch block.

A)There are basically three blocks in exception handling
try block: In this block main code is written where we have the chances of getting an error at run time.
catch block: This block is executed only when there is an exception raised in try block.
finally block: This block is not mandatory, but whatever the statements given in this block are executed irrespective of exception or even if there is no exception

Syntax:

try
{
//Your statements to be executed
}
catch(Exception e)
{
//Code after catching the exception
}
finally
{
//Code which will execute irrespective of exception handled or not.
}

Q) What is serialization?(This is interviewers favorite if he plays with data in business logic)

A)Conversion of an object into a stream of bytes is called serialization. This process is generally used when we want to transfer an object through network. For an object to be serializable, it should implement ISerialize Interface.

Similarly De-serialization is the reverse process of creating an object from stream of bytes


Q) Is it possible to have multiple catch blocks for same try block?

A)Yes. It is possible, we can write multiple catch blocks for same try block but type of exception should be different for every catch block.


Q) What is Hashtable in C#?

A)It is used to store the key/value pairs based on hash code of the key. Key will be used to access the element in the collection. For example,

Hashtable myHash = new Hashtable();
 myHash.Add("1", "TestValue1");
 myHash.Add("2", "TestValue2");

Q) Explain threads in C#(Threads are import to handle concurrency)

A)In general a thread is a sequential flow of control. In C# System.Threading namespace allow us to handle threads and multi-threading concepts.


Q) What are the different states of a Thread?(This question is generally asked in interview to know the handling of thread)

A)Below are Different states of a thread:

Unstarted: Thread is created.
Running: Thread starts execution.
WaitSleepJoin: 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.


Q) Name some properties of Thread Class?

A)Below are few Properties of thread class:

IsAlive : contains value True when a thread is Active.
Name : Can return the name of the thread. Also, can set a name for the thread.
Priority : returns the prioritized value of the task set by the operating system.
IsBackground: gets or sets a value which indicates whether a thread should be a background process or foreground.
ThreadState: describes the thread state.


Q) What is Thread Pooling?(This interview question is only if you have more than 4 to 5 years of experience)

A)A 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 which manage the threads in the pool and its operations.


Q) What are important classes in System.Threading namespace?

A)System.Threading namespace contains many classes of which four important classes are briefly described

1.Thread class:Thread class is used for creating a thread, setting its priority, obtain its status, etc.

2.Monitor class: With monitor class we can lock and release an object control access.

3.ThreadPool class: Thread pool class provides a pool of threads to perform various tasks. We can also set limit to threads by using methods like SetMaxThreads, SetMinThreads.

4.Mutex Class: Mutex class allows to have exclusive access to the resource(resource can be code, method or function). It will not allow to execute any other thread on given resource until current thread execution is finished.


Q) What is Anonymous type in C#?

A) Anonymous type in C# enable us to create an object at compile time. Below is the example:

Var myTestVehicle = new { VehicleId = 1, VehicleName = “Car”};

Q) Write a sample code to write the contents to text file in C#?

A)Below is the sample code to write the contents to text file:

Using System.IO;
File.WriteAllText(”textfilePath”, “TxtFileContent”);

Q) What are Indexers in C#?

A)Indexers are used for allowing the classes to be indexed like arrays. Indexers will resemble the property structure but only difference is indexer’s accessors will take parameters. Below is the example:

class SampleCollection<T>
{
 private T[] SampleArr = new T[100];
 public T this[int t]
 {
 get
 {
 return SampleArr[t];
 }
 set
 {
 SampleArr[t] = value;
 }
 }
}

Q) What is Async method of C#?

A)Async (asynchronous programming) can be described as a method that returns to the calling method before finishing its work fully. It then proceeds to complete its work while the calling method goes along with its execution.


Q) In which assembly System namespace lies in C#?

A)Assembly Name – mscorlib.dll

C Sharp(C#) Interview Questions Part I