C# Interview questions & Answers

Interview
Question & Answers
Tutorials

C Sharp Interview questions and answers101  C Sharp Interview questions and answers  help job seekers and freshers to have basic and advance knowledge of C# language and Dot Net framework. Experienced also can take the advantage of  C Sharp Interview questions and answers post.  I got the feedback from many C# developers that they found C Sharp Interview questions and answers post very helpful for succeeding in freelancers.com and upwork.com exam C# test. C Sharp Interview questions and answers have been designed to help you understand the basics and advance commands.

In this tutorials following topics have been covered.

1. Basic Concepts C# language.

2. OOPs Concepts

3. Classes

4. Constructors

5. Interfaces

6. Methods

7. Delegates in C#

8. Multithreading in C#

9. Loops

10. ADO.NET

11. Exceptions

12. Reflection

13. Others

14. Serialization / Deserialization

Basics Concepts C# language:-

1. Explain  C-Sharp (C#) in brief.

C# is a type-safe means all it ensures that  operations are being performed in right domain with right data.

C# is managed language means managed code can be written only in high level language like in c#  and managed code is compiled by .Net framework for generating intermediate language (IL).

C# is object oriented language because it supports Abstraction, Encapsulation, Polymorphism and Inheritance.

2. Define sealed class.

Sometime there is a situation when you don not want to some class use as a parent class so that members of that class should not be  overridden. For this purpose declare the class as "sealed" class. Sealed class can not be inherited so no member in that can not be overridden.

EXAMPLE:
sealed class MySealedClass
{
int ID=0;
public string GetName()
{
return "Some Name";
}
}
public class ChildClass: MySealedClass// Gives compile time error
{
}

3. Array and ArrayList?C Sharp Interview questions and answers

4. Define Namespace in C#.

Namespace is the Logical cluster of varieties or a instrumentality that organize the class, Structures, Interfaces, Enumerations, Delegates and logical programming code.

5. Define "const" in c#.

A variable whose value you don not want to be changed at run time then declare that variable as constant and assign value at compile time.

Example : string const MemeberNo="10101";

6.   Define “constant” and “readonly” variables.

constant variables are  declared ans assigned value at compile time. The values of constant variables can not be changed at run time.

readonly variables can be declared ans assigned value in constructor or at declaration time . The values of readonly variables can be changed at run time.

7. Define "static" in c#.

  •  The static keyword in the C# programming language permits  you to define static classes and static members.
  • Instantiation and inheritance is not applicable on static class.
  • By default all member method and variables are static of a class declared as static.
  • Modifier is applicable on a class, field, method, property, operator, event or constructor.
  • this keyword  in static class is not applicable.

8. System namespace belongs to __ assembly.

Assembly Name – mscorlib.dll

9. What are Regular expressions?

A regular expression is a template(pattern) that might be matched against associate degree input text.  A pattern consists of 1 or a lot of character literals, operators, or constructs.

10.  Define Synchronous and Asynchronous operations.

Synchronous operation : When called method in  synchronous  mode then next part of code execution wait till the called method completes its operation.

Asynchronous operation : When called method in  asynchronous  mode then next part of code execution  continues without waiting for called method completes its operation.

11. Which class is a base class for all arrays in C#?

System.Object

12.  Define Escape Sequence C#.

Whenever there is a requirement to process the some character as special character to perform some special task then you can use those characters starting with backslash (\).

Example:
\r Carriage return
\r\n Carriage return—new line
\" Quotation marks
\\ Backslash character

13. Defines Managed And Unmanaged Code.

The code, that is developed in .NET framework, is thought as managed code. This code is directly dealt by CLR with facilitate of managed code execution. Any language that's written in .NET Framework is managed code. The code, that is developed outside .NET, Framework is thought as unmanaged code.

14. Define string and StringBuilder in C#.

  • String is immutable , immutable suggests that if you produce string object then you can not modify it and It continuously produce new object of string sort in memory.
  • StringBuilder is changeable, suggests that if produce string builder object then you'll be able to perform any operation like insert, replace or append while not making new instance for each time.it will update string at one place in memory doesn't produce new area in memory.

15. Define Boxing and Unboxing.

  • Boxing means  converting a value type to the type object or to any interface type implemented by this value type.
  • Unboxing extracts the value type from the object.

16. Define  late binding and early binding in C#.

  • Late binding means run time performs the binding to assign a variable to object.
  • Early binding means compiler at compiling time  performs the binding to assign a variable to object.

17. Define Nullable Types in C#.

One of the powerful data types in C# is nullable types ( special data type), The Nullable data type can take Null or normal range of values. Range any value from -2,147,483,648 to 2,147,483,647 or null in a Nullable<Int32> variable.

18. Define CType and Directcast in C#.

  • DirectCast is generally used to cast reference types.
  • Ctype is generally used to cast value types.
  • DirectCast on arguments that don't match then it will throw InvalidCastException whereas exceptions are not thrown while using Ctype.

19. How to concatenate two strings in C#.

string.Concat(AStr, BStr)

20. Define is and as operators in C#.

“is” operator is used to check the compatibility of an object with a given type and it returns the result as Boolean.

“as” operator is used for casting of object to a type or a class.

21. What is Satellite Assembly?

A satellite gathering is an ordered library (DLL) that contains "localizable" assets particular to a given culture, for example, strings, bitmaps, and so forth. You are probably going to utilize satellite congregations while making a multilingual UI application.

OOPs Concepts

1. Define encapsulation?

Encapsulation means hiding the implementation details i.e methods, members variables etc.  Encapsulation  can be refereed as a physical or logical package'. Encapsulation prevents access to implementation details.

2. Abstraction

Abstraction is vital as a result of it will hide unessential details from reference objects to names. it's conjointly necessary for the development of programs. rather than showing however An object is portrayed or however it works, it focuses on what AN object will. Therefore, information abstraction is usually used for managing massive and complicated programs.

3. Inheritance

Inheritance is a feature of object-oriented programming. It allows code re-usability when a class includes property of another class it is known as inheritance.

4. What is polymorphism?

Polymorphism means one face with many forms. In OOPs concept means 'one interface, multiple functions'. Methods overloading is the example of Polymorphism .

Classes 

1. Define object and class.

  • A Class is associate encapsulation of properties and strategies. In different words category defines the strategies and knowledge to be accessed by its object.
  • An Object in associate instance of a category. once instantiating a class associate object will access the member strategies and variables of instantiated class.

2. Define types of classes in C#.

Partial class – 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 which 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 which 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.

3. Define types of  access modifiers in C#.

public: Access is not restricted.

protected: Access is limited to the containing class or types derived from the containing class.

internal: Access is limited to the current assembly.

protected internal: Access is limited to the current assembly or types derived from the containing class.

4. Define partial class.

In case of complex and  lengthy logic in one class you can divide  complex and  lengthy logic in multiple class  with same name with .cs  extension. Further divided classes are called partial class. However compiler considers all partial class altogether as a single class.

5.  Define "this" pointer.

The this keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method.

6. Define generics in C#.

Generics means you can create a class with a generic data type. it is defined with angle brackets<T>.  When you create a instance of this class then you can decide the data type. The generic class declared with specific data type accepts only that data type.

Example:
class MyGenericClass<T>
{
}
MyGenericClass<int> myGenericClass = new MyGenericClass<int>();
MyGenericClass<string> myGenericClass2 = new MyGenericClass<string>();
MyGenericClass<object> myGenericClass3 = new MyGenericClass<object>();

7. Explain Anonymous type in C#.

Anonymous means a type without name. In C# You can create anonymous type by using the new key word  without defining its class. The "var" is used to store the reference of anonymous types.

Var myTestCategory = new { CategoryId = 1, CategoryName = “Category1”};

8. Define Property in C#.net.

A property is a member that provides a mechanism to read, write value of a private field. Properties can be used as if they are public data members, but they are actually special methods called assessors.

9. struct and class in C#.

Struct Class
Struct is value type inherits from System.ValueType Class is reference type in C#  inherits from the System.Object Type
Struct can't be Inherited or cant be  base type to the classes and also to the other structure. Another class and Interface can be inherited by a class and it can be base class to another class.
Struct can only inherit the interfaces. Class can inherit the interfaces, abstract classes.
Struct can have only constructor. Class can have the constructor and destructor.
Struct does not have the default constructor Class will have the default constructor
Struct is by default sealed class hence it will not allow to inherit. It can't use the abstract, sealed, base keyword. Class can be declared as abstract, sealed class
Struct can't initialize at the time of declaration. class can have the initializes fields.
The struct value will be stored on the stack memory. class object is stored on the heap memory.

Constructors

1. Define constructors in C#.

Constructors' name must be indistinguishable name from class   or struct.  Constructor is an extraordinary kind of technique which is utilized to introduce the information individuals from the new object. On the off chance that no constructor is characterized then a default constructor is taken when class is instantiated.

2. Define Static constructor in C#.

If the constructor is declared as static then it will be invoked only once for all number of instances of a class. Static constructor will initialize the static fields of a class.

3. List sequence of firing of the Constructors.

First Base Class Constructor then parent class constructor fires.

4. What is Default Constructor?

If there is no declaration of any constructor, the class will call its default constructor which has a default public access modifier.

Interfaces 

1. Define Interface in C#.

An Interface is a class with no implementation. The only thing that it contains is the declaration of methods, properties, and events.

2. Interface and Abstract Class.

  • An Interface defines the full abstraction but an abstract class does not define full abstraction because it may have some member functions along with abstraction.
  • Multiple inheritance is allowed with Interface but in case of abstract class  no multiple inheritance allowed.
  • Interface does not allow declaration of member fields.
  • In interface by default all declaration are public. so We can not use any access modifier i.e. public , private , protected , internal etc.
  • An Interface member cannot be defined using the keyword static, virtual, abstract or sealed.

3. Why Interface have only methods signatures not the implementation of methods?

Interface allow only signatures or definitions of methods and these methods have to be implemented in derived classes that's why all are public by default.

Methods

1. Define method overloading in C#.

The process of creating more than one method in a class with same name or creating a method in derived class with same name as a method in base class is called as method overloading.

2. Define method overloading and method overriding in C#.

In Overloading we can define two or more methods in one class with the same method name but different parameters.

In Overriding we can two methods with the same method name and parameters (signature). One of the methods is in the parent class and the other is in the child class.

3. Define Virtual method and Abstract method in C#.

  • virtual method : For virtual method's prerequisite is, it must have default implementation in base class however using keyword "override" you can redefine the logic of that method  in child class. However it is optional.
  • abstract method: only signature of method  stays in abstract class.  Derived class must provide the implementation for that method.

4. Define virtual functions in C#.

For virtual method's prerequisite is, it must have default implementation in base class however using keyword "override" you can redefine the logic of that method  in child class. However it is optional.

5. How to prevent the method from being over-ridden?

Declare virtual method as "sealed" in derived public class to prevent it from being next level overridden.

Example:
class BaseClass
{
virtual public void DoSomething()
{
}
}
class DerivedClass : BaseClass
{
sealed override public void DoSomething()
{
}
}
class OtherClass : DerivedClass
{
\\Error Not Possible because DoSomething is sealed
override public void DoSomething()
{
}
}

6. Can a private virtual method be overridden?

No, because virtual method can not be declared as private.

7. Define public, static and void?

public : The keyword public is an access modifier that tells the C# compiler that the Main method is accessible by anyone.

static : The keyword static declares that the Main method is a global one and can be called without creating an instance of the class.

void : The keyword void is a type modifier that states that the Main method does not return any value.

8. What is Function for Overloading in C# .net ?

Different parameters with same name more than one functions is the called overloading.

public class Employee {
public void DoSomething() { }
public void DoSomething(String Name) { }
}

9. Define Virtual Keyword in C#.

To override a method in base class, Virtual keyword is used.

Example:
class BaseClass
{
virtual public void DoSomething()
{
}
}

10. Define Method Hiding in C#.

if you are not interested using some method of base class in derived class then you can implement that method using "new" keyword in derived class with same signature to hide the method of base class.

Example:
public class BaseClass
{
public void DoSomething()
{}
}
public class DerivedClass : BaseClass
{
public new void DoSomething()
{}
}

11. Define  attributes in C#.

To change the run time behaviour of some entities like classes and methods C# supports declarative tags on entities like Class and method. Reflection fetches the attribute’s information at runtime.

13. Dispose and Finalize methods in C#.

  • dispose()  method is responsible for cleaning the  unmanaged   resources held by an object.  The developer has to implement the dispose() method in logical way.
  • finalize() method is dealt by  the garbage collector, just before the object is destroyed.

14. “this”  can not be used within a static method why?

The this keyword refers to the current instance of the class. Static member functions do not have a this pointer.

15. Define ref and out keywords.

  • out keyword: The caller of a method which takes an out parameter is not required to assign to the variable passed as the out parameter prior to the call; however, the callee is required to assign to the out parameter before returning.
  • ref keyword: In contrast ref parameters are considered initially assigned by the caller. As such, the callee is not required to assign to the ref parameter before use. Ref parameters are passed both into and out of a method.

Loops

1. Define “continue” and “break” statements in C#.

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

Serialization / Deserialization

1. Define  serialization.

Sometime you want to save the state of the object and transmit it another resource then  by using serialization you can convert an object into a stream of bytes to store the object or transmit it to another resource. The reverse process is called deserialization.

2. Define Deserialization.

Deserialization is converting stream of byte to object. Deserialization is the reverse process of serialization. It is the process of getting back the serialization object (so that) it can be loaded into memory. It lives the state of the object by setting properties, fields etc.

I/O Classes:-

1. List the I/O Classes in C#.

System.IO namespace, consisting of classes that supports various operations on files like creating, deleting, opening, closing etc.

File – Helps in manipulating a file.

StreamWriter – Used for writing characters to a stream.

StreamReader – Used for reading characters to a stream.

StringWriter – Used for reading a string buffer.

StringReader – Used for writing a string buffer.

Path – Used for performing operations related to path information.

2. Define StreamReader and StreamWriter class.

StreamReader and StreamWriter are classes of namespace System.IO. They are used  to read or write data.

Cryptography:-

1. Define Cryptography.

Converting or transforming(encryption) data into non-readable data using a specific technique is called cipher-text. In simple word the method of disguising plain text in such a way as to hide its meaning is called 'Encryption'.  To decrypt( decipher) encrypted data into plain text one's requires secret key.  In Dot Net Cryptography is common practice.

2. What is difference in Hashing and Encryption in C#?

A Hashing transform the plain text into  combination of text + number + special characters. Basically it disguises the actual text into non readable text. Hashing is a is a one-way function i.e hashed value cant be reversed However  encryption is a two-way function; what is encrypted can be decrypted with the proper key.

Collections:-

1. Define collection.

Collection are special type of container for storing all types of values and objects. Collection classes in C# provides functions for  data storage and retrieval. Stacks, queues, lists, and hash tables are example of classes.

2. What is enum in C#?

Enumeration (or enum) is a user defined data type in C#. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain.

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

3. Explain Hashtable in C#.

The Hashtable stores the values in form of key/value pairs and it is form of collection. The key-and-value pairs that are organized based on the hash code of the key. To access the value of element key is refereed.

4. How to check existence of specific key in hash table in C#?

ContainsKey  method return true if key is found otherwise  false value.

Example: Hashtbl.ContainsKey("abc");

5. Define IEnumerable<> in c#.

GetEnumerator  is the method of IEnumerable interface which returns an IEnumerator readonly collection.

6. Define  stack in C#.

The collection that implement concept of LIFO(Last In Fisrt Out) data structure.

8. Define System.Array.CopyTo() and System.Array.Clone().

CopyTo() performs a deep copy of the array. It copies the elements of one array to another array. It requires a destination array.

Clone() performs a shallow copy of the array. It creates a copy of an array as an object. It does not require destination array.

9. Define indexers in C#.

Indexers  in c# introduces a new concept used for treating an object as an array. Similar to array instances of a class can be indexed.

10. What is Jagged Arrays?

A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays."

Threading in C#

1. Define Thread.

A Thread is a piece of code  can be executed within parent thread, thread can perform multiple and concurrent processing. Thread has a life cycle.

2. What is Lock statement?

Lock statement put the lock on particular logic so that only one thread can enter and process that piece of code and other threads wait till the thread acquiring the lock release the lock.

3. What is Thread Pooling?

Thread pooling is like a container where multiple thread can resides. Whenever multi threading application is internationalized  thread from pool is used and after completion of task thread return to pool and when new task started the thread from pool takes that task.

4. List different states of a Thread.

Unstarted – 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.

ADO.NET

1. What is an ADO.Net?

ADO.Net is commonly termed as ActiveX Data Objects which is a part of .Net Framework. ADO.NET is a collection of managed libraries used by .NET applications for connecting different type of databases.

2. What are two important objects of ADO.Net?

DataReader and DataSet.

3. What is the use CommandBehaviour.CloseConnection?

We can use it command object in ExecuteReader

rdr=command.ExecuteReader(CommandBehaviour.CloseConnection);

Above will make sure that after executing command connection will be closed.

Exceptions

1. Define implementation of  Exception Handling in C#.

try : Contains a block of code for which an exception will be checked.
catch : It is a program that catches an exception with the help of exception handler.
finally : It always executes  whether an exception is caught or not.
Throw : Throws an exception when a exception occurs.

2. Define  “throw” and “throw ex” in C#.

If you want to see original error then you can use "Throw" and to see the stack trace(origin point and details of error) you can use "Throw ex".

3. What are Custom Exceptions?

To create business rule violations or other requirement you can crate customs exceptions classes ApplicationException  must be inherited to create a custom exception class.

4. Define inner exception in C#.

Inner exception provides parent exception and child exception details.

5. Can finally block have error in C#?

Yes. even in finally block you can another try catch block.

6. Define  “finally” block in C#.

“Finally” block  is called irrespective of exception. You can use finally block for closing database connection or closing native file connection.

Reflection

1. Define reflection in C#.

Reflection in  Dot NET is used to gather  information about loaded assemblies and the types defined within, such as classes, interfaces, and value types.

Others

1. What is Garbage Collection?

Whenever a new object is created then CLR(Common Language Runtime) allocates memory for the object from heap. Garbage collector is responsible for cleaning memory bu collection those objects which are not in use any longer and frees memory.

2. What is the use of using statement in C#?

using statement will automatically dispose of the object once that context is complete,The using statement  implements the IDisposable interface.

3. What is object pool in .Net?

Object Pooling means more than one objects residing in a container. The purpose of pooling objects is reuse of object and reducing the load of objects creating again and again.

Conclusion

In C Sharp Interview questions and answers I have tried to cover almost all topics of C# language and C# Dot Net Framework. However in interview question on C# could be random but my experience says generally interviewer starts from basic questions and moves on advance questions.

 

See Also PHP Interview Questions And Answers
See Also : Asp.Net Interview Question And Answers