c sharp Interview Questions

20 Important C# interview questions for experienced

Spread the love

Lets quickly brush up through these top 20 most Important C# interview questions for experienced.
If you’re planning to attend an Interview on C#, and now you think, where should I focus to get prepared for C#?. Then I am bringing out this article, to make sure that you qualify. I am listing here my top 20 C# interview questions for experienced questions and their answers.
Questions asked for those having experience in C# language.

1. What is C# and what are the compilers used in C#?

C# is an object-oriented programming language built by Microsoft in 2000 . It is type-safe , versatile,performance-oriented language and a well-managed programming language.C# that is compiled by the .Net. a framework to generate Microsoft Intermediate Language.C# running on Visual Studio gives it the utmost features of debugging and use various of its features.
C# can be used to develop all kinds of software targeting various platforms including Windows, Web, and Mobile (Android/IOS/Windows)

In c# there are two compilers:

Compile Time:C# Compiler – This converts your written code to Intermediate level code .
Run Time: Just In Time Compiler – This Converts Intermediate Level Code to Native Code

2. Explain different access specifiers used in C#.

private: U can access the members-only for that same class
public:U can access from anywhere in our outside the assembly
internal:You can access only under particular assembly
protected: You can access only for the inherited class
Protected internal: You can access only the inherited class for that particular assembly

oaccess SpecifierSame Assembly containing ClassSame assembly Derived ClassDifferent assemblyOutside containing assembly
publicyyyy
protected internalyyyn
protectedyynn
internal ynyn
privateynnn

3.Explain Encapsulation and Abstraction, and also state how it differs from one another.

You can read the full article over here.

4.Difference between Iqueryable and IEnumerable.

 IEnumerableIQueryable
NamespaceSystem.Collections NamespaceSystem.Linq Namespace
Derives fromNo base interfaceDerives from IEnumerable
Deferred ExecutionSupportedSupported
Lazy LoadingNot SupportedSupported
How does it workWhile querying data from the database, IEnumerable executes a select query on the server-side, load data in-memory on client-side, and then filter data. Hence does more work and becomes slow.While querying data from the database, IQueryable executes select query on the server-side with all filters. Hence does less work and becomes fast.
Suitable forLINQ to Object and LINQ to XML queriesLINQ to SQL queries
Custom QueryDoesn’t supportSupports using CreateQuery and Execute methods
Extension method
parameter
Extension methods supported in IEnumerable takes functional objects.Extension methods supported in IEnumerable takes expression objects, i.e., expression tree.
When to useWhen querying data from in-memory collections like List, Array, etc.When querying data from out-memory (like remote database, service) collections.
Best UsesIn-memory traversalPaging

5.Difference between List and ArrayList.

The List is the type-safe conversion of ArrayList, this means that there is no unboxing and boxing. So performance is good.

List:
Index-based.
It’s generic

ArrayList:
Index-based
Non-Generic

6. Difference between Method Overloading, overriding, and hiding.

class Base {
    int a;
    public void Addition() {
        Console.WriteLine("Addition Base");
    }
    public virtual void Multiply()
    {
        Console.WriteLine("Multiply Base");
    }
    public void Divide() {
        Console.WriteLine("Divide Base");
    }
}

class Child : Base
{
    new public void Addition()
    {
        Console.WriteLine("Addition Child");
    }
    public override void Multiply()
    {
        Console.WriteLine("Multiply Child");
    }
    new public void Divide()
    {
        Console.WriteLine("Divide Child");
    }
}
class Program
{        
    static void Main(string[] args)
    {
        Child c = new Child();
        c.Addition();
        c.Multiply();
        c.Divide();

        Base b = new Child();
        b.Addition();
        b.Multiply();
        b.Divide();

        b = new Base();
        b.Addition();
        b.Multiply();
        b.Divide();
    }
}	
class Base {
    int a;
    public void Addition() {
        Console.WriteLine("Addition Base");
    }
    public virtual void Multiply()
    {
        Console.WriteLine("Multiply Base");
    }
    public void Divide() {
        Console.WriteLine("Divide Base");
    }
}

class Child : Base
{
    new public void Addition()
    {
        Console.WriteLine("Addition Child");
    }
    public override void Multiply()
    {
        Console.WriteLine("Multiply Child");
    }
    new public void Divide()
    {
        Console.WriteLine("Divide Child");
    }
}
class Program
{        
    static void Main(string[] args)
    {
        Child c = new Child();
        c.Addition();
        c.Multiply();
        c.Divide();

        Base b = new Child();
        b.Addition();
        b.Multiply();
        b.Divide();

        b = new Base();
        b.Addition();
        b.Multiply();
        b.Divide();
    }
}
Output : -
Addition Child ,Multiply Child ,Divide Child ,Addition Base, Multiply Child, Divide Base, Addition Base ,Multiply Base ,Divide Bas

6. What is ICollection Interface

The ICollection interface is inherited from the IEnumerable interface which means that any class that implements the ICollection interface can also be enumerated using a for each loop. In the IEnumerable interface, we don’t know how many elements there are in the collection whereas the ICollection interface gives us this extra property for getting the count of items in the collection. The ICollection interface contains the following

7.Difference between authentication and authorizaion

Authentication means the given credentials by which one user logins into the system or anything, while authorization is to give restriction to authenticated users to handle method.

[Authorized Users, Admin ]Public ActionResult Index()
{
}

[Authorized Admin ]//authenticated admin can only access this is authorization.
Public ActionResult Save()
{
}

8.What is an interface ?

The interface is an abstract class which has only public abstract methods.
Abstract Methods is just declared, it does not have any implementations.

interface admin
{
string GetName();
void GetFullName();
}

9.What are Asynchronous programming in C#?

When we are checking with certain UI where on button click, we have a big method like reading or importing a large file, in that case, the entire application must wait to complete the whole task.

In other words, if a certain process or code is blocked in a synchronous application, the entire application gets blocked and our application halts responding until the whole task completes.

At such cases, Using Asynchronous programming is very needful and helpful as with this technique we continue with the other work that does not depend on the completion of the whole task. Asynchronous programming comes into needful by the help of async and await keywords.

Example:
Suppose, we are using two methods as Method1 and Method2 respectively and both the methods are not dependent on each other and Method1 is taking a long time to complete its task. In Synchronous programming, it will execute the first Method1 and it will wait for the completion of this method, and then it will execute Method2. Thus, it will be a time-saving process.

We can run all the methods parallelly by using simple thread programming but it will block UI and wait to complete all the tasks. To come out of this problem, we have to write too many codes in traditional programming but if we will simply use the async and await keywords, then we will get the solutions in much less code.

Async and await are the code markers, which marks code positions from where the control should resume after a task completes.

Let’s start with practical examples for understanding the programming concept. Sample examples of async and await keyword in C#

Console Application


Example 1

In this example, we are going to take two methods, which are not dependent on each other.

Code sample 

class Program  
{  
    static void Main(string[] args)  
    {  
        Method1();  
        Method2();  
        Console.ReadKey();  
    }  
  
    public static async Task Method1()  
    {  
        await Task.Run(() =>  
        {  
            for (int i = 0; i < 100; i++)  
            {  
                Console.WriteLine(" Method 1");  
            }  
        });  
    }  
  
  
    public static void Method2()  
    {  
        for (int i = 0; i < 25; i++)  
        {  
            Console.WriteLine(" Method 2");  
        }  
    }  
}  
In the code given above, Method1 and Method2 are not dependent on each other and we are calling from the Main method.
Here, we can clearly see Method1 and Method2 are not waiting for each other.

Output
method 1
method 2
mthpd 2
method1
.....

10.Difference between all the http verbs.

11. What are delegates?

Delegates are just like function pointers, which are type-safe, unlike function pointers. They can be used to write much more generic type-safe functions.

using System;

public delegate void YourDelegate(string msg);

public class Program
{
	public static void Main()
	{
		YourDelegate del = A.MethodA;
		del("Hello tenoclocks");
			
		del = B.MethodB;
		del("Welcome");
		
	}
}

public class A
{
	public static void MethodA(string message)
	{
		Console.WriteLine("A"+ message);
	}
}

public class B
{
	public static void MethodB(string message)
	{
		Console.WriteLine("B"+ message);
	}
}

12.Exceptions & Exception Handling:

Generally under every program, we will be coming across errors which are of 2 types:
-Compile Time Errors
-Run-Time Errors

-A compile-time error occurs due to the syntactical mistake that occurs in a program, these are not considered to be dangerous.

-A runtime error also known as an Exception occurs under a program while the execution of the program is taking place this can be due to various reasons like the wrong implementation of logic, invalid input supplied to the program etc., these errors are considered to be dangerous because when they occur under the program the program terminates abnormally without executing the next lines of code.

13. What happens when an exception or runtime error occurs under a program?

Whenever an exception occurs in a program on a certain line, the execution of the program stops immediately on the line without executing the next lines of code as well as displays an error msg related to the error.

As a programmer, every exception is a class that is defined under the system namespace. The parent class for all these exception classes is “Exception”.

To stop the abnormal termination that occurs when an exception occurs we are provided with an approach known as “Exception Handling”, which allows u to stop the abnormal termination as well as can be used to display user-friendly error msgs to the end-users.

14. How to perform Exception Handling within a program?

To perform Exception Handling we were provided with 2 blocks of code known as “try..catch” blocks, which has to be used as follows:

try
{
//Statement
}
catch (Exception ex ) or Exception()
{
//throw exception
//Catch the exception in your log file
}

15.What are OOPS principles?

Traditional languages like “C” are known to be Procedural languages that don’t provide features likes Code Security and Code Re-usability.

-To provide the above features a new approach in programming has been introduced as Object-Oriented Approach.

-OOPs languages support security and re-usability, to call a language as object-oriented it needs to satisfy the following principles:
-Abstraction
-Encapsulation
-Inheritance
-Polymorphism

Abstraction: These principles talk about hiding the complexity by providing the user with a set of interfaces to drive the functionalities.

Encapsulation: This principle talks about wrapping the code under a container known as “Class” which is going to protect the content inside, as wrappers always protect the content in them.

Inheritance: according to this principles if there is a parent-child relationship between any 2 the property of the parent can be acquired by their children, so in the same way if u can establish parent-child relationships between classes, the code in 1 class can be consumed in the other, also referred as reusability of the code.

Polymorphism: Entities behaving in different ways depending upon the input they receive is known as polymorphism, which allows u to give the same name for more than 1 method present in a class.

//No Input & Output
void Test1()
{
Console.WriteLine(“First Method”);
}

//No Output Has Input
void Test2(int x)
{
Console.WriteLine(“Second Method: ” + x);
}

//No Input Has Output
string Test3()
{
return “Third Method”;
}

//Has Input & Output
string Test4(string name)
{
return “Hello ” + name;
}

//Returns multiple values
int Test5(int x, int y, ref int z)
{
z = x * y;
return x + y;
}

a = p.Test5(100, 25, ref b);
b = [ new ( [] ) ]

Program p; //p is a variable
p = new Program(); //p is a object
or
Program p = new Program(); //p is a object

Note: The object of the class in java & .net programming languages gets created only with the use of “new” keyword, if new is not used it is considered as a variable of the class which will not occupy any space in the memory.

17. What is multithreading and advantages of using Multithreading? ?  

Multithreading is used to execute multiple methods or multiple applications are work simultaneously.  

Using multi-threading we can break a complex task in a single application into multiple threads and they execute independently and simultaneously.

Thread is a class, using this class we can create multiple threads. This class is used for creating and managing the created thread.  

“ System.Threading”  is the namespace.  

18. Can you explain in brief how can we implement threading?  

i)  Import the API, like  
using System. Threading;

ii) Create the thread, like
Thread th = new Thread(method name); iii) Start the thread, like th.Start( );  

Thread.Sleep( ) in Threading?  

The Thread.Sleep( ) method deactivates the current executed thread features. This method takes the expiry time. After the expiry time thread will execute automatically.   Eg: Thread.Sleep(1000):  
** Time is in milliseconds.  

The Thread.Start( ) method is used to start the created thread. Eg: threadObject.Start( );  

The Thread.Suspend( ) method deactivates the executed thread features. This method features can be reusable in the application by using Thread.Resume( );

19.Collections in C#.

There are two types of collections available in C#:
a.non-generic collections and
b.generic collections

Genric Collection:
1.Dictionary
key/value pairs and provides functionality similar to that found in the non-generic Hashtable class

2.List
Simple Easy , where a list of pairs without a key u can make

3.Queue<T>
first-in, first-out list

4.Stack<T>
first-in, last-out list

5.HashSet<T>
 an unordered collection of the unique elements

6.Linkedlist<T>
fast inserting and removing of element

7.SortedList
sorted list of key/value pairs

NonGeneric

ArrayList
Dynamic array

Hashtable
collection of key-and-value pairs

Queue
 First-in, first out collection of objects

Stack
Last In, First Out

20.Ajax in C#

AJAX allows the user to interact with web pages asynchronously by exchanging small amounts of data with the server behind the scenes .

    $.ajax({
                type: 'post',
                url: 'url',
                data: { data: data},
                dataType: 'json',
                success: function (res) {
                   if (res == "Success") {
                         }
                    },
                failure: function (err) { 
                          alert(err); 
                             }

            })

These are the top 20 most Important C# interview questions for experienced. Kindly check all top 20 Important C# interview questions and earn the benefit of getting a selection.

Other related articles are
20 Important ASP.NET MVC Interview Questions
20 Important SQL Server interview questions for experienced.

Leave a Reply

Your email address will not be published. Required fields are marked *