Now, let us take a look at the top 60 .Net / C# interview questions that you might face!
1. Discuss the various methods to pass parameters in a method.
The various methods of passing parameters in a method include –
- Output parameters: Lets the method return more than one value.
- Value parameters: The formal value copies and stores the value of the actual argument, which enables the manipulation of the formal parameter without affecting the value of the actual parameter.
- Reference parameters: The memory address of the actual parameter is stored in the formal argument, which means any change to the formal parameter would reflect on the actual argument too.
2. Name all the C# access modifiers.
The C# access modifiers are –
- Private Access Modifier – A private attribute or method is one that can only be accessed from within the class.
- Public Access Modifier – When an attribute or method is declared public, it can be accessed from anywhere in the code.
- Internal Access Modifier – When a property or method is defined as internal, it can only be accessible from the current assembly point of that class.
- Protected Access Modifier – When a user declares a method or attribute as protected, it can only be accessed by members of that class and those who inherit it.
3. Mention the features of C# briefly.
Some of the main features of C# are –
- C# is a safely typed and managed language.
- C# is object-oriented in nature.
- C# is a Cross-platform friendly language.
- C# is a platform-independent language when it comes to compilation.
- C# is general purpose in nature.
- C# is used in implementing Destructors and Constructors.
- C# is part of the .NET framework.
- C# is an easy-to-learn and easy-to-grasp language.
- C# is a structured language.
4. What is meant by Unmanaged or Managed Code?
In simple terms, managed code is code that is executed by the CLR (Common Language Runtime). This means that every application code is totally dependent on the .NET platform and is regarded as overseen in light of it. Code executed by a runtime programme that is not part of the .NET platform is considered unmanaged code. Memory, security, and other activities related to execution will be handled by the application’s runtime.
5. Differentiate between finalize blocks and finalize.
Once the try and catch blocks have been completed, the finalize block is called since it is used for exception handling. No matter if the exception has been captured, this block of code is run. In general, the code in this block is cleaner.
Just before garbage collection, the finalize method is called. The main priorities of the finalize method are to clean up unmanaged code, which is automatically triggered whenever an instance is not re-called.
6. What is meant by an Interface?
An interface is a class that does not have any implementation. Only the declarations of events,
7. List down the most commonly used types of exceptions in .NET
Commonly used types of exceptions in .NET are:
ArgumentException
ArithmeticException
DivideByZeroException
OverflowException
InvalidCastException
InvalidOperationException
NullReferenceException
OutOfMemoryException
StackOverflowException
8. Write features of Generics in C#?
Generics is a technique to improve your program in various ways including creating generic classes and reusing code.
9. Difference between SortedList and SortedDictionary in C#.
SortedList is a collection of value pairs sorted by their keys. SortedDictionary is a collection to store the value pairs in the sorted form, in which the sorting is done on the key.
10. What is Singleton design pattern in C#?
Singleton design pattern in C# has just one instance that gives global access to it.
10. What is tuple in C#?
Tuple is a data structure to represent a data set that has multiple values that could be related to each other.
11. What are Events?
An event is a notice that something has occurred.
12. What is LINQ in C#?
LINQ refers to Language Integrated Query. It provides .NET languages (like C#) the ability to generate queries to retrieve data from the data source.
13. Why can’t a private virtual procedure in C# be overridden?
Private virtual methods are not accessible outside of the class.
14. What do you understand about Get and Set Accessor properties?
In C#, Get and Set are termed accessors because they use properties. Such private fields are accessed via accessors.
15. What is the Race condition in C#?
When 2 threads access the same resource and try to change it at the same time, we have a race condition.
16. Why are Async and Await used in C#?
Asynchronous programming processes execute independently of the primary or other processes. Asynchronous methods in C# are created using the Async and Await keywords.
17. What is an Indexer in C#?
An indexer is a class property that allows you to access a member variable of another class using array characteristics.
18. What is Thread Pooling in C#?
In C#, a Thread Pool is a group of threads. These threads are used to do work without interfering with the principal thread’s operation.
19. Discuss the various methods to pass parameters in a method.
The various methods of passing parameters in a method include –
- Output parameters: Lets the method return more than one value.
- Value parameters: The formal value copies and stores the value of the actual argument, which enables the manipulation of the formal parameter without affecting the value of the actual parameter.
- Reference parameters: The memory address of the actual parameter is stored in the formal argument, which means any change to the formal parameter would reflect on the actual argument too.
20. What is Common Language Runtime (CLR)?
CLR handles program execution for various languages including C#. The architecture of CLR handles memory management, garbage collection, security handling, and looks like:
Architecture of CLR
21. What is garbage collection in C#?
Garbage collection is the process of freeing up memory that is captured by unwanted objects. When you create a class object, automatically some memory space is allocated to the object in the heap memory. Now, after you perform all the actions on the object, the memory space occupied by the object becomes waste. It is necessary to free up memory. Garbage collection 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
22. What is a managed and unmanaged code?
Managed code lets you run the code on a managed CLR runtime environment in the .NET framework.
Managed code runs on the managed runtime environment than the operating system itself.
Benefits: Provides various services like a garbage collector, exception handling, etc.
Unmanaged code is when the code doesn’t run on CLR, it is an unmanaged code that works outside the .NET framework.
They don’t provide services of the high-level languages and therefore, run without them. Such an example is C++.
23. What are extension methods in C#?
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
usingSystem;
namespaceExtensionMethod
{
staticclass
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
publicclass
IB
{
// Main Method
public static void Main(string[] args)
{
Scaler s =
newScaler();
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
24. What are Generics in C#?
In C# collections, defining any kind of object is termed okay which compromises C#’s basic rule of type-safety. Therefore, generics were included to type-safe the code by allowing re-use of the data processing algorithms. Generics in C# mean not linked to any specific data type. Generics reduce the load of using boxing, unboxing, and typecasting objects. Generics are always defined inside angular brackets <>. To create a generic class, this syntax is used:
GenericList<float> list1 = new GenericList<float>();
GenericList<Features> list2 = new GenericList<Features>();
GenericList<Struct> list3 = new GenericList<Struct>();
Here, GenericList<float> is a generic class. In each of these instances of GenericList<T>, every occurrence of T in the class is substituted at run time with the type argument. By substituting the T, we have created three different type-safe using the same class.
25. What are the Arrays in C#?
When a group of similar elements is clubbed together under one name, they are called arrays.
For ex. An array of tea Atea[4]: [green tea, chamomile tea, black tea, lemon tea]. The length of the array defines how many elements are present in the array.
In C#, the memory allocations for the elements of the array happen dynamically. This is how values are stored in an array sequentially.
Arrays in C#
A few pointers for arrays in C#:
- The memory allocation is DYNAMIC.
- Arrays in C# are treated as objects.
- The length of the array is easy to find by detecting the number of members in the array.
- The members in the array are ordered and begin with the index value=0.
- The array types are reference types derived from the base array type.
Syntax: < Data Type > [ ] < Name_Array >
26. What are Indexers in C#?
Indexers are called smart arrays that allow access to a member variable. Indexers allow member variables using the features of an array. They are created using the Indexer keyword. Indexers are not static members.
For ex. Here the indexer is defined the same way.
<
returntype>
this[<parameter type> index]
{
get
{
// return the value from the specified index of an internal collection
}
set
{
// set values at the specified index in an internal collection
}
}
27. Difference between the Equality Operator (==) and Equals() Method in C#?
Although both are used to compare two objects by value, still they both are used differently.
For ex.:
intx =
10;
inty =
10;
Console.WriteLine( x == y);
Console.WriteLine(x.Equals(y));
Output:
True
True
Equality operator (==) is a reference type which means that if equality operator is used, it will return true only if both the references point to the same object.
Equals() method: Equals method is used to compare the values carried by the objects. int x=10, int y=10. If x==y is compared then, the values carried by x and y are compared which is equal and therefore they return true.
Equality operator: Compares by reference
28. What is Reflection in C#?
Reflection in C# extracts metadata from the datatypes during runtime.
To add reflection in the .NET framework, simply use System.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
29) What is an Array? Give the syntax for a single and multi-dimensional array?
Answer: An Array is used to store multiple variables of the same type. It is a collection of variables stored in a contiguous memory location.
For Example:
double numbers = new double[10];
int[] score = new int[4] {25,24,23,25};
A single dimensional array is a linear array where the variables are stored in a single row. Above example is a single dimensional array.
Arrays can have more than one dimension. Multidimensional arrays are also called rectangular arrays.
For Example, int[,] numbers = new int[3,2] { {1,2} ,{2,3},{3,4} };
30) What is a Jagged Array?
Answer: A Jagged array is an array whose elements are arrays. It is also called as the array of arrays. It can be either single or multiple dimensions.
int[] jaggedArray = new int[4][];
31) Name some properties of Array.
Answer: Properties of an Array include:
- Length: Gets the total number of elements in an array.
- IsFixedSize: Tells whether the array is fixed in size or not.
- IsReadOnly: Tells whether the array is read-only or not.
32) What is an Array Class?
Answer: An Array class is the base class for all arrays. It provides many properties and methods. It is present in the namespace system.
33) What is a String? What are the properties of a String Class?
Answer: A String is a collection of char objects. We can also declare string variables in c#.
string name = “C# Questions”;
A string class in C# represents a string. The properties of the string class are:
- Chars get the Char object in the current String.
- Length gets the number of objects in the current String.
34) What is an Escape Sequence? Name some String escape sequences in C#.
Answer: An Escape sequence is denoted by a backslash (\). The backslash indicates that the character that follows it should be interpreted literally or it is a special character. An escape sequence is considered as a single character.
String escape sequences are as follows:
- \n – Newline character
- \b – Backspace
- \\ – Backslash
- \’ – Single quote
- \’’ – Double Quote
35) What are Regular expressions? Search a string using regular expressions?
Answer: 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.
36) What are the basic String Operations? Explain.
Answer: Some of the basic string operations are:
- Concatenate: Two strings can be concatenated either by using a System.String.Concat or by using + operator.
- Modify: Replace(a,b) is used to replace a string with another string. Trim() is used to trim the string at the end or at the beginning.
- Compare: System.StringComparison() is used to compare two strings, either a case-sensitive comparison or not case sensitive. Mainly takes two parameters, original string, and string to be compared with.
- Search: StartWith, EndsWith methods are used to search a particular string.
37) What is Parsing? How to Parse a Date Time String?
Answer: Parsing converts a string into another data type.
For Example:
string text = “500”;
int num = int.Parse(text);
500 is an integer. So, the Parse method converts the string 500 into its own base type, i.e int.
Follow the same method to convert a DateTime string.
string dateTime = “Jan 1, 2018”;
DateTime parsedValue = DateTime.Parse(dateTime);
Advanced Concepts
38) What is a Delegate? Explain.
Answer: A Delegate is a variable that holds the reference to a method. Hence it is a function pointer or reference type. All Delegates are derived from System.Delegate namespace. Both Delegate and the method that it refers to can have the same signature.
- Declaring a delegate: public delegate void AddNumbers(int n);
After the declaration of a delegate, the object must be created by the delegate using the new keyword.
AddNumbers an1 = new AddNumbers(number);
The delegate provides a kind of encapsulation to the reference method, which will internally get called when a delegate is called.
public delegate int myDel(int number); public class Program { public int AddNumbers(int a) { int Sum = a + 10; return Sum; } public void Start() { myDel DelgateExample = AddNumbers; } } |
In the above example, we have a delegate myDel which takes an integer value as a parameter. Class Program has a method of the same signature as the delegate, called AddNumbers().
If there is another method called Start() which creates an object of the delegate, then the object can be assigned to AddNumbers as it has the same signature as that of the delegate.
39) What are Events?
Answer: Events are user actions that generate notifications to the application to which it must respond. The user actions can be mouse movements, keypress and so on.
Programmatically, a class that raises an event is called a publisher and a class which responds/receives the event is called a subscriber. Event should have at least one subscriber else that event is never raised.
Delegates are used to declare Events.
Public delegate void PrintNumbers();
Event PrintNumbers myEvent;
40) How to use Delegates with Events?
Answer: Delegates are used to raise events and handle them. Always a delegate needs to be declared first and then the Events are declared.
Let us see an example:
Consider a class called Patient. Consider two other classes, Insurance, and Bank which requires Death information of the Patient from patient class. Here, Insurance and Bank are the subscribers and the Patient class becomes the Publisher. It triggers the death event and the other two classes should receive the event.
namespace ConsoleApp2 { public class Patient { public delegate void deathInfo();//Declaring a Delegate// public event deathInfo deathDate;//Declaring the event// public void Death() { deathDate(); } } public class Insurance { Patient myPat = new Patient(); void GetDeathDetails() { //-------Do Something with the deathDate event------------// } void Main() { //--------Subscribe the function GetDeathDetails----------// myPat.deathDate += GetDeathDetails; } } public class Bank { Patient myPat = new Patient(); void GetPatInfo () { //-------Do Something with the deathDate event------------// } void Main() { //--------Subscribe the function GetPatInfo ----------// myPat.deathDate += GetPatInfo; } } } |
41) What are the different types of Delegates?
Answer: 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);
42) What do Multicast Delegates mean?
Answer: A Delegate that points to more than one method is called a Multicast Delegate. Multicasting is achieved by using + and += operator.
Consider the example from Q #32.
There are two subscribers for deathEvent, GetPatInfo, and GetDeathDetails. And hence we have used += operator. It means whenever the myDel is called, both the subscribers get called. The delegates will be called in the order in which they are added.
43) Explain Publishers and Subscribers in Events.
Answer: Publisher is a class responsible for publishing a message of different types of other classes. The message is nothing but Event as discussed in the above questions.
From the Example in Q #32, Class Patient is the Publisher class. It is generating an Event deathEvent, which is received by the other classes.
Subscribers capture the message of the type that it is interested in. Again, from the Example of Q#32, Class Insurance and Bank are Subscribers. They are interested in event deathEvent of type void.
44) What are Synchronous and Asynchronous operations?
Answer: Synchronization is a way to create a thread-safe code where only one thread can access the resource at any given time. The asynchronous call waits for the method to complete before continuing with the program flow.
Synchronous programming badly affects the UI operations when the user tries to perform time-consuming operations since only one thread will be used. In Asynchronous operation, the method call will immediately return so that the program can perform other operations while the called method completes its work in certain situations.
In C#, Async and Await keywords are used to achieve asynchronous programming. Look at Q #43 for more details on synchronous programming.
45) What is a Thread? What is Multithreading?
Answer: A Thread is a set of instructions that can be executed, which will enable our program to perform concurrent processing. Concurrent processing helps us do more than one operation at a time. By default, C# has only one thread. But the other threads can be created to execute the code in parallel with the original thread.
Thread has a life cycle. It starts whenever a thread class is created and is terminated after the execution. System.Threading is the namespace which needs to be included to create threads and use its members.
Threads are created by extending the Thread Class. Start() method is used to begin thread execution.
//CallThread is the target method//
ThreadStart methodThread = new ThreadStart(CallThread);
Thread childThread = new Thread(methodThread);
childThread.Start();
C# can execute more than one task at a time. This is done by handling different processes by different threads. This is called MultiThreading.
There are several thread methods that are used to handle multi-threaded operations:
Start, Sleep, Abort, Suspend, Resume and Join.
Most of these methods are self-explanatory.
46) Name some properties of Thread Class.
Answer: Few Properties of thread class are:
- 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.
47) What are the different states of a Thread?
Answer: Different states of a thread are:
- 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.
48) What are Async and Await?
Answer: Async and Await keywords are used to create asynchronous methods in C.
Asynchronous programming means that the process runs independently of main or other processes.
Usage of Async and Await is as shown below:
- Async keyword is used for the method declaration.
- The count is of a task of type int which calls the method CalculateCount().
- Calculatecount() starts execution and calculates something.
- Independent work is done on my thread and then await count statement is reached.
- If the Calculatecount is not finished, myMethod will return to its calling method, thus the main thread doesn’t get blocked.
- If the Calculatecount is already finished, then we have the result available when the control reaches await count. So the next step will continue in the same thread. However, it is not the situation in the above case where the Delay of 1 second is involved.
49) What is a Deadlock?
Answer: A Deadlock is a situation where a process is not able to complete its execution because two or more processes are waiting for each other to finish. This usually occurs in multi-threading.
Here a shared resource is being held by a process and another process is waiting for the first process to release it and the thread holding the locked item is waiting for another process to complete.
Consider the below Example:
- Perform tasks accesses objB and waits for 1 second.
- Meanwhile, PerformtaskB tries to access ObjA.
- After 1 second, PeformtaskA tries to access ObjA which is locked by PerformtaskB.
- PerformtaskB tries to access ObjB which is locked by PerformtaskA.
This creates Deadlock.
50) Explain Lock, Monitors, and Mutex Object in Threading.
Answer: 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.
Monitor.Enter(ObjA);
try
{
}
Finally {Monitor.Exit(ObjA));}
51) What is a Race Condition?
Ans: 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.
52) What is Thread Pooling?
Ans: 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.
53) What is Serialization?
Answer: 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.
54) What are the types of Serialization?
Answer: 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.
55) What is an XSD file?
Answer: 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.
Beginner’s Level
56. Illustrate Serialization?
Ans- A process that involves converting some code into its binary format is known as a serialization in C#. In doing so it gives the flexibility where code can be stored easily and or written to a disk or some other storage device. Serialization is used when there is a strict need for not losing the original code.
Serialization in C# is of three types:
Binary Serialization- It is fast and demands less space, converts any code into its binary format. Serialize and restore public and non-public properties.
SOAP- Generates a complete SOAP compliant envelope used by any system by its ability to understand SOAP. Classes under this type of Serialization reside in System.Runtime.Serialization.
XML Serialization- It serializes all the public properties to XML document. Readability being one factor, an XML document can also be manipulated in various ways. Classes under this type reside in System.sml.Serialization.
To know more about Serialization in Java, check out the following blog:
57. Define Parsing? Explain how to Parse a DateTime String?
Ans- Parsing is a method of converting a string into another data type.
Example:
1 2 | string text = "200"; int num = int.Parse(text); |
In the above-given example, 200 is an integer. So, the Parse method converts the string 200 into its own base type, i.e. int.
To parse a DateTime String let’s see a small example.
Example:
1 | string dateTime = "Aug 26,2019"; Datetime parsedvalue = Datetime.Parse(dateTime); |
58. Explain about generics in C#.NET?
Ans- Generics are used to make reusable code classes which decrease the code redundancy,
- Increase type safety, performance, and optimization
- Using Generics one can do a variety of things like create collections
- To create Generic collection, System.namespace
- The generic namespace should be used inspite of classes such as ArrayList in the System
- Generics instigates the usage of a parameterized type
59. Explain Synchronous and Asynchronous Operations?
Ans- Synchronization is a way of creating a thread-safe code where only a single thread will access the code in a given time. A synchronous call waits for completion of method and then continous the program flow. Synchronous programming adversely affects the UI operations that normally happens when user tries to perform time-consuming operations since only one thread is used.
In Asynchronous operation, the method call immediately returns allowing the program to perform other operations while the method called completes its share of work in certain circumstances.
60. Explain Async and Await?
Ans- Async and Await keywords are mostly used for creating asynchronous methods in C#. Usage of the same is shown through an example:
1 2 3 4 5 6 7 8 9 10 | 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.
.
61. Illustrate Race Condition?
Ans- A Race Condition occurs in a situation when two threads access the same resource and try to change it at the same time. The thread which accesses the resource first cannot be predicted. Let me take a small example where two threads X1 and X2 are trying to access the same shared resource called T. And if both threads try to write the value to T, then the last value written to T will be saved.
62. What is Thread Pooling?
Ans- A Thread pool is a collection of threads that perform tasks without disturbing the primary thread. Once the task is completed by a thread it returns to the primary thread.
This brings us to the end of this article on C# Interview Questions. I hope it helped in adding up to your knowledge. Wishing you all the best for your interview.
63.What are dynamic type variables in C#?
Answer
You can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time.
64.Can you return multiple values from a function in C#? Provide some examples.
Answer
There are several ways.
Use ref / out parameters. A return statement can be used for returning only one value from a function. However, using output parameters, you can return two values from a function.
Consider:
privatestatic
void
Add_Multiply(int
a
,int
b
,ref
int
add,
ref
int
multiply
)
{
add
=
a
+b
;
multiply
=a
*b
;
}
or
privatestatic
void
Add_Multiply(int
a
,int
b
,out
int
add,
out
int
multiply
)
{
add
=
a
+b
;
multiply
=a
*b
;
}
Another way is to use <Tuple>
:
privatestatic
Tuple
<int,int>
Add_Multiply(int
a
,int
b
)
{
var
tuple
=new
Tuple<int, int>(
a
+b
,a
*b
);
return
tuple
;
}
Now that C# 7 has been released, you can use the new included Tuples syntax:
(string,string,
string)
LookupName(long
id
)// tuple return type
{
...
// retrieve first, middle and last from data storage
return
(
first
,middle
,last
);// tuple literal
}
which could then be used like this:
varnames
=LookupName(
id
);
WriteLine($
"found {names.Item1} {names.Item3}.");
65.Explain Anonymous type in C#
Answer
Anonymous types allow us to create a new type without defining them. This is way to defining read only properties into a single object without having to define type explicitly. Here Type is generating by the compiler and it is accessible only for the current block of code. The type of properties is also inferred by the compiler.
Consider:
varanonymousData
=new
{
ForeName
="Jignesh",
SurName
="Trivedi"
};
Console
.WriteLine("First Name : "+
anonymousData
.ForeName
);
66.Explain the difference between Task and Thread in .NET
Answer
- Thread represents an actual OS-level thread, with its own stack and kernel resources. Thread allows the highest degree of control; you can
Abort()
orSuspend()
orResume()
a thread, you can observe its state, and you can set thread-level properties like the stack size, apartment state, or culture.ThreadPool
is a wrapper around a pool of threads maintained by the CLR. - The Task class from the Task Parallel Library offers the best of both worlds. Like the
ThreadPool
, a task does not create its own OS thread. Instead, tasks are executed by aTaskScheduler
; the default scheduler simply runs on the ThreadPool. Unlike the ThreadPool, Task also allows you to find out when it finishes, and (via the generic Task) to return a result.
67.What is lambda expressions in C#?
Answer
A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions.
In the following example, the lambda expression x => x * x
, which specifies a parameter that’s named x
and returns the value of x
squared, is assigned to a variable of a delegate type:
Func
<int,int>
square
=x
=>x
*x
;
Console
.WriteLine(square(5));
// Output:
// 25
good read