Kata Library: C# Practice
- Collections
Status: Testing & feedback needed
Estimated rank: 4 kyu, status: waiting for issues to be resolved, estimated rank: 3 kyu, collect: kata.
Loading collection data...
You have not created any collections yet.
Collections are a way for you to organize kata so that you can create your own training routines. Every collection you create is public and automatically sharable with other warriors. After you have added a few kata to a collection you and others can train on the kata contained within the collection.
Get started now by creating a new collection .
Set the name for your new collection. Remember, this is going to be visible by everyone so think of something that others will understand.
Crack the top 45 C# data structure questions
Become a Software Engineer in Months, Not Years
From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.
Data structure questions are some of the most commonly asked in coding interviews. These questions test your ability to implement, optimize, and adapt data structures to solve a unique situation. It’s essential to review common questions before your coding interview to ensure you’re not caught off guard with an unfamiliar question.
Today, we’ll help you brush up on your data structure skills by reviewing 45 of the top data structure questions you should practice before your next interview.
Here’s what we’ll cover today:
Complexity Measures Questions
C# linked lists, c# stacks and queues, c# trees and tries, c# heaps and hashing.
- 20 more questions for C# coding interview
What to learn next
Ace your c# interview the first time practice hundreds of common interview questions with hands-on code environments and instant feedback. data structures for coding interviews in c#, 1. big o complexity: nested addition.
Find the Big O complexity of the following code snippet.
2. Big O complexity: Nested Multiplication
3. big o with nested multiplication (advanced).
Find the Big O complexity of the following code snippet:
4. Remove even integers from an array
Implement a function removeEven( int[]Arr, int size ) , which takes an array arr and its size and removes all the even elements from the given array.
For example:
Solution and Explanation
Time Complexity : O ( n ) O(n) O ( n )
This solution first checks if the first element of Arr is odd. Then it appends this element to the start of the array Arr ; otherwise, it jumps to the next element. This repeats until the end of the array Arr is reached while keeping the count of total odd numbers m in Arr . Next, we make a temporary array, temp , to store all odd numbers.
From there, we delete the memory allocated to Arr , and point it to the temp array. Lastly, we return the array Arr that is, which now contains only odd elements.
5. Find the minimum value in an array
Implement a function findMinimum(int arr[], int size) , which takes an array arr and its size and returns the smallest number in the given array.
Start with the first element (which is 9 in this example), and save it as the smallest value. Then, iterate over the rest of the array. Whenever an element that is smaller than minimum is found, set minimum to that number.
By the end of the array, the number stored in minimum will be the smallest integer in the whole array.
6. Maximum subarray sum
Given an unsorted array Arr , find the collection of contiguous elements that sums to the greatest value.
Hint : Remember that the array could contain negative numbers.
This solution uses Kadane’s algorithm to scan the entire array.
Take a look at Kadane’s algorithm in pseudocode:
At each position in the array, we find the maximum sum of the subarray ending there. This is achieved by keeping a currMax for the current array index and a globalMax . By the end, we know that the value of globalMax will be the highest subarray, regardless of the value of currMax .
Below are the Node and LinkedList classes available for you to use throughout this section:
7. Insertion at Tail
Create a function insertAtTail() that takes an integer, adds the integer to the end of a linked list, and returns the updated linked list. The new node will point to null .
If the list is empty, the situation is exactly like insertion at the head.
Otherwise, you can simply use a loop to reach the tail of the list, and set your new node as the nextElement of the last node.
8. Remove Duplicates from a Linked List
Implement the removeDuplicates() function, which takes a linked list and returns the linked list with no duplicate nodes.
Time Complexity : O ( n 2 ) O(n^2) O ( n 2 )
In this implementation, we check each node against the remaining list to see if a node contains an identical value.
start iterates through the outer loop, while startNext checks for duplicates on line 90 in LinkedList.cs .
Whenever a duplicate is found, it is removed from the list using line 103 .
9. Join two linked lists
Implement the Union() function that takes two linked lists and returns a single linked list that contains all unique elements from both linked lists.
Time Complexity : O ( m + n ) 2 O(m + n)^2 O ( m + n ) 2 where m is the size of the first list, and n is the size of the second list.
Traverse to the tail of the first list, and link it to the first node of the second list on line 125 - 131 in LinkedList.cs . Now, remove duplicates from the combined list.
Below are the implementations of Stacks and Queues available for you to use throughout this section:
10. Generate binary numbers from 1 to N
Implement a function string [] findBin(int n) , which generates binary numbers from 1 to n stored in a String array using a queue.
On line 17 , 1 is enqueued as a starting point. Then, a number is dequeued from the queue and stored in the result array to generate a binary number sequence.
On lines 22-23 , 0 and 1 are appended to it to produce the next numbers, which are then also enqueued to the queue on lines 24-25 . The queue takes integer values. Before enqueueing, the solution makes sure to convert the string to an integer.
The size of the queue should be one more than n because you are enqueuing two variations of each number; one is appended with 0 , and one with 1 .
11. Implement a queue using stacks
Use the myStack class to implement the enqueue() function in the NewQueue class. enqueue() takes an integer and returns true after inserting the value into the queue.
This approach, uses two stacks. The mainStack stores the queue elements and the tempStack acts as a temporary buffer to provide queue functionality.
Make sure that after every enqueue operation, the newly inserted value is at the bottom of the main stack.
Before insertion, all the other elements are transferred to tempStack and naturally, their order is reversed. The new element is added into the empty mainStack . Finally, all the elements are pushed back into mainStack and tempStack becomes empty.
12. Find the lowest value in a stack
Implement the minStack class with the function min() , which returns the lowest value in the stack. min() must have a complexity of O ( 1 ) O(1) O ( 1 ) .
Hint : The element is returned , not popped.
Time Complexity : O ( 1 ) O(1) O ( 1 )
The whole implementation relies on the existence of two stacks: minStack and mainStack .
mainStack holds the actual stack with all the elements, whereas minStack is a stack whose top always contains the current minimum value in the stack.
Whenever push is called, mainStack simply inserts the new value at the top.
However, minStack checks the value being pushed. If minStack is empty, this value is pushed into it and becomes the current minimum. If minStack already has elements in it, the value is compared with the top element.
If the value is lower than the top of minStack , it is pushed in and becomes the new minimum. Otherwise, the top remains the same.
Due to all these safeguards put in place, the min function only needs to return the value at the top of minStack .
Below is an implementation of a Graph available for your use throughout this section. The Graph Class consists of two data members:
- The total number of vertices in the graph
- A list of linked lists to store adjacent vertices
13. Implement Depth First Search (DFS)
Implement a Depth First Search algorithm that can find a passed integer within a graph.
Depth First Search : Starts at the graph’s root node and explores as far as possible along each branch before backtracking.
Time Complexity : O ( V + N ) O(V + N) O ( V + N )
The approach is very similar to that of the BFS solution. However, instead of a queue, use a stack since it follows the Last In First Out (LIFO) approach. You will see how that is useful in this situation.
dfsTraversal calls the helper function dfs_helper on every vertex, which is not visited. dfs_helper starts from source and each node is pushed into the stack. Whenever a node is popped, it is marked “visited” in the visited array, and its adjacent nodes are pushed into the stack.
The stack is helpful because it pops out the new adjacent nodes instead of returning the previous nodes that you pushed in.
14. Find a “Mother Vertex” in a graph
Implement the int findMotherVertex(Graph g) function, which will take a graph as input and find out a mother vertex in the graph. By definition, the mother vertex is one from which all other vertices are reachable.
Time Complexity : O ( V + E ) O(V + E) O ( V + E )
This solution is based in Kosaraju’s Strongly Connected Component Algorithm.
Initially, we run the Depth First Search on the whole graph in a loop on line 17 . The DFS ensures that all the nodes in the graph are visited. If the graph is disconnected, the visited array will still have some vertices, which haven’t been set to true.
The theory is that the last vertex visited in the recursive DFS will be the mother vertex because at the last vertex, all slots in visited would be true (DFS only stops when all nodes are visited); hence, keeping track of this last vertex using lastV .
Then reset the visited array, and run the DFS only on lastV . If it visits all nodes, it is a mother vertex. If not, a mother vertex does not exist.
The only limitation in this algorithm is that it can only detect one mother vertex even if others exist.
15. Remove edge
Implement the remove_Edge() function that takes a source and destination node and deletes any edge between the two.
Reminder : An edge is the connection between two nodes in a graph.
Time Complexity : O ( E ) O(E) O ( E )
Edge connections are handled by our source linked list. We’ll access this source linked list and call our delete() function from line 127 on the node connections between 2 and 3 .
delete() essentially searches for a passed value then removes the node by redirecting the pointer.
Keep practicing C#.
Practice hundreds of hands-on C# questions, each with in-depth explanations. Educative’s text-based courses are easy to skim and feature live practice environments so you can prepare for your interview in half the time.
Data Structures for Coding Interviews in C#
Below is an implementation of Binary Search Trees available for your use in this section.
16. Find the lowest value in a Binary Search Tree
Implement int findMin(Node* rootNode) , which takes a Binary Search Tree and returns the lowest value within the tree.
Remember : Nodes in the left subtree of a current node will always be lower, while the right subtree will always be greater.
Time Complexity : O ( h ) O(h) O ( h )
This solution is recursive to increase efficiency. The sorted structure of a BST makes this solution easier because we just have to find the left-most node.
First, we check if the root is null . If it is, we return -1 ( lines 10-11 ). Otherwise, we check to see if the left child of the current node is null . If it is, then this root is the leftmost node, and you return the value there ( lines 12-13 ).
If a left node exists, call the findMin() function on it ( lines 14-15 ).
17. Find the height of a BST
Implement int findHeight(Node* rootNode) , which takes a binary search tree and returns its height.
The height of a tree is equal to the number of edges between the root node and the lowest node.
The height of your tree equals the greatest height from either the left or right subtree.
Therefore, we must recursively find the heights of the left and right-subtrees. First, we check if the tree is empty, returning -1 if the given node is null . If not, we call the findHeight() function on the left and right-subtrees and return the one that has a greater value plus 1.
18. 2-3 Trees vs. BST
What is the difference between 2-3 Trees and Binary Search Trees?
19. Insertion in a Trie
Implement the insertNode(string key) function, which takes a word and inserts it into an existing trie.
Remember : Consider the three cases for insertion: no common prefix, common prefix, and existing word.
The function takes a string key , indicating a word. NULL keys are not allowed, and all keys are stored in lowercase.
First, we iterate over the characters in the key. For each character, we generate an index using getIndex() .
The next step is to check the child of currentNode at that particular index. If it is NULL , then we create a new TrieNode at that index.
In the end, we mark the last node as a leaf since the word has ended.
20. Total words in a Trie
Implement the totalWords() function, which will take a trie and return the total number of words in the trie.
Starting from the root, we visit each branch recursively. Whenever a node is found with isEndWord set to true, the result variable is incremented by 1.
At the end, we return result to state the total number of words.
21. Implement a Max-Heap
A max-heap is a complete binary tree in which the value of each internal node is greater than or equal to the values in the children of that node.
Your max-heap must include insert() and delete() functions but can also contain any additional functionalities.
Notice that you start from the bottom of the heap, i.e., i = size-1 ( line 78 ). If the height of the heap is h , then the levels go from “0” (at the root node) to “h” at the deepest leaf nodes. By calling maxHeapify() at the leaf nodes, you will have a constant time operation.
At level h - 1h−1 , for every node, maxHeapify() makes one comparison and swap operation at most. At level h−2 , , it makes two at most comparisons and swaps for every node. This continues until the root node, where it makes h comparisons at most, swaps operations.
22. Find k smallest elements in an array
Implement a function findKSmallest(int[] arr, int size, int k) that takes an unsorted integer array as input and returns the “k” smallest elements in the array by using a heap.
You can use the following minHeap implementation as a starting point:
Time Complexity : O ( n + k l o g n ) O(n + klogn) O ( n + k l o g n )
Here create a heap and then call the buildHeap ( line 12 ) function to create a minimum heap from the given array. To find the k smallest elements in an array:
You get the minimum value from the heap.
Save the result to the vector output.
Remove the minimum value from the heap.
Repeat the same steps k times (provided k < size ).
23. Trie vs. Hash Table
Compare the use and performance of Tries and Hash Tables.
24. Subset Array Checker
Implement the isSubset(int[] arr1, int[] arr2, int size1, int size2) function, which will take two arrays and their sizes as input and check if one array is the subset of the other.
The arrays will not contain duplicate values.
Time Complexity : O ( m + n ) O(m+n) O ( m + n ) where m is the number of elements in arr1 and n is the number of elements in arr2 .
C# built-in HashSet makes this solution much simpler. First, we iterate over arr1 on line 16 . If the value at the current index is not present in the HashSet , we insert that value in the HashSet on lines 20-21 . Then, we iterate through arr2 to see whether their elements are present in HashSet .
If all the elements of arr2 are present in HashSet , then your function will return true lines 25-32 .
25. Find two pairs with an equal sum
Implement the string findPair(int[] arr, int size) function, which will take an array and find two pairs, [a, b] and [c, d] , in an array such that:
a + b = c + d a+b = c+d a + b = c + d
Remember : You only have to find any two pairs in the array, not all pairs.
Time Complexity : O ( n 2 ) O(n^2) O ( n 2 )
This solution uses C#'s built-in Dictionary class for simplicity.
On lines 23-33 , each element in arr is summed with all other elements. The sum becomes the key in the hMap . At every key, store the integer pair whose sum generated that key.
Whenever a sum is found such that its key in the hMap already has an integer pair stored in it, you can conclude that this sum can be made by two different pairs in the array. These two pairs are then returned in the result array on lines 36-46 .
20 more questions for a C# coding interview
- Reverse a string in C#
- Check if a given string is a palindrome
- Rotate an array
- Find the second largest integer within an array using one loop
- Convert a 2D Array to a 1D Array
- Explain and implement the MergeSort algorithm
- Find out if a linked list is circular
- Balance a binary search tree
- Search a sorted array with lowest time complexity possible
- 0-1 Knapsack problem
- Reverse a linked list
- Match beginning and ending parenthesis in a string
- Shuffle an array of integers in place
- Find the ancestors of a given node in a BST
- Find the shortest path between two vertices in a graph
- Count the number of edges in an undirected graph
- Check balanced parenthesis using a stack
- Sort values in a stack
- Reverse first k elements in a queue
- Find the middle node of a linked list
Great work on those questions! The best way to prepare for your next interview is to keep getting hands-on practice with common data structure questions like these.
To help your prepare for your interview right, Educative has created the course Data Structures for Coding Interviews in C# . This course lets you hone your data structure skills with hundreds of practice questions, each with live coding environments and in-depth explanations.
By the end of the course, you’ll be an expert on identifying and solving all the most-asked interview question patterns.
Happy learning!
Continue reading about C#
- S.O.L.I.D. Principles of Object-Oriented Programming in C#
- The Coding Interview FAQ: preparation, evaluation, and structure
- Crack coding interviews by building these 5 real-world features
Learn in-demand tech skills in half the time
Mock Interview
Skill Paths
Assessments
Learn to Code
Tech Interview Prep
Generative AI
Data Science
Machine Learning
GitHub Students Scholarship
Early Access Courses
For Individuals
Try for Free
Gift a Subscription
Become an Author
Become an Affiliate
Earn Referral Credits
Cheatsheets
Frequently Asked Questions
Privacy Policy
Cookie Policy
Terms of Service
Business Terms of Service
Data Processing Agreement
Copyright © 2024 Educative, Inc. All rights reserved.
15 Essential C# Interview Questions *
Toptal sourced essential questions that the best c# developers and engineers can answer. driven from our community, we encourage experts to submit questions and offer feedback..
Interview Questions
What is the output of the short program below? Explain your answer.
The output will be:
Although both variables are uninitialized, String is a reference type and DateTime is a value type. As a value type, an unitialized DateTime variable is set to a default value of midnight of 1/1/1 (yup, that’s the year 1 A.D.), not null .
Given an array of ints, write a C# method to total all the values that are even numbers.
There are of course many ways to do this, but two of the most straightforward would be either:
Here are the key things to look for in the answer:
- Does the candidate take advantage of the C# language constructs which make a one-liner solution possible (i.e., rather than employing a more lengthy solution which contains a loop, conditional statement, and accumulator)?
- Does the candidate consider the possibility of overflow. For example, an implementation such as return intArray.Where(i => i % 2 == 0).Sum() (regardless of the return type of the function) might be an “obvious” one-line solution, but the probability of overflow here is high. While the approach used in the answers above of converting to long doesn’t eliminate the possibility, it makes it a highly unlikely that an overflow exception will occur. Note that, if the candidate asks about the expected size of the array and the magnitude of its members, he or she is obviously considering this overflow issue, which is part of what we’re looking to ascertain.
Is the comparison of time and null in the if statement below valid or not? Why or why not?
One might think that, since a DateTime variable can never be null (it is automatically initialized to Jan 1, 0001), the compiler would complain when a DateTime variable is compared to null . However, due to type coercion, the compiler does allow it, which can potentially lead to headfakes and pull-out-your-hair bugs.
Specifically, the == operator will cast its operands to different allowable types in order to get a common type on both sides, which it can then compare. That is why something like this will give you the result you expect (as opposed to failing or behaving unexpectedly because the operands are of different types):
However, this can sometimes result in unexpected behavior, as is the case with the comparison of a DateTime variable and null . In such a case, both the DateTime variable and the null literal can be cast to Nullable<DateTime> . Therefore it is legal to compare the two values, even though the result will always be false.
Apply to Join Toptal's Development Network
and enjoy reliable, steady, remote Freelance C# Developer Jobs
Given an instance circle of the following class:
write code to calculate the circumference of the circle, without modifying the Circle class itself.
The preferred answer would be of the form:
Since we don’t have access to the private radius field of the object, we tell the object itself to calculate the circumference, by passing it the calculation function inline.
A lot of C# programmers shy away from (or don’t understand) function-valued parameters. While in this case the example is a little contrived, the purpose is to see if the applicant understands how to formulate a call to Calculate which matches the method’s definition.
Alternatively, a valid (though less elegant) solution would be to retrieve the radius value itself from the object and then perform the calculation with the result:
Either way works. The main thing we’re looking for here is to see that the candidate is familiar with, and understands how to invoke, the Calculate method.
What is the output of the program below? Explain your answer.
Also, would the answer change if we were to replace await Task.Delay(5); with Thread.Sleep(5) ? Why or why not?
The answer to the first part of the question (i.e., the version of the code with await Task.Delay(5); ) is that the program will just output a blank line ( not “Hello world!”). This is because result will still be uninitialized when Console.WriteLine is called.
Most procedural and object-oriented programmers expect a function to execute from beginning to end, or to a return statement, before returning to the calling function. This is not the case with C# async functions. They only execute up until the first await statement, then return to the caller. The function called by await (in this case Task.Delay ) is executed asynchronously, and the line after the await statement isn’t signaled to execute until Task.Delay completes (in 5 milliseconds). However, within that time, control has already returned to the caller, which executes the Console.WriteLine statement on a string that hasn’t yet been initialized.
Calling await Task.Delay(5) lets the current thread continue what it is doing, and if it’s done (pending any awaits), returns it to the thread pool. This is the primary benefit of the async/await mechanism. It allows the CLR to service more requests with less threads in the thread pool.
Asynchronous programming has become a lot more common, with the prevalence of devices which perform over-the-network service requests or database requests for many activities. C# has some excellent programming constructs which greatly ease the task of programming asynchronous methods, and a programmer who is aware of them will produce better programs.
With regard to the second part of the question, if await Task.Delay(5); was replaced with Thread.Sleep(5) , the program would output Hello world! . An async method without at least one await statement in it operates just like a synchronous method; that is, it will execute from beginning to end, or until it encounters a return statement. Calling Thread.Sleep() simply blocks the currently running thread, so the Thread.Sleep(5) call just adds 5 milliseconds to the execution time of the SaySomething() method.
This program will output the number 10 ten times.
Here’s why: The delegate is added in the for loop and “reference” (or perhaps “pointer” would be a better choice of words) to i is stored, rather than the value itself. Therefore, after we exit the loop, the variable i has been set to 10, so by the time each delegate is invoked, the value passed to all of them is 10.
It is possible to store mixed datatypes such as int, string, float, char all in one array?
Yes! It is possible to do so because the array can be of type object that can not only store any datatype but also the object of the class as shown below:
Compare structs and classes in C#. What do they have in common? How do they differ?
Classes and Structs in C# do have a few things in common, namely:
- Are compound data types
- Can contain methods and events
- Can support interfaces
But there are a number of differences. Here’s a comparison:
- Support inheritance
- Are reference (pointer) types
- The reference can be null
- Have memory overhead per new instance
- Do not support inheritance
- Are value types
- Are passed by value (like integers)
- Cannot have a null reference (unless Nullable is used)
- Do not have memory overhead per new instance (unless “boxed”)
What is the output of the program below?
TestValue : 10
The static constructor of a class is called before any instance of the class is created. The static constructor called here initializes the TestValue variable first.
At the client side:
Is there a way to modify ClassA so that you can you call the constructor with parameters, when the Main method is called, without creating any other new instances of the ClassA ?
The this keyword is used to call other constructors, to initialize the class object. The following shows the implementation:
What does the following code output?
Describe dependency injection.
Dependency injection is a way to de-couple tightly linked classes, thereby reducing the direct dependency of classes upon each other. There are different ways by which dependency injection can be achived:
- Constructor dependency
- Property dependency
- Method dependency
Write a C# program that accepts a distance in kilometers, converts it into meters, and then displays the result.
Describe boxing and unboxing. Provide an example.
Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by the value type. Boxing a value type creates an object instance containing the value and stores it on the heap.
You’re given a word string containing at least one $ symbol, e.g.:
"foo bar foo $ bar $ foo bar $ "
Question: How do you remove all but the first occurrence of $ from a given string?
This problem has two parts: Preserving the first occurrence and replacing all the others.
We can solve it using a regular expression and String.Replace() :
Explanation:
- ([^$]*\$) —Group 1 captures any number of non- $ characters, plus a single $ character (escaped with a \ )
- (.*) —Group 2 (greedily) captures everything else
With the first occurrence of $ preserved in halves[1].Value , we can simply use String.Replace() on halves[2].Value to eliminate all $ characters found in the remainder of the string, without the need for a second regular expression.
There is more to interviewing than tricky technical questions, so these are intended merely as a guide. Not every “A” candidate worth hiring will be able to answer them all, nor does answering them all guarantee an “A” candidate. At the end of the day, hiring remains an art, a science — and a lot of work .
Tired of interviewing candidates? Not sure what to ask to get you a top hire?
Let Toptal find the best people for you.
Our Exclusive Network of C# Developers
Looking to land a job as a C# Developer?
Let Toptal find the right job for you.
Job Opportunities From Our Network
Submit an interview question
Submitted questions and answers are subject to review and editing, and may or may not be selected for posting, at the sole discretion of Toptal, LLC.
Looking for C# Developers?
Looking for C# Developers ? Check out Toptal’s C# developers.
Rahul Dutta
Rahul is a full-stack developer with over 13 years of C# programming experience. He is pivotal in every project he leads and executes, engaging his team and communicating complex concepts effectively to stakeholders. He has built custom APIs, integrations, data-driven jQuery-based plugins, and dynamic websites. Committed to excellence, Rahul is known for his exceptional programming skills, meticulous attention to detail, and adaptability, landing promotions in three organizations in 1.5 years.
Steve Sampson
Steve is a senior software developer with 20 years of experience in full-stack software development, working with notable clients such as Bell Canada, the Nova Scotia Provincial Government, and Sobeys. His primary expertise lies in C#, SQL, and C++ technologies, with a focus on the government, oil and gas, and retail industries. Steve is a team player who is willing to expend whatever energy is necessary and thrives in any environment.
Csaba is a full-stack developer who's been working with C# and SQL since 2001 and as an architect since 2015. Csaba is comfortable working with companies of all sizes using both the Waterfall and Agile methodologies and has experience in banking & finance (ten years), aviation (six years), and TV/radio stations (four years). Csaba also excels at database & application architecture planning, implementation, quality assurance, data transformation (ETL), and performance optimization.
Toptal Connects the Top 3% of Freelance Talent All Over The World.
Join the Toptal community.
- Skills Directory
Developed around 2000 by Microsoft as part of its .NET initiative, C# is a general-purpose, object-oriented programming language designed for Common Language Infrastructure (CLI), and widely recognized for its structured, strong-typing and lexical scoping abilities.
This competency area includes understanding the structure of C# programs, types, and Variables, basic OOP, Properties and Indexers, Collections, Exception handling, among others.
Key Competencies:
- Program Structure - Understand the physical structure of C# programs and the use of namespaces and types.
- Types and Variables - Know the difference between value types and reference.
- Nullable Types - Understand the differences between nullable and non-nullable types.
- Basic OOP - Use classes and objects to write simple object-oriented code. Understand inheritance facilities and use of interfaces to create compositional object-oriented code.
- Properties and Indexers - Using properties and indexers on classes to provide additional safety and expressivity.
- Collections - Knowledge in trade-offs of the various standard library generic collections like List, Set, Dictionary, etc.
- Exception handling - Use of try/catch/finally for managing exceptions.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Practice 167 exercises in C#
Learn and practice C# by completing 167 exercises that explore different concepts and ideas.
Explore the C# exercises on Exercism
Unlock more exercises as you progress. They’re great practice and fun to do!
16 C# Interview Questions to Practice
- Share article on Twitter
- Share article on Facebook
- Share article on LinkedIn
Whether you’re drawn to C# for its versatility, usability, or the ease with which you can transition to it from C++ , C# is a powerful, effective programming language. Many types of programmers, especially Game Developers , commonly use it because of the speed and consistency it gives your coding.
Plus, not only is C# a fun and convenient language, but it can also net you a pretty impressive salary. C# Developers earn an average of $112,952 a year .
To land a six-figure C# job, you’ll have to perform well during the interview. Below, you’ll find some C# interview questions to practice, as well as their answers, so you can walk into your next interview with confidence.
1. What is C#?
C# is a programming language that’s object-oriented and type-safe. This means that the program will catch errors as you make them, preventing you from wasting time fixing minor problems later on.
It’s compiled with the .Net framework to generate Microsoft Intermediate Language (MSIL), which is a set of instructions that can run on multiple environments.
2. Can you execute more than one catch block?
No, you cannot execute multiple types of catch blocks. Once you’ve executed the proper catch code, the control gets transferred over to a final block. The code after that final block is what gets executed.
3. What are jagged arrays?
Jagged arrays have elements of tape arrays, and these can include different sizes and dimensions. They’re also referred to as arrays of arrays.
4. What’s the difference between void, public, and static?
If you have a public declared variable or method, it’ll be accessible anywhere inside the application. On the other hand, you can access static declared variables or methods without having to create an instance of a class . Void is different in that it’s a type modifier that says the variable or method doesn’t return a value.
5. What differentiates a constant from a read-only?
Constant variables get initialized and declared when it’s time to compile the code. After that, you can’t alter their values. Read-only refers to when you assign a value at run-time.
6. What’s an object?
An object refers to a class instance that allows you to access the methods pertaining to that class. If a class creates an object in memory, it’ll contain all of the information about the class’s variables, methods, and behavior.
7. What is a “using” statement in C#?
A “using” block is used to get a resource and process it but then dispose of it automatically after completing the block.
8. What do sealed classes refer to in C#?
Sealed classes are created when you want to restrict which class is going to get inherited. You’d use sealed modifiers to prevent deviation from a class. If you chose a sealed class to be a base class, you’d get a compile-time error.
9. What’s the difference between “out” and “ref” parameters?
An argument that’s passed as ref has to be initialized before it’s passed to the method. On the other hand, out parameters don’t have to be initialized before getting passed to a method.
10. What’s meant by method overloading?
Overloading refers to creating multiple methods that have the same name and unique signatures within the same class. During compilation, the compiler can use overload resolution to determine which method you need to invoke.
11. Describe the difference between array and arraylist
Items within an array have the same type. The size of an array is fixed. An arraylist is similar, except it doesn’t have a fixed size.
12. Are you able to use a “this” command within the context of a static method?
No, you cannot use a “this” command in a static method because you can only use static methods and variables in a static method.
13. What’s the accessibility modifier “protected internal”?
You can access protected internal methods and variables from within the same assembly. Also, you can access them from classes that have been derived from the parent class.
14. What’s meant by “serialization”?
Serialization refers to the process you use when you want to move an object through your network and have to convert it into a stream of bytes.
For an object to be eligible for serialization, it has to implement the ISerialize Interface. When you do the opposite operation — start with a stream of bytes and use it to create an object — you call the process de-serialization.
15. What’s the difference between System.Text.StringBuilder and System.String classes?
System.String isn’t mutable. As an immutable class, you can’t change its value without allocating new memory to the new value and releasing the previous allocation.
System.StringBuilder has a mutable string. This makes it possible to perform a variety of operations without having to allocate a separate memory location for the string you modified.
16. What’s the difference between System.Array.Clone() and System.Array.CopyTo()?
If you use Clone(), you create a fresh array object that has all the elements of the original array. When you use the CopyTo() technique, the elements of an existing array get copied into another existing array. With both methods, a shallow copy gets performed.
How to go beyond C# interview questions
Take your time and practice answering these questions to get ready to nail your next interview. If you still need a little help understanding the ins and outs of C#, check out our Learn C# course .
Depending on what role you’re applying for, your interview process may also include technical interviews, in which you’ll showcase your programming skills by completing coding challenges. Need help preparing for technical interviews? Check out our Career Center .
Related articles
How to Use GitHub to Strengthen Your Resume
Learn how to use GitHub to strengthen your resume, and discover our Career Paths to help boost your programming career.
6 Benefits of Learning Technical Skills — No Matter What Your Job Title Is
Empower your non-technical team to take on new responsibilities.
Bring Technical Training to Your Organization with Codecademy for Teams
Use this checklist to kick off learning with Codecademy Teams.
How To Write A Programmer Bio (With 6 Examples)
The simple formula will make writing a bio feel like no big deal.
What is C# Used For?
C# is a popular programming language that’s similar to C and C++. Learn what it’s used for, what you can do with it, and how to get started.
How I Went From Intern to Microsoft Software Engineer in 3 Years
Today’s story is from Jordan Guada, a 24-year-old Software Engineer I at Microsoft, living in Orlando, Florida.
Cool Job: I’m Stack Overflow’s Director of Engineering
How this developer empowers a team of engineers working on Stack Overflow’s community products.
50+ C# Programs, Exercises, Solutions for beginners to practice
Top C# Programs with solutions for beginners to practice. Fibonacci Series, Prime, Palindrome, Armstrong, loops, Swap, Pyramids , Triangles, and many more
C# Program to Check Whether a Number is Prime or Not
In this C# program, we will take input from the user and check whether the number is prime or not. A prime number is a positive integer that is divisible only by 1 and itself.
C# Program to Calculate Sum of first N natural numbers
In this C# program, we will take input from the user and generate the sum of first N natural Numbers. The sum of natural numbers up to 10 is: 1+2+3+4+5+6+7+8+9+10=55
C# Program to swap two numbers without using the third variable
In this C# program, we will swap two numbers without using the third variable. We will use two methods to swap numbers 1) By using Addition and Subtraction 2) By using Multiplication and Division
C# Program to print prime numbers from 1 to N
In this C# program, we will take input from the user and print prime numbers between 1 and the number input by the user. A prime number is a positive integer that is divisible only by 1 and itself.
C# Program to print perfect numbers from 1 to N
In this C# program, we will take input from the user and print perfect numbers between 1 and the number input by the user. A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For instance, 6 has divisors 1, 2 and 3, and 1 + 2 + 3 = 6, so 6 is a perfect number.
C# Program to print even numbers from 1 to N
In this C# program, we will take input from the user and print even numbers between 1 and the number input by the user. A even number is a positive integer that is exactly divisible by 2.
C# Program to print odd numbers from 1 to N
In this C# program, we will take input from the user and print odd numbers between 1 and the number input by the user. An odd number is a positive integer that is not divisible by 2.
C# Program to Check Whether a Number is Even or Odd
In this C# program, we will take input from the user and check whether a number is even or odd. An Even number is a positive integer that is divisible by 2 and An odd number is a positive integer that is not divisible by 2.
C# Program to Check Whether a Number is Positive or Negative
In this C# program, we will take input from the user and check whether a number is Positive or Negative. A Positive number is a number that is greater than 0 and a Negative number is a number that is lesser than 0.
C# Program to generate a sum of digits
In this C# program, we will take input from the user and generate a sum of digits. For example, if the user input 88 then result is 16.
C# Program to Generate a Multiplication Table of a given integer
In this C# program, we will take input from the user and generate a multiplication table.
C# Program to Calculate the Area of a Circle
In this C# program, we will take input (radius) from the user and calculate the area of a circle. Formula to calculate area of circle is A= π*r*r.
C# Program to Calculate the Area of a Square
In this C# program, we will take input (side) from the user and calculate the area of a square. Formula to calculate area of Square is A= (side of square*side of square).
C# Program to Calculate the Area of a Rectangle
In this C# program, we will take input (Length and Width) from the user and calculate the area of a Rectangle. Formula to calculate area of Rectangle is A= Length*Width.
C# Program to Calculate the Area of a Triangle
In this C# program, we will take input (Base and Height) from the user and calculate the area of a Triangle. Formula to calculate area of Triangle is A= (base*height/2).
C# Program to Check Whether a Number is Palindrome or Not
In this C# program, we will take input from the user and Check Whether a Number is Palindrome or Not. A number is a palindrome if the reverse of that number is equal to the original number.
C# Program to Check Whether a String is Palindrome or Not
In this C# program, we will take input from the user and Check Whether a String is Palindrome or Not. A String is a palindrome if the reverse of that String is equal to the original
C# Program to Print Fibonacci Series
The Fibonacci sequence is a sequence where the next number is the sum of the previous two numbers. The first two numbers of fibonacci series are 0 and 1.
C# Program to Find Factorial of a Number
In this C# program, we will take input from the user and Find the Factorial of a Number using 3 different ways using 1) For loop 2) Recursion 3) While loop. The factorial of a positive number n is given by n!. 5!=5*4*3*2*1=120
C# Program to print Alphabet Triangle
In this C# program, we will take input (Number of rows) from the user and print the alphabet triangle based on the number of rows input by the user.
C# Program to print Number Triangle
In this C# program, we will take input (Number of rows) from the user and print the Number triangle based on the number of rows input by the user.
C# Program to print Star Triangle
In this C# program, we will take input (Number of rows) from the user and print the Star (*) triangle based on the Number of rows input by the user.
C# Program to print Diamond Shape
In this C# program, we will take input (Number of rows) from the user and print the diamond shape based on the Number of rows input by the user.
C# program to change case of a string
In this C# program, we will take the input string from the user and change it to 1)Upper Case 2)Lower Case 3)Title Case.
C# program to add and subtract days from the date
In this C# program, we will add and subtract days from the date.
C# Program to Check Leap Year
In this C# program, we will take the input from the user and check whether the input year is a Leap Year or not. Leap year is a year which is divisible by 4.
C# program to compare two dates
In this C# program, we will compare two dates and print the result.
C# program to convert days into years, weeks and days
In this C# program, we will take the input (days) from the user and Convert days into years, weeks and days.
C# Program to Print Day Name of Week
In this C# program, we will take the input from the user and print day name of week.
C# Program to convert Celsius into Fahrenheit
In this C# program, we will take the input Celsius from the user and change it to Fahrenheit.
C# Program to Convert Number into Words
In this C# program, we will take the input number from the user and change it to Words. E.g. 1024 will be converted to One Thousand Twenty Four only.
C# Program to Convert Meters To Kilometers
In this C# program, we will take the input meters from the user and change it Kilometers.
C# program to calculate Simple Interest
In this C# program, we will take the input "Principal Amount", "Interest Rate" and "Time" from the user and calculate the simple interest.
C# program to calculate Compound Interest
In this C# program, we will take the input "Principal Amount", "Interest Rate", "Interest Compound Frequency" and "Time" from the user and calculate the simple interest.
C# Program to Find GCD of two Numbers
In this C# program, we will take the input from the user and find GCD of two numbers.
C# Program to Find LCM of two Numbers
In this C# program, we will take the input from the user and find LCM of two numbers.
C# Program to Find HCF of two Numbers
In this C# program, we will take the input from the user and find HCF of two numbers.
C# program to reverse an array elements
In this C# program, we will reverse an array without using Array.Revers() Method.
C# Program to concatenate two strings
In this C# program, we will take the input strings from the user and print the concatenated string.
C# Program to read the content of a file
In this C# program, we will read the content of the Text file and print the content of the file.
C# Program to Check Whether a Character is a Vowel or Consonant
In this C# program, we will take the input from the user and Check Whether a Character is a Vowel or Consonant.
C# switch example
In this C# program, we will learn how to implement a switch case in C#. We will use a switch statement to display the name of the day based on the input entered by the user.
C# For Loop with examples
In this C# program, we will see For Loop with examples.
C# While Loop with examples
In this C# program, we will see While Loop with examples.
C# Do While Loop with examples
In this C# program, we will see Do While Loop with examples.
C# Remove last specific character in a string
In this C# program, we will see how to Remove last specific character in a string. In this example we will remove last , from the string.
C# Program to Convert a List to a comma separated string
In this C# program, we will see how to Convert a List to a comma separated string.
1) |
2) |
3) |
4) |
5) |
- Popular Articles
- Recent Articles
Subscribe for Latest Updates.
C# Tutorial
C# examples, c# exercises.
You can test your C# skills with W3Schools' Exercises.
We have gathered a variety of C# exercises (with answers) for each C# Chapter.
Try to solve an exercise by editing some code, or show the answer to see what you've done wrong.
Count Your Score
You will get 1 point for each correct answer. Your score and total score will always be displayed.
Start C# Exercises
Start C# Exercises ❯
If you don't know C#, we suggest that you read our C# Tutorial from scratch.
Kickstart your career
Get certified by completing the course
COLOR PICKER
Contact Sales
If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]
Report Error
If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]
Top Tutorials
Top references, top examples, get certified.
27 tricky C# interview questions to add to your hiring campaign (and answers to look for)
Hire top c# developers with testgorilla.
C# is a programming language used to develop applications, games, and more. Currently, it’s the fifth most popular programming language in the world. [1] With so many professionals using the language, finding the right developer for a C# role can be challenging. You must have a robust, accurate understanding of your applicants’ skills and expertise to be sure you truly select the best of the best.
While a talented developer can help you develop and deploy products effectively, a mis-hire can lead to missed deadlines, buggy applications, and disruption to the entire team’s workflow. This can cause your organization to lose opportunities and your reputation to take a hit with customers.
Therefore, creating a comprehensive candidate assessment process that includes tricky C# interview questions is crucial.
In this article, we share 27 complex questions to ask C# developers during interviews. These questions help you get a complete picture of your candidates’ theoretical knowledge, practical expertise, and situational judgment. We’ve also provided example answers so you know what to listen for.
Table of contents
What are tricky c# interview questions, why include c# tricky questions in interviews, 27 tricky c# interview questions and answers, how to include tricky c# interview questions in your hiring campaign, find skilled c# developers with testgorilla.
The ideal candidate for a C# role has a strong grasp of the language, including how to implement it effectively for business use cases. While basic questions can test a candidate’s familiarity with the language, they typically can’t test how they will react in real-life work scenarios.
This is when tricky C# interview questions are helpful. These questions assess a candidate’s proficiency in C#’s more advanced concepts and features. They also require developers to think critically and demonstrate their problem-solving abilities.
Advanced questions show you how a developer would respond within the context of the specific role and its responsibilities. This enables you to find the best-suited candidate for your open positions.
Tricky C# interview questions can comprise:
Theoretical questions asking candidates to explain a C# concept, its functionalities, and its principles.
Practical questions , which enable candidates to show their C# skills by asking them to write code for specific projects or tasks.
Scenario-based questions that present candidates with an example scenario to test their coding and problem-solving on the spot.
Tricky C# interview questions are the key to evaluating a candidate’s skills, suitability for the position, and overall potential contribution to your development team. Plus, these questions help you remove bias from the hiring process , as they give you a way to compare candidates objectively and identify top talent.
In particular, adding tricky questions in interviews can help you assess:
Technical expertise and understanding of best practices
These questions go beyond basic syntax and standard concepts, revealing a candidate’s ability to handle complex scenarios. They enable you to identify developers who deeply understand advanced C# topics and how to use them to solve coding problems.
Plus, these questions help you measure whether candidates know the best practices for writing efficient and maintainable code. Many advanced questions revolve around performance optimization, memory management, and design patterns.
Critical thinking and problem-solving skills
Tricky questions also assess applicants’ problem-solving skills and ability to approach challenging coding scenarios. It’s crucial for you to understand how a developer has tackled past problems, as it’s a strong indicator of how they’ll approach challenges at your organization if they’re hired.
Versatility and learning potential
Complex questions evaluate a candidate’s versatility in using C# to solve problems – which is crucial in software development, where different projects demand different skill sets.
Additionally, a candidate’s response to advanced questions reveals their potential for learning and growth. Those who engage well with these questions will likely adapt to new challenges and learn quickly on the job.
Communication skills
A developer might have all the right skills for the position, but without clear communication, they’re unlikely to succeed in your organization. Candidates who can answer difficult questions and break down complex subjects in an interview will likely be able to communicate clearly and collaborate effectively within your team.
Use the following questions to ensure your candidate has the necessary C# skills and expertise to succeed at your organization. We’ve included sample answers for each question so you can listen for ideal answers.
1. What is the difference between IEnumerable and IQueryable interfaces in C#? When would you use each one?
IEnumerable is used for querying in-memory collections, while IQueryable is used for querying external data sources, like databases. IQueryable allows you to write and execute more complex queries on the server.
2. What are the differences between async/await and Task.Run in C# when dealing with asynchronous code?
Async/await is used to create asynchronous methods that can be awaited without blocking the main thread. Task.Run is used to execute a delegate or lambda expression on a ThreadPool thread asynchronously. It can be helpful to offload CPU-bound work from the main thread.
3 . Explain the various methods of sharing data between tasks in C#.
Data can be shared between tasks using thread-safe data structures like
ConcurrentDictionary and ConcurrentQueue or synchronization constructs like lock , Monitor , and Semaphore .
4 . How do you implement a custom exception handling middleware in ASP.NET Core?
Here’s a summary of the process:
Implement a custom middleware that handles exceptions.
Use app.UseMiddleware to add the middleware to the application’s request pipeline.
In the middleware, catch exceptions, log them, and return an appropriate response.
5. How do you implement a custom attribute in C#? Provide an example of how to use it to decorate a class.
Implement a custom attribute by creating a class that derives from Attribute . Add properties or fields to store data associated with the attribute. To use the attribute, apply it to classes or members using square bracket syntax.
Here’s an example:
[AttributeUsage(AttributeTargets.Class)]
public class CustomAttribute : Attribute
public string Name { get; set; }
public CustomAttribute(string name)
Name = name;
[Custom("ExampleClass")]
public class MyClass
// Class implementation
6. Explain the differences between covariance and contravariance in C# for delegates and interfaces.
Covariance allows using a more derived type instead of a less derived type, while contravariance enables the opposite. In C#, covariance can be applied to interfaces using the out keyword, and contravariance can be applied using the in keyword.
7. How do you handle deadlocks in multi-threaded C# applications?
Deadlocks occur when multiple threads are blocked, waiting for each other to release resources. To handle deadlocks, follow best practices like acquiring locks in a consistent order, using timeout mechanisms, and avoiding long-running locks.
8. Explain the using directive and the using statement in C#. What are their differences?
The using directive is used to include namespaces in a file, making types in those namespaces accessible without fully qualifying their names. The using statement is used for the automatic disposal of resources that implement IDisposable .
9. Explain the differences between value types and reference types in C#.
Value types store their value directly in memory, while reference types store a reference to an object in memory. Value types are stored on the stack, and reference types are stored on the heap.
10. How do you implement a custom IComparer<T> for sorting in C#?
Create a class that implements the IComparer<T> interface, defining the Compare method for comparing two objects. Then, use an instance of this custom comparer with the Sort method of a collection to apply your customized sorting logic.
11. Explain the concept of object pooling in C# and its benefits in multi-threaded applications.
Object pooling involves reusing objects instead of creating new ones. This can improve performance and reduce garbage collection overhead, especially in multi-threaded applications, where object creation and destruction can be costly.
12. How can you improve string concatenation performance in C#?
Use StringBuilder instead of repeated string concatenation with + to improve performance, especially when concatenating or linking multiple strings together in a loop.
13. What are delegates and events in C#? Provide an example of using events in a C# application.
Delegates are function pointers that enable encapsulating a method and calling it indirectly. Events are a way to provide notifications to other parts of the application when something happens.
public delegate void EventHandler(object sender, EventArgs e);
public class EventPublisher
public event EventHandler SomethingHappened;
public void DoSomething()
// ... do something
OnSomethingHappened();
protected virtual void OnSomethingHappened()
SomethingHappened?.Invoke(this, EventArgs.Empty);
14. What are the different types of garbage collection in C#? How can you configure them?
C# supports three types of garbage collection: Workstation garbage collection, Server garbage collection, and Concurrent garbage collection. You can configure garbage collection behavior using configuration settings in the app’s configuration file.
15. Explain the differences between a deep copy and a shallow copy of objects in C#. How can you perform each type of copy?
A shallow copy creates a new object but doesn’t duplicate internal references. A deep copy creates a new object and clones all internal references recursively. Shallow copying can be done using MemberwiseClone , while deep copying requires custom implementation.
16. What is reflection in C#? How is it useful, and what are its limitations?
Reflection allows inspecting and manipulating types, methods, properties, etc., at runtime. It’s useful for building generic frameworks and creating dynamic and extensible applications. However, it can be slower and lacks compile-time safety.
17. What is the purpose of the yield keyword in C#? Provide an example of using it with an iterator.
The yield keyword is used to create an iterator in C#. It allows you to return a sequence of values without building the entire sequence in memory before returning it.
For example:
public IEnumerable<int> GetNumbers()
for (int i = 0; i < 10; i++)
yield return i;
18. Explain how to implement a custom serializer and deserializer for a complex object in C#.
You can implement custom serialization logic by manually converting the object’s properties to a serialized format (e.g., JSON or XML). Then, implement the deserialization logic to read the serialized data and recreate the object.
19. Explain the differences between Memory<T> and Span<T> in C#. When would you use one over the other?
Memory<T> represents a chunk of memory that can be read from and written to. Span<T> is a lightweight view of a portion of an array or memory.
Use Memory<T> when you need a dynamically allocated memory block and Span<T> to work with a portion of an existing array or memory.
20. How can you optimize memory usage and performance when working with large data collections in C#?
You can consider using data structures that are more memory-efficient for specific scenarios, like BitArray for managing sets of bits or HashSet<T> for effective membership checks. Also, you can use streaming and lazy-loading techniques to avoid loading the entire data set into memory.
21. What are extension methods in C#? Provide an example of using an extension method with an existing class.
Extension methods are created by defining static methods within static classes. The “this” keyword is used in the method's parameter to indicate the type being extended.
public static class StringExtensions{ public static bool IsPalindrome(this string str)
// Check if the string is a palindrome
// ...
string word = "racecar";
bool isPalindrome = word.IsPalindrome(); // true
22. How do you work with parallelism and concurrency in C#? Explain the differences between Parallel.ForEach and PLINQ (Parallel LINQ).
Parallel.ForEach is used to parallelize the iteration over a collection, while PLINQ allows performing parallel queries on data using LINQ. Use Parallel.ForEach when you need to apply a function to each element of a collection in parallel. Use PLINQ when you want to perform data queries in parallel.
23. How does the volatile keyword work in C#? When and how should you use it?
The volatile keyword is used to ensure that the value of a variable is always read from and written to the main memory, not from a cache. Use it when you have a variable shared between multiple threads and want to avoid potential visibility issues or stale values.
24. Explain the differences between async void and async Task in C#. When would you use one over the other?
async void is used for event handlers and should be avoided in most other scenarios since it makes error handling more difficult. async Task is used for asynchronous methods that return a result and allow better error handling through Tasks’ Exception property.
25. What is boxing and unboxing in C#? How can you avoid performance issues related to boxing?
Boxing is the process of converting a value type to an object type, and unboxing is the reverse process. Boxing and unboxing can cause performance overhead. To avoid it, use generics ( List<T>, Dictionary<TKey, TValue> , etc.) over non-generic collections ( ArrayList , Hashtable , etc.), and use generic versions of interfaces like IEnumerable<T> instead of non-generic versions like IEnumerable .
26. What is a Singleton design pattern?
The singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It typically involves a private constructor and a static method to retrieve the instance.
27. Explain the Factory Method design pattern.
The factory Method pattern defines an interface for creating objects, but allows the sub class to decide which class to instantiate. It promotes loose coupling between the client code and the objects.
Advanced C# questions are a great way to get more detailed insight into your candidates’ skills. But they aren’t enough to make up your entire assessment process. It’s important to pair these questions with additional tests to get a clear picture of your prospective hires.
TestGorilla’s multi-measure testing technique can help you make bias-free, well-informed hiring decisions. Use a combination of our 300+ tests to comprehensively evaluate candidates’ skills and qualifications for the C# role, along with their personality traits, cognitive ability, and more.
With TestGorilla, you can evaluate C# developers by creating assessments that include:
Job-specific skills tests , including C# debugging , algorithms , and data structures tests.
Personality tests , like Enneagram and DISC , to understand applicants’ behavioral traits.
Soft skills tests , such as our Motivation test , Communication skills test , and more.
Custom questions tailored to the position and your company.
By combining tricky interview questions with TestGorilla’s skills and personality tests, you can be confident in hiring the best developers for your organization.
Have you tried our soft skills assessments?
Level up your recruiting with soft skills assessments from TestGorilla.
Finding highly-qualified developers for a C# position requires going beyond basic testing and questions. You must use complex C# questions that challenge candidates and provide in-depth insights into their knowledge and skills.
Using these tricky questions alongside TestGorilla’s range of programming and personality tests enables you and your hiring team to assess candidates accurately, reduce unconscious bias during hiring, and prevent mis-hires that can harm your business.
Sign up for TestGorilla’s free plan to explore our tests, or get a free 30-minute live demo to see how they can elevate your hiring campaigns.
1. (n.d.). TIOBE Index for August 2023 . Tiobe Index. Retrieved August 25, 2023, from https://www.tiobe.com/tiobe-index/
Related posts
The case for mindfulness at work: Benefits and best practices
How to use strategic HR data analysis to unlock long-term success
What is counterproductive work behavior (CWB)? + How to fix & prevent it
You've scrolled this far
Why not try TestGorilla for free, and see what happens when you put skills first.
Latest posts
The best advice on pre-employment testing, in your inbox.
No spam. Unsubscribe at any time.
Hire the best. No bias. No stress.
Our screening tests identify the best candidates and make your hiring decisions faster, easier, and bias-free.
Free resources
This checklist covers key features you should look for when choosing a skills testing platform
This resource will help you develop an onboarding checklist for new hires.
How to assess your candidates' attention to detail.
Learn how to get human resources certified through HRCI or SHRM.
Learn how you can improve the level of talent at your company.
Learn how CapitalT reduced hiring bias with online skills assessments.
Learn how to make the resume process more efficient and more effective.
Improve your hiring strategy with these 7 critical recruitment metrics.
Learn how Sukhi decreased time spent reviewing resumes by 83%!
Hire more efficiently with these hacks that 99% of recruiters aren't using.
Make a business case for diversity and inclusion initiatives with this data.
- Python Course
- Python Basics
- Interview Questions
- Python Quiz
- Popular Packages
- Python Projects
- Practice Python
- AI With Python
- Learn Python3
- Python Automation
- Python Web Dev
- DSA with Python
- Python OOPs
- Dictionaries
C# Interview Questions and Answers
C# is the most popular general-purpose programming language and was developed by Microsoft in 2000, renowned for its robustness, flexibility, and extensive application range . It is simple and has an object-oriented programming concept that can be used for creating different types of applications.
Here, we will provide 50+ C# Interview Questions and Answers which are suitable for both freshers and experienced professionals with 2, 5, and 10 years of experience. Here, we cover everything, including core C# concepts, Object-Oriented Programming (OOP), multithreading, exception handling, design patterns, .NET framework, and more, that will surely help you to crack C# interviews.
Table of Content
- C# Interview Questions for Freshers
Intermediate C# Interview Questions
- C# Interview Questions For Experienced
Basic C# Interview Questions for Freshers
1. what is c#.
C# is an object-oriented, modern programming language that was created by Microsoft. 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.
2. How is C# different from the C programming language?
S.No | C Programming Language | C# Programming Language |
---|---|---|
1. | C language supports procedural programming. | Whereas C# supports object-oriented programming. |
2. | C language supports pointers. | Whereas in C#, pointers are used only in unsafe mode. |
3. | In C language, garbage collection is not. | While in C#, garbage collection is managed by Common Language Runtime (CLR). |
4. | C language can be executed cross-platform. | Whereas .NET Framework is required to execute C# language. |
5. | By using C language we can achieve a low level of abstraction. | Whereas by using the C# we can achieve a high degree of abstraction. |
6. | C language is more on functions. | While C# is more on design. |
7. | C language gives a top-notch performance. | While C# gives an objectives standard performance. |
8. | There are 32 total keywords used in the C language. | While a total of 86 keywords are used in C#. |
9. | C language is mainly used in commercial industries and engineering. | Whereas C# is used for software formation and other networking-related objectives. |
3. What is Common Language Runtime (CLR)?
CLR is the basic and Virtual Machine component of the .NET Framework. It is the run-time environment in the .NET Framework that runs the codes and helps in making the development process easier by providing various services such as remoting, thread management, type-safety, memory management, robustness, etc.
Basically, it is responsible for managing the execution of .NET programs regardless of any .NET programming language. It also helps in the management of code, as code that targets the runtime is known as the Managed Code, and code that doesn’t target to runtime is known as Unmanaged code. To read more, refer to the article: Common Language Runtime.
4. What is inheritance? Does C# support multiple inheritance?
Inheritance is an important pillar of OOP(Object Oriented Programming). It is the mechanism in C# by which one class is allowed to inherit the features(fields and methods) of another class.
- Super Class: The class whose features are inherited is known as superclass(or a base class or a parent class).
- Sub Class: The class that inherits the other class is known as a subclass(or a derived class, extended class, or child class). The subclass can add its own fields and methods in addition to the superclass fields and methods.
- Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class and there is already a class that includes some of the code that we want, we can derive our new class from the existing class. By doing this, we are reusing the fields and methods of the existing class.
C# does not support multiple class inheritance . To read more, refer to the article: Inheritance in C#
5. What is the difference between a struct and a class in C#?
A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit.
A structure is a collection of variables of different data types under a single unit. It is almost similar to a class because both are user-defined data types and both hold a bunch of different data types. To read more, refer to the article: struct and class in C#
6. What is enum in C#?
Enumeration (or enum) is a value data type in C#. It is mainly used to assign the names or string values to integral constants, which make a program easy to read and maintain. For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. Other examples include natural enumerated types (like the planets, days of the week, colors, directions, etc.). The main objective of enum is to define our own data types(Enumerated Data Types). Enumeration is declared using the enum keyword directly inside a namespace, class, or structure. To read more, refer to the article: Enum in C#
7. What is the difference between ref and out keywords?
The ref is a keyword in C# which is used for passing the arguments by a reference. Or we can say that if any changes made in this argument in the method will reflect in that variable when the control return to the calling method. The ref parameter does not pass the property.
The out is a keyword in C# which is used for passing the arguments to methods as a reference type. It is generally used when a method returns multiple values. The out parameter does not pass the property. To read more, refer to the article: ref and out keywords
8. What are Properties in C#?
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. To read more, refer to the article: Properties in C#
9. What is the difference between constant and read-only in C#?
In C#, a const keyword is used to declare constant fields and constant local. The value of the constant field is the same throughout the program or in other words, once the constant field is assigned the value of this field is not be changed. In C#, constant fields and locals are not variables, a constant is a number, string, null reference, boolean values. readonly keyword is used to declare a readonly variable. This readonly keyword shows that you can assign the variable only when you declare a variable or in a constructor of the same class in which it is declared.
To read more, refer to the article: constant and read-only in C#
10. Can multiple catch blocks be executed?
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. To read more, refer to the article: Multiple catch block in C#
11. What is Jagged Arrays?
A jagged array is an array of arrays such that member arrays can be of different sizes. In other words, the length of each array index can differ. The elements of Jagged Array are reference types and initialized to null by default. Jagged Array can also be mixed with multidimensional arrays. Here, the number of rows will be fixed at the declaration time, but you can vary the number of columns. To read more, refer to the article: Jagged Array in C#
12. What’s the difference between the System.Array.CopyTo() and System.Array.Clone() ?
The System.Array.CopyTo() technique makes a replica of the components into another existing array. It makes copies the components of one cluster to another existing array. The Clone() technique returns a new array object containing every one of the components in the first array. The Clone() makes a duplicate of an array as an object, consequently should be cast to the real exhibit type before it tends to be utilized to do definitely. The clone is of a similar type as the first Array.
13. What is the difference between “is” and “as” operators in C#?
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.
14. What is tuple in C#?
The word Tuple means “a data structure which consists of the multiple parts”. So tuple is a data structure that gives you the easiest way to represent a data set that has multiple values that may/may not be related to each other. It was introduced in .NET Framework 4.0 . In tuple, you can add elements from 1 to 8 . If you try to add elements greater than eight, then the compiler will throw an error. Tuples are generally used when you want to create a data structure that contains objects with their properties and you don’t want to create a separate type for that.
15. What are namespaces in C#?
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. To read more about this, please refer to Namespaces in C#
16. Who can be the members of namespaces in C#?
The members of a namespace can be namespaces, interfaces , structures , and delegates .
17. What are indexers in C# .NET?
Indexers are known as smart arrays in C#. It allows the instances of a class to be indexed in the same way as an array. To read more, refer to the article: C# indexers
18. What is the JIT compiler process?
Just-In-Time compiler(JIT) is a part of Common Language Runtime (CLR) in .NET which is responsible for managing the execution of .NET programs regardless of any .NET programming language. A language-specific compiler converts the source code to the intermediate language. This intermediate language is then converted into the machine code by the Just-In-Time (JIT) compiler. This machine code is specific to the computer environment that the JIT compiler runs on. To read more, refer to the article: What is Just-In-Time(JIT) Compiler in .NET ?
19. What is the System. String and System.Text.StringBuilder classes?
C# StringBuilder is similar to Java StringBuilder. A String object is immutable, i.e. a String cannot be changed once created. Every time when you use any of the methods of the System. String class, then you create a new string object in memory. For example, a string “GeeksForGeeks” occupies memory in the heap, now, changing the initial string “GeeksForGeeks” to “GFG” will create a new string object on the memory heap instead of modifying the initial string at the same memory location. In situations where you need to perform repeated modifications to a string, we need the StringBuilder class.
To avoid string replacing, appending, removing, or inserting new strings in the initial string C# introduce StringBuilder concept. StringBuilder is a dynamic object. It doesn’t create a new object in the memory but dynamically expands the needed memory to accommodate the modified or new string. To read more, refer to the article: System.String and System.Text.StringBuilder in C#
20. What is garbage collection in C#?
Automatic memory management is made possible by Garbage Collection in .NET Framework. When a class object is created at runtime, certain memory space is allocated to it in the heap memory. However, after all the actions related to the object are completed in the program, the memory space allocated to it is a waste as it cannot be used. In this case, garbage collection is very useful as it automatically releases the memory space after it is no longer required.
Garbage collection will always work on Managed Heap, and internally it has an Engine which is known as the Optimization Engine. Garbage Collection occurs if at least one of multiple conditions is satisfied. These conditions are given as follows:
- If the system has low physical memory, then garbage collection is necessary.
- If the memory allocated to various objects in the heap memory exceeds a pre-set threshold, then garbage collection occurs.
- If the GC.Collect method is called, then garbage collection occurs. However, this method is only called under unusual situations as normally garbage collector runs automatically.
To read more, refer to the article: Garbage collection in C# .
21. What are the types of classes in C#?
- Abstract class
- Partial class
- Sealed class
- Static class
22. What is the difference between C# abstract class and an interface?
Abstract Class | Interface |
---|---|
It contains both declaration and definition parts. | It contains only a declaration part. |
Multiple inheritance is not achieved by an abstract class. | Multiple inheritance is achieved by the interface. |
It contains a constructor. | It does not contain a constructor. |
It can contain static members. | It does not contain static members. |
It can contain different types of access modifiers like public, private, protected, etc. | It only contains public access modifier because everything in the interface is public. |
The performance of an abstract class is fast. | The performance of the interface is slow because it requires time to search the actual method in the corresponding class. |
It is used to implement the core identity of class. | It is used to implement the peripheral abilities of the class. |
A class can only use one abstract class. | A class can use multiple interfaces. |
If many implementations are of the same kind and use common behavior, then it is superior to use an abstract class. | If many implementations only share methods, then it is superior to use Interface. |
An abstract class can contain methods, fields, constants, etc. | The interface can only contain methods. |
It can be fully, partially, interface or not implemented. | It should be fully implemented. |
23. What are extension methods in C#?
In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type, and you do not require any kind of special permission from the original type and there is no need to re-compile the original type. It is introduced in C# 3.0. To read more, refer to the article: Extension methods in C#
24. What are partial classes in C#?
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 }
To read more, refer to the article: Partial classes in C#
25. What is the difference between late binding and early binding in C#?
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. To read more, refer to the article: Early binding and Late Binding
26. What are the different ways in which a method can be Overloaded in C#?
Method Overloading is the common way of implementing polymorphism. It is the ability to redefine a function in more than one form. A user can implement function overloading by defining two or more functions in a class sharing the same name. C# can distinguish the methods with different method signatures. i.e. the methods can have the same name but with different parameters list (i.e. the number of the parameters, order of the parameters, and data types of the parameters) within the same class.
- Overloaded methods are differentiated based on the number and type of the parameters passed as arguments to the methods.
- You can not define more than one method with the same name, Order, and type of the arguments. It would be a compiler error.
- The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return types. It will throw a compile-time error. If both methods have the same parameter types, but different return types, then it is not possible. To read more, refer to the article: Method Overloading in C#
27. What is Reflection in C#?
Reflection is the process of describing the metadata of types, methods, and fields in a code. The namespace System. Reflection enables you to obtain data about the loaded assemblies, the elements within them like classes, methods, and value types. To read more, refer to the article: Reflection in C#
28. What is Managed or Unmanaged Code?
A code that is written to aimed to get the services of the managed runtime environment execution like CLR(Common Language Runtime) in .NET Framework is known as Managed Code. It is always implemented by the managed runtime environment instead of directly executed by the operating system. The managed runtime environment provides different types of services like garbage collection, type checking, exception handling, bounds checking, etc. to code automatically without the interference of the programmer. It also provides memory allocation, type safety, etc to the code. The application is written in the languages like Java, C#, VB.Net, etc. is always aimed at runtime environment services to manage the execution, and the code written in these types of languages is known as managed code.
A code that is directly executed by the operating system is known as Unmanaged code. It is always aimed at the processor architecture and depends upon computer architecture. When this code is compiled it always tends to get a specific architecture and always runs on that platform, in other words, whenever you want to execute the same code for the different architecture you have to recompile that code again according to that architecture. It always compiles to the native code that is specific to the architecture. To read more, refer to the article: Managed and Unmanaged code
29. What is Multithreading with .NET?
Multi-threading is a process that contains multiple threads within a single process. Here each thread performs different activities. For example, we have a class and this call contains two different methods, now using multithreading each method is executed by a separate thread. So the major advantage of multithreading is it works simultaneously, which means multiple tasks execute at the same time. And also maximizing the utilization of the CPU because multithreading works on time-sharing concept mean each thread takes its own time for execution and does not affect the execution of another thread, this time interval is given by the operating system. To read more, refer to the article: Multithreading in C#
30. What is LINQ in C#?
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. To read more, refer to the article: LINQ in C#
31. What are delegates in C#?
A delegate is an object which refers to a method, or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++ . It provides a way that tells which method is to be called when an event is triggered. For example, if you click a button on a form (Windows Form application), the program would call a specific method. In simple words, it is a type that represents references to methods with a particular parameter list and return type and then calls the method in a program for execution when it is needed. To read more, refer to the article: Delegates in C#
32. What are sealed classes in C#?
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 :
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. To read more, refer to the article: Sealed Classes in C#
33. What is the Constructor Chaining in C#?
We can call an overloaded constructor from another constructor using this keyword but the constructor must belong to the same class because this keyword is pointing to the members of the same class in which this is used. This type of calling the overloaded constructor is also termed as Constructor Chaining. To read more, refer to the article: Constructor Chaining
34. Describe Accessibility Modifiers in C#?
Access Modifiers are keywords that define the accessibility of a member, class, or datatype in a program. These are mainly used to restrict unwanted data manipulation by external programs or classes. There are 4 access modifiers (public, protected, internal, private) which defines the 6 accessibility levels as follows:
- private protected
- protected internal
35. What is a Virtual Method in C#?
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 overridden in the child class. We make a virtual method in the base class by using the virtual keyword and that method is overridden 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. To read more, refer to the article: Virtual Method in C#
36. What is File Handling in C#?
Generally, the file is used to store the data. The term File Handling refers to the various operations like creating the file, reading from the file, writing to the file, appending the file, etc. There are two basic operations that are mostly used in file handling is reading and writing of the file. The file becomes stream when we open the file for writing and reading. A stream is a sequence of bytes that is used for communication. Two streams can be formed from the file one is the input stream which is used to read the file and another is the output stream is used to write in the file. In C#, the System.IO namespace contains classes that handle input and output streams and provide information about file and directory structure.
37. List down the commonly used types of exceptions?
An exception is an error that happens at runtime. Using C#’s exception-handling subsystem, we can, during a structured and controlled manner, handle runtime errors. The primary advantage of exception handling is that it automates much of the error handling code. An Exception handling is additionally important because C# defines standard exceptions for common program errors, like divide-by-zero or index-out-of-range.
C# Exception with their meaning:
- ArrayTypeMismatchException: This exception comes when the Type of value being stored is incompatible with the type of the array.
- DivideByZeroException: It comes when the user tries to division an integer value by zero.
- IndexOutOfRangeException: When an array index is out-of-bounds, it exception occurred.
- InvalidCastException: A runtime cast is invalid.
- OutOfMemoryException: Insufficient free memory exists to continue program execution.
- OverflowException: An arithmetic overflow occurred.
- NullReferenceException: An attempt was made to operate on a null reference—that is, a reference that does not refer to an object.
38. What is Singleton design pattern in C#?
Singleton design pattern in C# is a common design pattern. In this pattern, a class has just one instance in the program that gives global access to it. Or we can say that a singleton is a class that permits only one instance of itself to be made and usually gives simple access to that instance.
There are different approaches to carry out a singleton design in C#. Coming up next are the regular attributes of a singleton design.
- Private and parameterizes single constructor
- Sealed class.
- Static variable to hold a reference to the single made example
- A public and static method of getting the reference to the made example.
39. How to implement a singleton design pattern in C#?
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.
40. What are Events?
An event is a notification that some action has occurred. Delegates and events are related because an event is built upon a delegate. Both expand the set of programming tasks to which C# can be applied. It is an important C# feature is built upon the foundation of delegates: the event. An event is, essentially, an automatic notification that some action has occurred. Events work like this:
An object that has an interest in an event registers an event handler for that event. When the event occurs, all registered handlers are called. Event handlers are represented by delegates.
Events are members of a class and are declared using the event keyword. Its most commonly used form is shown here:
event event-delegate event-name ;
Here, event-delegate is the name of the delegate used to support the event, and event-name is the name of the specific event object being declared.
Advanced C# Interview Questions
41. what is the difference between to dispose and finalize methods in c#.
The primary difference between dispose() and finalize() is that the dispose() must be explicitly invoked by the user and the finalize() is called by the garbage collector when the object is destroyed.
42. What is a multicasting delegate in C#?
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.
43. What are Generics in C#?
Generic is a class that allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc, and user-defined types) to be a parameter to methods, classes, and interfaces. A primary limitation of collections is the absence of effective type checking. This means that you can put any object in a collection because all classes in the C# programming language extend from the object base class. This compromises type safety and contradicts the basic definition of C# as a type-safe language. In addition, using collections involves a significant performance overhead in the form of implicit and explicit type casting that is required to add or retrieve objects from a collection. To read more, refer to the article: Generics in C#
44. What is Boxing and Unboxing in C#?
Boxing and unboxing is an important concept in C#. C# Type System contains three data types: Value Types (int, char, etc), Reference Types (object), and Pointer Types. Basically, it converts a Value Type to a Reference Type, and vice versa. Boxing and Unboxing enable a unified view of the type system in which a value of any type can be treated as an object.
Boxing In C#
- The process of Converting a Value Type (char, int, etc.) to a Reference Type(object) is called Boxing.
- Boxing is an implicit conversion process in which object type (supertype) is used.
- The Value type is always stored in Stack. The Referenced Type is stored in Heap.
Unboxing In C#
- The process of converting the reference type into the value type is known as Unboxing.
- It is an explicit conversion process.
To read more, refer to the article: C# – Boxing and Unboxing
45. What is a Hash table class in C#?
The Hashtable class represents a collection of key/value pairs that are organized based on the hash code of the key. This class comes under the System. Collections namespace. The Hashtable class provides various types of methods that are used to perform different types of operations on the hashtables. In Hashtable, keys are used to access the elements present in the collection. For very large Hashtable objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system.
46. Why a private virtual method cannot be overridden in C#?
Because private virtual methods are not accessible outside the class.
47. Write a Features of Generics in C#?
Generics is a technique that improves your programs in many ways such as:
- It helps you in code reuse, performance, and type safety.
- You can create your own generic classes, methods, interfaces, and delegates.
- You can create generic collection classes. The .NET Framework class library contains many new generic collection classes in System.Collections.Generic namespace.
- You can get information on the types used in generic data types at run-time.
48. Difference between SortedList and SortedDictionary in C#.
SortedList a collection of key/value pairs that are sorted according to keys. By default, this collection sort the key/value pairs in ascending order. It is of both generic and non-generic types of collection.
SortedDictionary a generic collection that is used to store the key/value pairs in the sorted form and the sorting is done on the key.
To read more about this, you can refer to Difference between SortedList and SortedDictionary in C#
49. What is the difference between Dispose() and Finalize() methods?
The main difference between both methods is that Dispose() method is used to release the unmanaged resources of an object while Finalize is also used for the same purpose but it doesn’t guarantee the garbage collection of an object. Another major difference is that dispose() method is explicitly invoked by the user and finalize() method is invoked by the garbage collector, just before the object is destroyed.
50. What is the difference between Array and ArrayList?
An array is a group of like-typed variables that are referred to by a common name. ArrayList represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array. Below are the major differences
To read more about this, please refer to C# – Array vs ArrayList
Similar Reads
- interview-questions
Please Login to comment...
- How to Watch NFL on NFL+ in 2024: A Complete Guide
- Best Smartwatches in 2024: Top Picks for Every Need
- Top Budgeting Apps in 2024
- 10 Best Parental Control App in 2024
- GeeksforGeeks Practice - Leading Online Coding Platform
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
C# Coding Questions For Technical Interviews
Introduction.
In this article, we will learn about some of the frequently asked C# programming questions in technical interviews.
Note: We won’t be using any inbuilt functions such as Reverse, Substring etc. for string manipulation, also we will avoid using LINQ as these are generally restricted to be used in coding interviews.
Source Code
Download the source code for all the questions from GitHub
Q.1: How to reverse a string?
Ans.: The user will input a string and the method should return the reverse of that string
- input: hello, output: olleh
- input: hello world, output: dlrow olleh
Q.2: How to find if the given string is a palindrome or not?
Ans.: The user will input a string and we need to print “ Palindrome ” or “ Not Palindrome ” based on whether the input string is a palindrome or not.
- input: madam, output: Palindrome
- input: step on no pets, output: Palindrome
- input: book, output: Not Palindrome
if we pass an integer as a string parameter then also this method will give the correct output
- input: 1221, output: Palindrome
Q.3: How to reverse the order of words in a given string?
Ans.: The user will input a sentence and we need to reverse the sequence of words in the sentence.
- input: Welcome to Csharp corner, output: corner Csharp to Welcome
Q.4: How to reverse each word in a given string?
Ans.: The user will input a sentence and we need to reverse each word individually without changing its position in the sentence.
- input: Welcome to Csharp corner, output: emocleW ot prahsC renroc
Q.5: How to count the occurrence of each character in a string?
Ans.: The user will input a string and we need to find the count of each character of the string and display it on console. We won’t be counting space character.
- input: hello world;
h – 1
e – 1
l – 3
o – 2
w – 1
r – 1
Q.6: How to remove duplicate characters from a string?
Ans.: The user will input a string and the method should remove multiple occurrences of characters in the string
- input: csharpcorner , output: csharpone
Q.7: How to find all possible substring of a given string?
Ans.: This is a very frequent interview question. Here we need to form all the possible substrings from input string, varying from length 1 to the input string length. The output will include the input string also.
- input: abcd , output : a ab abc abcd b bc bcd c cd d
Q.8: How to perform Left circular rotation of an array?
Ans.: The user will input an integer array and the method should shift each element of input array to its Left by one position in circular fashion. The logic is to iterate loop from Length-1 to 0 and swap each element with last element.
- input: 1 2 3 4 5, output: 2 3 4 5 1
Q.9: How to perform Right circular rotation of an array?
Ans: The user will input an integer array and the method should shift each element of input array to its Right by one position in circular fashion. The logic is to iterate loop from 0 to Length-1 and swap each element with first element
- input: 1 2 3 4 5, output: 5 1 2 3 4
Q.10: How to find if a positive integer is a prime number or not?
Ans.: The user will input a positive integer and the method should output “ Prime ” or “ Not Prime ” based on whether the input integer is a prime number or not.
The logic is to find a positive integer less than or equal to the square root of input integer. If there is a divisor of number that is less than the square root of number, then there will be a divisor of number that is greater than square root of number. Hence, we have to traverse till the square root of number.
The time complexity of this function is O(√N) because we traverse from 1 to √N.
- input: 20, output: Not Prime
- input: 17, output: Prime
Q.11: How to find the sum of digits of a positive integer?
Ans.: The user will input a positive integer and the method should return the sum of all the digits in that integer.
- input: 168, output: 15
Q.12: How to find second largest integer in an array using only one loop?
Ans.: The user will input an unsorted integer array and the method should find the second largest integer in the array.
- input: 3 2 1 5 4, output: 4
Q.13: How to find third largest integer in an array using only one loop?
Ans.: The user will input an unsorted integer array and the method should find the third largest integer in the array.
- input : 3 2 1 5 4 , output : 3
Q.14: How to convert a two-dimensional array to a one-dimensional array?
Ans.: The user will input a 2-D array (matrix) and we need to convert it to a 1-D array. We will create a 1-D array column-wise.
- input: { { 1, 2, 3 }, { 4, 5, 6 } }, output: 1 4 2 5 3 6
This question can also be asked to form a 1-D array row-wise. In this case, just swap the sequence of the for loops as shown below. The output will be 1 2 3 4 5 6 for the input matrix mentioned above.
Q.15: How to convert a one-dimensional array to a two-dimensional array?
Ans.: The user will input a 1-D array along with the number of rows and columns. The method should convert this 1-D array to a 2-D array(matrix) of a given row and column. We will create a matrix row-wise.
- input: {1, 2, 3, 4, 5, 6} ,2 ,3
Q.16: How to find the angle between hour and minute hands of a clock at any given time?
Ans.: The user will input the hour and minute of the time and the method should give the angle between the hour hand and minute hand at that given time.
- input: 9 30, output: The angle between hour hand and minute hand is 105 degrees
- input: 13 30, output: The angle between hour hand and minute hand is 135 degrees
The logic is to find the difference in the angle of an hour and minute hand from the position of 12 O Clock when the angle between them is zero. Each hour on the clock represents an angle of 30 degrees (360 divided by 12). Similarly, each minute on the clock will represent an angle of 6 degrees (360 divided by 60) and the angle for an hour will increase as the minutes for that hour increases.
So, our code will be as follows:
Q.17: Explain Bubble Sort Algorithm In C#
This algorithm follows the concept of iterating through the array from the first index to the last index and comparing adjacent elements and then swapping them if they appear in the wrong order. i.e. If the next element is smaller than the current element, they are swapped.
The Time Complexity of bubble sort is O(n²) .
Read Bubble Sort Algorithm In C# to learn more.
Q.18: Explain Quick Sort Algorithm In C#
This Algorithm selects an element as a pivot element from the given array and partitions the array around it such that, Left side of the pivot contains all the elements that are less than the pivot element. The right side contains all elements that are greater than the pivot element. Let P be the index of pivot after partitioning the array. Then, the left subarray(start to P-1) and right subarray(P+1 to end) are sorted recursively to get the final sorted array as output.
The worst-case time complexity of this algorithm is O(N²) . The best-case and average-case time complexity of this algorithm is O(NLogN) .
Read Quick Sort Algorithm In C# to learn more.
Q.19: Explain Merge Sort Algorithm In C#
This algorithm works as follows.
- Divide the unsorted array of size N into N subarrays having single element each.
- Take two adjacent subarrays and merge them to form a sorted subarray having 2 elements.Now we have N/2 subarrays of size 2.
- Repeat the process until a single sorted array is obtained.
In all three cases (worst, average, best), the time complexity of Merge sort is O(NLogN)
Read Merge Sort Algorithm In C# to learn more.
Q. 20: Explain Insertion Sort Algorithm In C#
Insertion sort compares the current element with the largest value in the sorted array. If the current element is smaller then the algorithm finds its correct position in a sorted array and moves the element to that position otherwise if the current element is greater then it leaves the element in its place and moves on to the next element.
To place the element in its correct position in a sorted array, all the elements larger than the current element are shifted one place ahead. Thus the sorted array will grow at each iteration.
Every element is compared to every other element of a sorted array. Hence the complexity of Insertion sort is O(n²) .
Read Insertion Sort Algorithm In C# to learn more.
Q. 21: Explain Selection Sort Algorithm In C#
This algorithm follows the concept of dividing the given array into two subarrays.
- The subarray of sorted elements
- The subarray of unsorted elements
The algorithm will find the minimum element in the unsorted subarray and put it into its correct position in the sorted subarray.
Read Selection Sort Algorithm In C# to learn more.
The time complexity of Selection Sort as O(n²).
Q. 22: Explain Binary Search In C#
Binary search is an efficient and commonly used searching algorithm. This algorithm works only on sorted sets of elements. So if the given array is not sorted then we need to sort it before applying Binary search.
This algorithm searches a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty. If found return the index of matched element, else return -1.
Read Searching Algorithms In C# to learn more.
The array to be searched is reduced by half in every iteration. Hence time complexity of the Binary search is O(LogN) .
I hope you like this collection of interview questions. If you have any suggestions or want me to include any new questions, please let me know through the contact page.
You can download the source code for this article from GitHub and play around to get a better understanding.
You can also read my other articles here
- JavaScript Interview Questions
Popular Posts
- ASP.NET Core 33
- Algorithm 6
- .NET Core 4
- Angular 5 4
- 1,157,984 hits
Next Generation Obfuscator
Code analyzer to find vulnerabilities
Decentralized secret manager for applications
Monitor code exceptions and secure error reporting
Stay up to date with the latest changes and improvements
Open source tools
Documentation
Explore the documentation for each of our products and take your applications to the next level
Ensures the integrity of your application dependencies
Analyze your .NET source code for trojan source vulnerabilities
C# Interview Questions and Answers
Jun 1, 2023 | C# , .NET
Welcome to the ultimate guide to C# Interview Questions and Answers ! Whether you’re a fresh graduate or a seasoned developer, this comprehensive guide is designed to provide you with the knowledge and confidence needed to ace your next C# interview. With a total of 100 questions spanning easy, medium, and hard difficulties, this article covers a wide range of C# concepts and scenarios that you’re likely to encounter.
In this guide, we’ll be discussing:
- C# fundamentals
- Object-oriented programming (OOP) principles in C#
- Collections, data structures, and algorithms
- C# best practices and design patterns
- Working with APIs, libraries, and frameworks
- Real-world problem-solving using C#
So, sharpen your skills and be prepared for your next C# interview by diving deep into these Top 100 C# Interview Questions and Answers !
What does C# stand for?
C# (pronounced as “C-sharp”) is named after a musical notation, where the “sharp” symbol indicates that a note should be played one semitone higher. It is an analogy from the programming language C++, implying that C# is an enhanced and more advanced version of the C++ language.
Which company developed C#?
Microsoft is the company that developed the C# programming language.
What type of language is C#?
C# is a high-level, multi-paradigm programming language, which means it incorporates various programming paradigms such as procedural, object-oriented, and functional programming. It is a statically-typed and managed language, meaning that variable data types are checked at compile-time and C# uses a garbage collector to manage memory.
In which year was C# released?
C# was released in the year 2000.
Can you name the creator of the C# language?
Anders Hejlsberg is the creator of the C# language. He is a prominent software engineer from Denmark who has also contributed to the development of languages like Delphi and TypeScript.
What is the keyword for adding comments in C# code?
There are two types of comments in C#:
- Single-line comments : To create a single-line comment, use the double forward slashes (//) followed by your comment.
- Multi-line comments : To create a multi-line comment, use the forward slash and asterisk(/ ) at the beginning and an asterisk and forward slash ( /) at the end of the comment.
What type of loop does the ‘foreach’ statement create in C#?
The ‘foreach’ statement in C# creates a loop that iterates over a collection or an array. It allows you to work with each element in the collection or array without using an index variable.
In this example, the foreach loop iterates through the “names” array and prints each name to the console.
Can you name a widely used C# Integrated Development Environment (IDE)?
Visual Studio is a widely used IDE for C# development. It is developed by Microsoft and provides numerous features and tools for efficiently developing, testing, and debugging C# programs. Some alternatives to Visual Studio include Visual Studio Code and JetBrains Rider.
What is the file extension for C# source code files?
C# source code files have the file extension “.cs”.
How do you declare a variable in C#?
To declare a variable in C#, you need to specify the datatype followed by the variable name and the assignment operator (=) if you want to initialize the variable with a value at the declaration. Here’s an example:
In this example, we declare and initialize three variables with different data types: int (integer), string (text), and bool (boolean).
What is the syntax for defining a class in C#?
A class can be defined in C# using the class keyword followed by the class name and a pair of curly braces that enclose the class definition. Here’s the general syntax for defining a class in C#:
For example, to create a simple Person class, the following syntax can be used:
How do you instantiate an object of a class in C#?
To instantiate an object of a class in C#, use the new keyword followed by the class name and a pair of parentheses for invoking the constructor. The general syntax for creating an object is:
For example, to create an object of the Person class:
What is the print() method used for in C#?
There is no print() method in C#. Instead, we use the Console.WriteLine() or Console.Write() methods to output text to the console window.
- Console.WriteLine() : Writes the specified text or variable value followed by a new line.
- Console.Write() : Writes the specified text or variable value without appending a new line.
What is the purpose of the Main() method in C#?
The Main() method in C# serves as the entry point of the application. When an application starts executing, the Main() method is the first method that gets called. It typically contains the code that starts the application and initializes its behavior.
The Main() method can be defined with different signatures, including:
- The method must be static and have a return type of either void or int .
- The optional string[] args parameter is used for passing command-line arguments to the application.
Example of a basic Main() method:
How do you create a single-line comment in C#?
To create a single-line comment in C#, use the double forward-slash // . The text following the double forward-slash on the same line will be treated as a comment and ignored by the compiler.
Which keyword is used to create a function in C#?
In C#, the keyword void or a data type (like int , float , string , etc.) is used to create a function. A function is a named block of code that performs a specific task and can return a value.
Here is the general syntax for declaring a function in C#:
- access_modifier : Optional. Determines the visibility of the function (e.g., public , private , protected , internal ).
- return_type : The data type of the value that the function returns. Use void if the function doesn’t return any value.
- FunctionName : The name of the function.
- parameters : Optional. A list of input values (arguments) passed to the function.
How do you create an array in C#?
In C#, arrays are created using the data type followed by square brackets [] . To create an array, you need to specify its data type, size, and (optionally) its elements during initialization.
There are several ways to create an array in C#:
- Declare an array and then initialize its elements:
- Directly initialize an array with elements:
- A shorter syntax for initializing an array with elements:
How do you initialize the value of a variable?
To initialize the value of a variable in C#, first declare it using the data type followed by the variable name. Then, assign a value using the assignment operator = .
Here’s the general syntax for initializing a variable:
What is the base class for all C# classes?
The base class for all C# classes is the System.Object class, which is also referred to as object . Every class in C#, either directly or indirectly, inherits from the object class. When you create a new class, it implicitly inherits from object if no other base class is specified.
In this example, the Person class implicitly inherits from the object class.
What is the format specifier for an Integer in C#?
The format specifier for an integer in C# is {index_number:D} or {index_number:Dn} where D represents the decimal format and n represents the minimum size of the integer field if you want to add leading zeroes.
The index_number indicates the position of the argument to be formatted in the list of arguments provided. To use format specifiers, include them inside the string to be formatted and pass the integer(s) to the string.Format() method or inside the interpolation brackets in an interpolated string.
Congratulations on successfully tackling the first set of easy C# interview questions! You’re now ready to advance to the next round, which consists of medium-easy questions. These questions delve a bit deeper into the concepts of object-oriented programming, exception handling, and basic data structures in C#. Remember, practice makes perfect, so keep honing your skills with these questions and reinforce your understanding of C#.
What is a namespace in C#?
A namespace in C# is a way to group related types and improve the organization of your code. It is used to avoid naming conflicts between different classes or types that may have the same identifier. Namespaces work as a hierarchy, where you can have nested namespaces, and they can span multiple files or even libraries.
For example:
In this example, the MyClass class is declared inside the Company.Project namespace.
What is the purpose of the ‘using’ directive in C#?
The using directive in C# has two primary purposes:
- Namespace importing : using allows you to import a namespace so that you can use the types and members defined in that namespace without specifying their fully qualified name. It makes your code more readable and reduces code complexity. For example:
- Resource management : The using statement is used to help you manage resources like file streams, network connections, or database connections that implement the IDisposable interface. The using statement ensures that the Dispose() method is called on the resource when the block of code is exited, releasing the resources properly. For example:
What are reference types in C#?
Reference types in C# are types that store a reference to the memory location where the data is stored, rather than the actual data itself. When you create objects from classes or use arrays, delegates, interfaces, or most built-in data structures from the .NET Framework, you are working with reference types. Unlike value types, reference types are allocated on the heap, and the garbage collector manages their memory.
Key aspects of reference types:
- When you pass a reference type as a method parameter or assign it to another variable, both variables will refer to the same memory location. Thus, modifications in one variable will affect the other one.
- Reference types can have a null value, which means they don’t reference any memory location or object.
How do you declare a method in C#?
A method in C# is a block of code that performs a specific task and can be called as many times as needed. To declare a method, you need to specify its access level, return type, method name, and a parameter list (if applicable) within the class. Here’s an example:
In this example, we declare a method named Add with the public access modifier, an int return type, and two parameters of type int. The method calculates the sum of the two numbers and returns the result.
What are the basic access modifiers available in C#?
Access modifiers in C# control the visibility and accessibility of class members (methods, properties, fields, etc.) and classes themselves. The basic access modifiers available in C# are:
- public : Members and classes with the public access modifier are accessible from any code inside the same assembly or another assembly that references it.
- private : Members declared as private can only be accessed within the same class. They are not visible to other classes, even within the same assembly. By default, class members are private if no access modifier is specified.
- protected : Members declared with the protected access modifier can be accessed within the same class, as well as within derived classes. They are not visible to other non-derived classes in the same assembly.
- internal : Members and classes with the internal access modifier can be accessed anywhere within the same assembly but are not visible to other assemblies.
- protected internal : Members declared with the protected internal access modifier are accessible within the same assembly and by derived classes in another assembly.
What is a constructor in C#?
A constructor is a special method in a class that is called when an object of that class is created. Constructors have the same name as the class and don’t have an explicit return type. Constructors can be overloaded, which means you can have multiple constructors within a class with different parameter lists.
Constructors are used to:
- Initialize the object’s state (set default values for properties, fields, etc.).
- Allocate resources, such as memory or network connections.
- Verify input parameters or ensure that the object is in a consistent state.
What are indexers in C#?
Indexers in C# are class members that allow you to access an object’s elements using index notation, similar to how you access elements in an array or a collection. Indexers provide a more intuitive way to interact with the elements stored in a class, especially when it contains a collection or an array.
To define an indexer, you need to use the this keyword, the type of the elements you want to access, and implement the get and set accessors to access and modify the underlying elements.
Here’s an example of an indexer implementation for a simple custom collection class:
How do you create custom exception handling in C#?
To create custom exception handling in C#, you can create a custom exception class that inherits from the built-in System.Exception class or one of its derived classes. Custom exceptions are useful when the built-in exception classes don’t cover specific error situations in your application.
Here’s an example of a custom exception class:
Now you can throw and catch the CustomException in your code:
How can you prevent class inheritance in C#?
To prevent class inheritance in C#, you can use the sealed keyword when declaring the class. A sealed class cannot be inherited by any other class, and it is a compile-time error to try to inherit from a sealed class.
What is the difference between ‘const’ and ‘readonly’ in C#?
const and readonly are both used in C# to create variables that cannot be changed after they are assigned a value, but they have some differences:
- Can only be applied to fields, not properties.
- Must be assigned a value at declaration.
- The value assigned must be a constant expression that can be resolved at compile-time.
- const fields are implicitly static, and you cannot use instance members to initialize them.
- Can be applied to fields and properties.
- Can be assigned a value at declaration or inside a constructor.
- The value assigned can be a constant expression or a non-constant expression that is resolved at runtime.
- readonly fields can be either static or instance members, depending on your needs.
Summary of differences:
- const is a compile-time constant, and its value cannot depend on runtime conditions. readonly is a runtime constant, and its value can be determined at runtime.
- const fields are implicitly static, while readonly fields can be either static or instance members.
What is garbage collection in C#?
Garbage collection (GC) in C# is an automatic memory management system provided by the .NET Framework. It is responsible for freeing up memory that is no longer being used by the application. The garbage collector keeps track of objects allocated on the heap, determines which objects are no longer accessible, and reclaims the corresponding memory space.
The main benefits of garbage collection are:
- Improved developer productivity by reducing boilerplate code for manual memory management.
- Prevention of memory leaks, as unused memory gets automatically reclaimed.
- Protection against certain programming bugs, like dangling pointers or double-free issues.
C#’s garbage collection is non-deterministic, meaning that you cannot predict when exactly the garbage collector will run. It uses a generational approach, classifying objects into generations to reduce the time and resources spent on garbage collection. The garbage collector will typically run when available memory is getting low or when the system is idle.
While garbage collection can bring benefits, care should still be taken when dealing with heavy resource-consuming objects, like file handlers or database connections. Classes that deal with such resource management should implement the IDisposable interface to allow deterministic resource release.
Describe object-oriented programming (OOP) in C#. Name the main OOP concepts.
Object-Oriented Programming (OOP) is a programming paradigm that represents concepts as objects with attributes (fields or properties) and behaviors (methods). The goal of OOP is to produce reusable, maintainable, and modular code by emphasizing the separation of concerns and adhering to OOP principles.
C# is an object-oriented programming language, and it fully supports OOP concepts. The main OOP concepts in C# are:
- Encapsulation : The process of bundling data (attributes) and methods (functions) that operate on the data into a single unit (class). Encapsulation helps to protect the internal state of an object and control access to its attributes.
- Inheritance : The ability of a class to inherit properties, methods, and behaviors from another class ( base class) to enable code reuse and represent a hierarchy of related objects. In C#, a class can only inherit from a single class but can implement multiple interfaces.
- Polymorphism : Polymorphism is the ability of a single interface to represent different types or the ability of a method to have multiple implementations based on derived types. In C#, polymorphism can be achieved through overloading (using the same method name with different parameters in the same type) and overriding (redefining a base class method in a derived class).
- Abstraction : Abstraction is the process of simplifying complex real-world objects and concepts by focusing on their essential features. Abstraction can be achieved in C# by using abstract classes and interfaces to define the common properties and methods that a group of related types must implement.
How can you create a generic class or method in C#?
A generic class or method in C# is a class or method that can work with any type without the need for explicit type casting or type checking at runtime. Generic types increase the reusability, flexibility, and type safety of your code.
To create a generic class or method in C#, you need to use the angle brackets <T> to define a type parameter. Here’s an example of a generic class and a generic method:
In this example, T is the type parameter for both the generic class GenericList<T> and the generic method Max<T>(T, T) . The method also uses a constraint ( where T : IComparable<T> ) to ensure that the type parameter T implements the IComparable<T> interface.
What is the difference between an abstract class and an interface in C#?
Both abstract classes and interfaces are used to define abstract entities in C#, but they have some differences:
Abstract Class :
- Can have both abstract and non-abstract (implemented) methods.
- Can have fields (variables), properties, and events.
- Supports constructors and destructors.
- Can have access modifiers for members (public, protected, internal, etc.).
- Supports inheritance; a class can inherit from only one abstract class.
- Can have complete implementations for some methods or properties, but cannot be instantiated directly.
Interface :
- Can only have method, property, and event signatures (no implementation).
- Cannot have fields or constructors.
- No member (methods, properties, events) can have an access modifier (all are implicitly public).
- Supports multiple inheritance; a class can implement multiple interfaces.
- Cannot have any implementation details, just the signatures of the members.
In summary, abstract classes provide a base implementation that can be shared among multiple derived classes, while interfaces define a contract that any implementing class must adhere to. Use an abstract class when you want to provide some default behavior and an interface when you need multiple inheritance or want to strictly define a common functionality contract.
What is the difference between ‘out’ and ‘ref’ parameters in C#?
Both out and ref parameters in C# are used to pass arguments by reference, allowing a method to modify the values of the passed variables outside the method. However, there are some differences between the two:
- The variable passed as a ref parameter must be initialized before passing it to the method.
- The method called doesn’t have to assign a value to the ref parameter, as it already has a value. Example:
- The variable passed as an out parameter doesn’t need to be initialized before passing it to the method.
- The method called must assign a value to the out parameter before the method returns. Example:
In summary, use ref parameters when you want the called method to modify an already initialized variable, and use out parameters when you want the called method to provide a value that doesn’t depend on the initial value of the passed variable.
Describe the concept of delegates in C#.
A delegate in C# is a reference type that represents a method with a specific signature. Delegates allow you to treat methods as objects and pass them as arguments, return them from methods, or store them as properties. Delegates provide a way to create function pointers or callbacks, making it possible to develop more flexible and extensible applications.
Delegates are particularly useful when designing event-driven systems, where components must react to other component events or signals without tight coupling. Here’s an example of a delegate declaration, instantiation, and invocation:
C# also supports generic delegates, multicast delegates, and built-in Func<T, TResult> and Action<T> delegates (introduced in .NET Framework 3.5) for increased flexibility and usability.
What is the difference between the ‘==’, ‘Equals’, and ‘ReferenceEquals’ methods?
In C#, ‘==’, ‘Equals’, and ‘ReferenceEquals’ are used to compare objects or values for equality, but with some differences:
- == operator : The ‘==’ operator compares two objects or values for equality. For value types, it checks if the values are equal. For reference types, it checks if the object references are equal, which means they’re pointing to the same object in memory. This behavior can be overridden for custom reference types by overloading the ‘==’ operator.
- Equals : The ‘Equals’ method compares two objects for equality by checking their values, not their references. The default implementation of ‘Equals’ for reference types checks reference equality, but it can be overridden in your custom class to provide value-based comparison.
- ReferenceEquals : The ‘ReferenceEquals’ method checks if two object references are equal, meaning they point to the same object in memory. It does not compare values. This method cannot be overridden and is useful when you need to perform a strict reference comparison.
In summary, use the ‘==’ operator for simple value comparisons and reference comparisons, ‘Equals’ when you need to perform a value-based comparison for reference types, and ‘ReferenceEquals’ when you want to specifically compare object references.
Explain the concept of dependency injection in C#.
Dependency Injection (DI) is a design pattern used in C# and other object-oriented languages that helps to separate the creation and management of object dependencies, increasing the modularity, maintainability, and testability of an application.
In the context of C#, dependency injection is a technique in which an object receives its dependencies (objects, services, or values it relies on) from an external source instead of directly creating, managing, or looking up these dependencies. Dependency injection can be achieved using constructor injection, property injection, or method injection:
- Constructor Injection : The dependencies are passed to the object through its constructor. This is the most common and recommended method of dependency injection because it enforces that the object is created with all required dependencies and in a valid state.
- Property Injection : The dependencies are set through public properties or setters of an object. This technique is used when the dependency is optional or can be changed during object lifetime.
- Method Injection : The dependencies are passed to an object through a method. This technique is suitable when an object requires a specific dependency for just one method and not for the entire lifecycle of the object.
In C#, popular dependency injection frameworks like Autofac, Unity, or built-in .NET Core Dependency Injection can be used to manage and resolve object dependencies.
How does C# support multiple inheritances?
C# does not directly support multiple inheritance for classes. A class in C# can inherit from only one base class. However, C# allows multiple inheritance through interfaces, as a class can implement multiple interfaces.
When a class implements multiple interfaces, it essentially inherits the behavior of each interface, and each interface can be considered as a contract that the class must adhere to. This approach to multiple inheritance enables flexibility while avoiding the complexity and ambiguity that can arise from multiple class inheritance.
In this example, Car implements the IEngine and IDriver interfaces to provide multiple inheritance-like functionality.
What is method overloading in C#?
Method overloading is a feature in C# that allows a class to have multiple methods with the same name, but different parameter lists. The correct method is called at compile time based on the arguments provided. Method overloading is a way to achieve compile-time polymorphism. The return type of the methods doesn’t factor into overloading. The method signature, i.e., the method name and parameter list, must be unique.
Here’s an example:
In the example above, we’ve overloaded the Add method with different parameter lists.
Great job completing the medium-easy questions! As you’ve noticed, the complexity has gradually increased, and you’ve now reached the medium-level questions. In this section, we’ll be focusing on more advanced features of C#, such as generics, delegates, events, and design patterns. Don’t worry if some of these topics are unfamiliar; this guide is here to help you expand your knowledge and master these essential C# concepts.
How do you create a property in C#?
In C#, properties are members of a class that provide a flexible mechanism to read, write, or compute the value of private fields. Properties can be created using get and set accessors in the property definition. A property can have a get accessor, a set accessor, or both, depending on whether you want the property to be read-only, write-only, or read-write.
Here’s an example of a property with both get and set accessors in C#:
In C# 3.0 and later, you can use auto-implemented properties, which enables you to create properties without having to define the backing field explicitly:
What is the purpose of the ‘params’ keyword in C#?
The params keyword in C# allows a method to accept a variable number of arguments of a specified type. Using the params keyword, you can pass an array of values or separate comma-separated values to the method. Inside the method, the params parameter is treated like an array.
Here’s an example of using the params keyword:
You can call the Sum method with any number of arguments, like this:
What are the characteristics of a static class in C#?
In C#, a static class is a class that cannot be instantiated or inherited. It can only have static members, and it cannot have instance members (like instance properties, methods, or fields). The main characteristics of a static class are:
- It is declared with the static keyword.
- It cannot have a constructor (except the static constructor).
- It cannot be instantiated or inherited.
- All members of a static class must also be static.
- It can be accessed directly using the class name, without creating an instance.
A common use of static classes is for utility functions and extension methods. Here’s an example of a static class in C#:
To use this static class, you simply call its methods like this:
How do you pass data between two forms in C#?
In C#, there are several ways to pass data between two forms in a Windows Forms application. One common approach is to use public properties or methods to expose the data that needs to be passed. Here’s an example:
- Create a second form with a public property that will hold the data to be passed.
- In the first form, instantiate the second form and set the Data property with the data you want to pass.
In this example, when the user clicks the OpenSecondFormButton , the second form opens, and the Data property of the second form contains the data passed from the first form.
What is the difference between a class and an object in C#?
In C#, a class is a blueprint for creating objects. It defines the structure, properties, and methods that objects of that class will have. Classes are reference types, and they can inherit from other classes to extend or override functionality.
An object, on the other hand, is an instance of a class. It is created from the class definition and occupies memory when instantiated. Objects are instances of classes, and they contain the data (fields) and behaviors (methods) that are defined in the class.
For example, consider a Car class:
In this example, Car is the class, and it defines the structure and behavior of car objects. To create objects (instances) of the class, you use the new keyword, like this:
In this example, car1 and car2 are objects (instances) of the Car class, and they have their own individual sets of properties and methods.
What is a delegate in C#?
A delegate in C# is a type that defines a method signature and can hold a reference to a method with a matching signature. Delegates are similar to function pointers in C++, but they are type-safe and secure. They are commonly used for implementing events and callbacks.
Delegates can be used to pass methods as arguments, assign them to class properties, or store them in collections. Once a delegate is defined, it can be used to create delegate instances that point to methods with the same signature.
Here’s an example of a delegate in C#:
In this example, MyDelegate is a delegate that defines the method signature for methods that take a string argument and return void . The Main method creates a delegate instance, assigns the MyClass.DisplayMessage method to it, and invokes the method through the delegate.
How do you implement polymorphism in C#?
Polymorphism is one of the fundamental principles of object-oriented programming. It allows objects of different classes to be treated as objects of a common superclass. In C#, there are two types of polymorphism: compile-time (method overloading) and runtime (method overriding and interfaces).
Method overriding and interfaces are the common ways to implement runtime polymorphism. Here’s an example using method overriding:
In this example, we define a base class Animal and a derived class Dog . The Speak method in the Animal class is marked as virtual , allowing its behavior to be overridden by derived classes. The Dog class overrides the Speak method with its own implementation. When we create a Dog object and assign it to an Animal variable, the overridden method in the Dog class is called at runtime, exhibiting polymorphism.
To implement polymorphism via interfaces, you can define an interface and then have classes implement the interface methods. For example:
In this example, we define an ISpeak interface with a Speak method. The Dog and Cat classes implement this interface and provide their own implementation of the Speak method. We can create and assign objects of these classes to an ISpeak variable, and the appropriate implementation of the Speak method is called at runtime, demonstrating polymorphism.
What is a struct in C#?
A struct (short for “structure”) in C# is a value type that can contain fields, properties, methods, and other members like a class. However, unlike classes, which are reference types, structs are value types and are stored on the stack. Structs do not support inheritance (except for implicitly inheriting from System.ValueType), and they cannot be used as a base for other classes or structs.
Structs are useful for representing small, lightweight objects that have a small memory footprint and do not require garbage collection overhead. They are commonly used to represent simple data structures, such as points in a 2D space, dates, time intervals, and colors.
Here’s an example of a struct in C#:
In this example, we define a Point struct with properties X and Y , a constructor, and a method DistanceToOrigin . We can create Point instances and use their methods like we would with class instances.
What is the difference between ‘throw’ and ‘throw ex’ in exception handling?
In C#, when handling exceptions, it’s important to understand the difference between throw and throw ex :
- throw : When you catch an exception and want to rethrow the original exception, you use the throw statement without specifying any exception object. This preserves the original exception’s stack trace and allows the upstream exception handler to access the full stack trace.
- throw ex : When you catch an exception and want to throw a new or modified exception object, you use the throw ex statement, where ex is an instance of an exception. This replaces the original exception’s stack trace, and the upstream exception handler will only see the stack trace starting from the point where throw ex was called.
In Method1 , we catch an exception and rethrow it using throw . The upstream exception handler can access the original stack trace of the exception. In Method2 , we catch an exception and throw a new ApplicationException with the original exception as its inner exception using throw ex . The upstream exception handler will see the stack trace starting from the point where throw ex was called.
What is a nullable type and how is it used in C#?
Nullable types in C# are value types that can have a ‘null’ value. By default, value types cannot have a ‘null’ value, as they have a default value (like 0 for int, false for bool, etc.). To create a nullable type, you can use the built-in Nullable<T> structure or the syntactic sugar ? modifier.
Nullable types are useful when you need to indicate the absence of a value or when working with data sources (like databases) that might contain missing values.
Creating nullable types:
Nullable types can be checked for having a value using the HasValue property and retrieved using the Value property. Alternatively, you can use the GetValueOrDefault method to get the value if it exists or a default value:
C# also supports nullable value type conversions and null coalescing using the ?? operator to provide a default value when a nullable type is ‘null’:
Describe the concept of LINQ in C#.
Language Integrated Query (LINQ) is a feature introduced in C# 3.0 (.NET Framework 3.5) that provides a set of query operators and a unified query syntax for querying, filtering, and transforming data from various types of data sources like collections, XML, databases, or even custom sources.
LINQ allows you to write type-safe, powerful, and expressive queries directly in C# with the benefits of full support from the compiler, static typing, and IntelliSense.
LINQ offers two types of syntax for writing queries:
- Query Syntax : This is a more SQL-like, declarative syntax that provides a high level of abstraction and readability. Query syntax requires the from keyword (retrieves the data), select keyword (specifies the output), and optional keywords (such as where , group , or orderby ).
- Method Syntax : This is based on LINQ extension methods of the System.Linq.Enumerable class and uses lambda expressions to manipulate the data. Method syntax provides a more functional approach but may be less readable if the query is complex.
LINQ supports a variety of providers like LINQ to Objects (for in-memory collections), LINQ to XML (for XML documents), and LINQ to Entities (for entity framework), enabling developers to work with different data sources using a similar query syntax.
What is a lambda expression in C#?
A lambda expression in C# is an anonymous function that is used to create inline delegates, expression trees, and expressions for LINQ queries or other functional programming constructs. Lambda expressions rely on the => operator (called the lambda operator) to separate the input parameters and the expression or statement block.
Lambda expressions can be used for both expression and statement lambdas:
- Expression Lambda : This consists of an input parameter list, followed by the lambda operator, and a single expression. An expression lambda automatically returns the result of the expression without the need for an explicit return statement.
- Statement Lambda : This is similar to an expression lambda but contains a statement block enclosed in braces {} instead of a single expression. A statement lambda allows for multiple statements and requires an explicit return statement if a value must be returned.
Lambda expressions are a concise and efficient way of representing delegates or expressions, and are commonly used with LINQ queries, event handlers, or higher-order functions that expect a function as an argument.
Describe the async and await keywords in C#. How can they be used together?
In C#, the async and await keywords are used to write asynchronous code that can run concurrently without blocking the main execution thread. This allows for more efficient and responsive applications, particularly in cases of I/O-bound operations (e.g., calling web services, reading files, or working with databases) or CPU-bound operations that can be parallelized.
- async : The async keyword is added to a method to indicate that it’s an asynchronous method. An async method usually returns a Task for void-returning methods or Task<TResult> for methods that return a value of type TResult. An async method can contain one or more await expressions.
- await : The await keyword is used to pause the execution of an async method until an awaited task completes. It asynchronously waits for the task to complete and returns the result (if any) without blocking the main execution thread. The await keyword can only be used inside an async method.
When using async and await together, ensure that you propagate the asynchronous behavior up the call stack by marking every calling method with the async keyword and awaiting async methods in the method body. This “async all the way” approach ensures that the benefits of asynchronous programming are fully utilized throughout the application.
What is the Task Parallel Library (TPL) and how does it relate to C#?
The Task Parallel Library (TPL) is a set of APIs introduced in the .NET Framework 4.0 to simplify parallelism, concurrency, and asynchronous programming. It is part of the System.Threading.Tasks namespace and provides a higher-level, more abstract model for working with multithreading, asynchrony, and parallelism than the traditional lower-level threading constructs (e.g., ThreadPool or Thread class).
TPL’s main components include Task , Task<TResult> , and Parallel classes, which serve the following purposes:
- Task : Represents an asynchronous operation that doesn’t return a value. Tasks can be awaited using the await keyword, or you can attach continuations to them using the ContinueWith method.
- Task : Represents an asynchronous operation that returns a value of type TResult. It derives from the Task class and has a Result property that holds the result once the task is complete.
- Parallel : Provides parallel versions of for and foreach loops, as well as an Invoke method to execute multiple actions concurrently. The Parallel class can automatically utilize multiple CPU cores or threads, allowing you to parallelize CPU-bound operations easily.
The TPL allows developers to write efficient and scalable parallel, concurrent, and asynchronous code in C# without having to deal directly with low-level threading and synchronization primitives.
Can you explain covariance and contravariance in C#?
Covariance and contravariance are terms related to the type relationships in C# when dealing with generics, delegates, or arrays. They describe how a derived type can be used in place of a base type (or vice versa) when assigning variables, parameters, or return values.
- Covariance (from less derived type to more derived type): Covariance allows you to use a more derived type instead of the original generic type parameter. In C#, covariance is supported for arrays, interfaces with generic parameters, and delegates with matching return types.
- Contravariance (from more derived type to less derived type): Contravariance allows you to use a less derived type instead of the original generic type parameter. In C#, contravariance is supported for interfaces with generic parameters marked with the in keyword and delegates with matching input parameters.
Covariance and contravariance can help increase the flexibility and reusability of your code by allowing assignments and conversions between different type hierarchies without explicit type casting.
Describe the differences between early binding and late binding in C#.
Early binding and late binding are two mechanisms in C# related to how the compiler and runtime resolve types, methods, or properties during program execution.
- Early Binding : Also known as static or compile-time binding, early binding refers to the process of resolving types, methods, or properties at compile time. With early binding, the compiler validates that the members being called exist and that they’re being called correctly regarding their accessibility, parameters, and return values. Early binding provides benefits like better performance (due to reduced runtime overhead) and type safety, as the compiler can catch and report errors during compilation. Example:
- Late Binding : Also known as dynamic or runtime binding, late binding refers to the process of resolving types, methods, or properties at runtime. With late binding, the actual binding of members occurs only when the code is executed, which can lead to runtime errors if the members don’t exist or are not accessible. Late binding is often used when the exact types or members aren’t known at compile time or when working with COM objects, reflection, or dynamic types. Late binding has certain advantages, such as allowing for more flexibility, extensibility, and the ability to work with types that aren’t known at compile time. However, it also comes with disadvantages such as increased runtime overhead (due to additional type checks, method lookups, or dynamic dispatch) and a loss of type safety (due to the possibility of runtime errors). Example:
Understanding the differences between early and late binding can help you make informed decisions about when to use each mechanism, based on your requirements for type safety, performance, and flexibility.
What is the Global Assembly Cache (GAC) in C#?
The Global Assembly Cache (GAC) is a centralized repository or cache for storing and sharing .NET assemblies (DLLs) on a machine. The GAC is part of the .NET Framework and is used to avoid DLL conflicts and enable side-by-side execution of different versions of the same assembly.
Assemblies stored in the GAC must have a strong name, which consists of the assembly name, version number, culture information (if applicable), and a public key token (generated from the developer’s private key). This strong name allows the GAC to uniquely identify and manage each assembly and its versions.
To install an assembly in the GAC, you can use the gacutil utility, or you can drag and drop the assembly into the GAC folder using Windows Explorer.
As a developer, you typically don’t need to explicitly reference assemblies from the GAC, as the .NET runtime automatically looks for them in the GAC before it searches other locations. However, it’s essential to be aware of the GAC and understand how it impacts assembly sharing, versioning, and deployment scenarios.
Explain how the ‘var’ keyword works in C#, and give a practical example of its use.
In C#, the var keyword is used to implicitly type a local variable when you don’t need or want to explicitly specify the type. When you use the var keyword, the C# compiler infers the type of the variable based on the value assigned to it during initialization. The variable is still strongly-typed at compile-time, just like any other typed variable.
It’s important to note that the var keyword can only be used with local variables, and the variable must be initialized with a value during its declaration (otherwise, the compiler cannot infer the type).
Using the var keyword can provide benefits like increased readability and ease of refactoring, particularly when dealing with complex or verbose types (e.g., generics or anonymous types).
In the example above, the compiler infers the types of the variables based on their assigned values. Using var here can make the code more concise and readable.
However, it’s important to strike the right balance between readability and maintainability. In cases where using var might decrease the readability or understandability of the code, it’s better to use an explicit type.
What is a thread-safe collection, and can you give an example of one in C#?
A thread-safe collection is a data structure designed to be safely and correctly accessed or modified by multiple threads concurrently. In general, most built-in .NET collection classes (e.g., List<T> , Dictionary<TKey, TValue> , etc.) are not thread-safe, which means that concurrent access or modifications can lead to unexpected results or data corruption.
To provide thread-safe collections, the .NET Framework offers the System.Collections.Concurrent namespace, which includes several thread-safe collection classes, such as:
- ConcurrentBag<T> : An unordered collection of items that allows duplicates and has fast Add and Take operations.
- ConcurrentQueue<T> : A first-in, first-out (FIFO) queue that supports concurrent Enqueue and TryDequeue operations.
- ConcurrentStack<T> : A last-in, first-out (LIFO) stack that supports concurrent Push and TryPop operations.
- ConcurrentDictionary<TKey, TValue> : A dictionary that supports thread-safe Add , Remove , and other dictionary operations.
In the example above, the ConcurrentQueue<int> instance safely handles concurrent Enqueue operations without the need for manual locking or synchronization.
Keep in mind that using thread-safe collections can come with some performance overhead, so you should carefully evaluate the trade-off between thread-safety and performance in your specific use case.
Explain how exception handling works in C# using try-catch-finally blocks.
Exception handling in C# is a mechanism for dealing with unexpected or exceptional conditions that may occur during program execution. It helps to maintain the normal flow of the program and ensure that resources are properly released even when an exception is encountered.
In C#, exception handling is primarily done using the try , catch , and finally blocks:
- try : The try block contains the code that might throw an exception. You enclose the code that may raise exceptions within this block.
- catch : The catch block is used to handle the specific exception that is thrown within the try block. You can have multiple catch blocks for different exception types. The first matching catch block that can handle the exception type will be executed.
- finally : The finally block is used to execute code regardless of whether an exception was thrown or not. This block is optional, and it’s typically used for resource cleanup (e.g., closing files or database connections).
In the example above, the try block attempts to execute a division operation that throws a DivideByZeroException . The catch block handling DivideByZeroException is executed, and the exception message is written to the console. Regardless of the exception, the finally block will always execute, ensuring that any necessary cleanup is performed.
Understanding and properly utilizing exception handling in C# allows you to write more robust, resilient, and fault-tolerant applications.
Superb work in completing the medium questions! You’ve shown great proficiency in C#, and now you’re ready for the next challenge: medium-hard questions. In this section, we explore advanced topics such as LINQ, multithreading and parallel programming, and C# 8.0 features. These questions will truly put your C# skills to the test, but don’t be discouraged. Keep pushing through and learning as you go!
What are the differences between IEnumerable, ICollection, and IList interfaces in C#?
IEnumerable, ICollection, and IList are interfaces provided by the .NET framework libraries for working with collections of data. They have the following differences:
IEnumerable :
- Provides the basic functionality to iterate through a collection using a foreach loop.
- It supports only-read access.
- Ideal for situations where you only need to iterate through a collection.
- Defines only one method: GetEnumerator(), which returns an IEnumerator.
ICollection :
- Inherits from IEnumerable.
- Represents a collective group of elements with the addition of functionalities like size, enumeration, and synchronization.
- Adds basic collection manipulation like Add, Remove, and Clear.
- Supports both read and write access.
- Provides properties like Count and IsReadOnly.
- Provides methods like Add, Remove, Clear, and Contains.
- Inherits from ICollection.
- Represents a list of items that are accessible by index.
- Provides advanced collection manipulation like insert and remove by index.
- Supports random access to elements.
- Contains properties like Item (property to access elements by index) and methods like Insert and RemoveAt.
Explain the concept of partial classes in C#.
A partial class, denoted with the partial keyword in C#, is a class whose definition can be split into multiple separate class definitions in the same namespace. All the separate class definitions with the partial keyword are combined by the compiler into a single class at the compile-time. Partial classes can be used to logically organize a large class or to enhance classes generated by code generators (e.g., for UI or web services).
Advantages of partial classes:
- Provides better maintainability by dividing a large class into multiple logical files.
- Enhances code generation in situations when you need to add your own code to a generated class.
- Allows multiple developers to work on the same class simultaneously without conflicts.
At compile-time, these two files are combined into a single class.
What is boxing and unboxing in C#? Provide examples.
Boxing and unboxing are operations in C# related to type conversions between value types and reference types.
Boxing is the process of converting a value type to a reference type (System.Object) by wrapping the value type inside a new object and storing it on the heap. The conversion is implicit. Example:
Unboxing is the process of converting a reference type back to a value type by extracting the value from the object and storing it on the stack, after checking its type is compatible. Unboxing requires an explicit type cast. Example:
Note that these operations come with a performance cost as they involve memory allocation and deallocation, particularly when dealing with large data structures or frequent conversions.
How can you implement multithreading in C#?
Multithreading is a technique for executing multiple threads concurrently to improve performance and responsiveness in applications. In C#, there are several ways to implement multithreading, including:
- Using the Thread class from the System.Threading namespace. Creating a new Thread requires passing a method (delegate) as a parameter to its constructor that will be executed when the thread starts.
- Using Task and Task<TResult> classes from System.Threading.Tasks . Tasks provide better abstraction and integration with the ThreadPool, eliminating the need to manually manage threads and their resources.
- Using the async and await keywords for asynchronous programming. This approach simplifies working with long-running methods without blocking the calling thread.
Additionally, you can use Parallel class for parallel operations on collections (e.g., Parallel.ForEach or Parallel.For ), and ThreadPool for managing a pool of threads.
What is the concept of anonymous methods in C#?
Anonymous methods in C# are a way to define inline unnamed methods that can be assigned to delegate instances. They provide a concise way to create small functions without declaring an entire named method. Anonymous methods use the delegate keyword and do not require a separate method declaration.
In C# 3.0 and later, anonymous methods can be replaced by lambda expressions, which provide a more concise syntax. The previous example can be rewritten as:
What are the different types of delegates in C#?
Delegates in C# can be divided into three main types:
- Singlecast Delegates : These delegates reference a single method with a matching signature. When the delegate is invoked, it calls the referenced method.
- Multicast Delegates : These delegates can reference multiple methods with a matching signature. When the delegate is invoked, it calls all the referenced methods in the order they were added. Multicast delegates are created using the += or -= operators.
- Generic Delegates : These delegates use generic type parameters, allowing them to work with multiple types without casting or boxing/unboxing. C# provides three built-in generic delegates: Func , Action , and Predicate .
- Func<TResult> : A delegate that represents a function with a return type.
- Action : A delegate that represents a void-returning method with no parameters.
- Predicate<T> : A delegate that represents a method that takes an input parameter and returns a boolean.
Example using Func and Action :
Explain the principle of encapsulation in C#.
Encapsulation is a fundamental object-oriented programming principle that refers to the bundling of data (properties) and behavior (methods) within a single class or object. This concept aims to:
- Hide internal implementation details from other parts of the application (encapsulating inner workings).
- Expose a well-defined public interface for communication between objects.
- Easily update or modify the implementation without affecting the external callers.
In C#, encapsulation can be achieved using access modifiers (public, private, protected, internal, protected internal) to restrict access to the class members and by combining fields, properties, and methods inside a class.
What is the benefit of using an extension method in C#?
Extension methods in C# are a way to add new methods to an existing type without modifying the original type, inheriting from it, or using any other type of customization. Extension methods can be useful in situations where you do not have the source code of the type, or you want to extend a sealed (non-inheritable) class. The benefits of using extension methods are:
- Improved code readability and maintainability.
- The ability to extend a class without modifying its code.
- Adding functionality to a class without inheriting from it or using composition.
An extension method is defined as a static method in a static class and uses the this keyword before the first parameter to specify the type it is extending. Example:
Here, the Reverse() extension method is added to the string type and can be called as if it was a native method of the string class.
How does C# support operator overloading?
Operator overloading in C# allows any custom class or struct to redefine the behavior of certain operators (like + , - , * , == , etc.) for its instances. This can provide a more intuitive and natural syntax when working with objects of the custom type.
To overload an operator, you need to define a public static method in your class with the operator keyword followed by the operator symbol being overloaded. The method must have the required parameters and return type as specified by the operator being overloaded.
What is the use of the ‘base’ keyword in C#?
The base keyword in C# is a reference to a class’s immediate parent class (base class) and is used to access its members, including properties, methods, and constructors. The base keyword is often used in the following scenarios:
- Calling base class constructors : When creating an instance of a derived class, you can call a base class constructor from the derived class constructor using the base keyword followed by the constructor parameters.
- Accessing base class methods : In a derived class, you may want to access the original implementation of an overridden or shadowed method from the base class. In this case, you can use the base keyword followed by the method name.
By using the base keyword, you can extend or reuse functionality from the base class while maintaining the inheritance relationship between the classes.
Explain how LINQ queries work in C# and give an example.
Language Integrated Query (LINQ) is a powerful feature in C# that allows you to query data from various data sources directly from within the C# language.
In LINQ, query operations are performed using familiar language syntax. This makes the query quite readable and easy to understand. LINQ queries can work with anything that implements the IEnumerable interface, such as arrays and collections. Plus, they are statically typed and use IntelliSense, making writing queries error-free.
Here is an example.
In the above example, evenNumbers will hold 2, 4, 6, and 8. The query determines the numbers in the input sequence that fulfill the condition (num % 2 == 0), which are even numbers.
What is a Thread Pool in C#? How can it be beneficial than creating a new thread?
A Thread Pool in C# is a collection of threads that are made available for use by various tasks. Instead of each task creating, starting, and stopping a new thread, tasks can use a thread from the thread pool, greatly improving efficiency.
There are several benefits to using a thread pool:
- Threads in a thread pool are reused, avoiding the overhead of creating a new thread every time.
- The number of threads in the application does not spike up, avoiding the issue of too many threads which can slow down the system.
- The system automatically manages the details of how and when tasks are assigned to threads in the thread pool.
Here is how you can use the ThreadPool:
In the above line, SomeMethod is a method that is executed on a separate thread.
What is a Nullable type in C# and how do you use it?
In C#, Nullable types are value types which can take null values. This capability is crucial because the value types don’t normally take null values. A Nullable type is declared using the ? symbol after the value type.
For instance, int? is a Nullable type based on the int type. You can assign any value which an int can take, plus an additional null value.
Here is how you can use it:
In the code above, because int? is a nullable type, we’re able to assign a null value to number .
How does C# manage memory automatically?
Memory management in C# is handled through the Garbage Collector (GC), an automatically enabled feature in the .NET framework. Here is how GC works:
- When an object is created in .NET, it is stored in the heap memory.
- The GC automatically reclaims the memory taken up by the unused objects, or the ones that are no longer being used by the application.
- The GC does this automatically without the programmer having to write any specific code for it. This automatic feature saves the developer from various potential errors like memory leaks and invalid memory references.
- The GC also compacts the space, thus enhancing memory locality, which in turn increases performance since objects that are referenced frequently end up being located close each other.
How do you use reflection in C# to inspect an object’s properties and methods?
Reflection in C# is a feature that enables you to obtain type information at runtime, inspect the metadata of types, create and manipulate instances of types, and invoke methods.
Here’s an example of using reflection to get an object’s properties:
In the example above, GetType() gets the type of the person object, GetProperties() gets all the properties of that type, then we loop through the properties and for each property name and its value, we write it out to the console.
Can you explain what a Lambda expression is and give an example of its use?
A lambda expression in C# is an anonymous function or method that can be used wherever delegate types are required. They provide a simple and concise way of defining methods. Lambda expressions use the => operator, which can be read as “goes to”.
For example, here is a lambda expression that squares a number:
Here x is the input parameter (can be more than one, comma separated) and x * x is the method body that is returned from the function.
Lambda expressions can be used in a lot of cases, but they are specially useful in LINQ queries, event handling and creating expression trees.
How do you enforce thread safety in C#?
Thread safety ensures that data shared between threads are shielded from corruption due to the threads being executed in an overlapping manner. In C#, you can enforce thread safety by using various techniques:
- Locks : The lock keyword can be used to ensure that a block of code is not executed by more than one thread at the same time.
- Monitor : Monitor class provides exclusive lock similar to lock keyword.
- Mutexes and Semaphores : Mutex and Semaphore classes can be used to control access over a pool of resources.
- Thread-Safe Collections : .NET provides inherently thread-safe collections like ConcurrentBag , ConcurrentQueue , ConcurrentStack , ConcurrentDictionary , etc.
What are the differences between a struct and a class in C#?
While structs and classes in C# are quite similar, there are many key differences between them:
- Value Type vs Reference Type : The most significant difference is that struct is a value type and class is a reference type. When a struct is assigned to a new variable, a completely new copy of the value is created and changes made to one will not affect the other. However, with classes, assigning an instance of a class to a new variable doesn’t create a new object but creates a new reference to the existing object.
- Inheritance : Structs in C# cannot inherit from a class or struct, but it can implement an interface. But classes in C# can inherit from a class or implement an interface.
- Default Constructor : Structs do not contain a default (parameterless) constructor, and the compiler does not add one. Classes, however, have a default constructor if no constructors are specified.
- Nullability : Structs cannot be null as they are a value type, whereas classes being a reference type can have a null value.
What are Attribute classes and how are they beneficial?
Attribute classes in C# are a way for adding declarative information to code. It is a kind of metadata that can be added to the assemblies, types, methods, fields etc. at compile time and can be queried at runtime using reflection.
Benefits of Attribute Classes:
- Code readability and maintainability : With attribute classes, you can control behavior of methods or classes without affecting their source code.
- Metadata Access at Runtime : You can access metadata at runtime for affecting the behavior or else for diagnostics / inspection purpose.
- Controlling behavior : Custom attributes can be queried at runtime and accordingly certain behaviors can be enabled or disabled, without hard-coding them.
For example, Conditional attribute in C# is used for conditional compilation:
In this example, DebugMethod will only be called if “DEBUG” symbol is defined.
You’ve made it through the medium-hard questions, proving you have a solid C# foundation. Now, you’re ready to face the hardest questions in the list. This section contains questions on performance optimizations, architectural patterns, and interop with other languages and technologies. The hard questions are meant to stretch your limits and expose you to real-world programming challenges. Keep pushing forward, and remember that the more you practice, the more confident you’ll be in your C# programming abilities.
Can you describe just-in-time compilation (JIT) in the context of C#?
Just-In-Time (JIT) Compilation is a technique used by the .NET runtime to provide significant performance improvements by compiling the Intermediate Language (IL) bytecode to native machine code at runtime. Instead of pre-compiling the entire code to native code before executing, the JIT compiler optimizes and compiles only the required methods at runtime, greatly reducing load times and memory usage.
The main benefits of JIT compilation in the context of C# are:
- Faster application startup: Because only the necessary parts of the code are compiled, the application starts up more quickly.
- Better memory usage: Unused IL bytecode is never converted to native code, leading to lower memory usage.
- Platform-specific optimization: Native code is generated specifically for the runtime platform, allowing better optimization and performance.
The process followed by the JIT compiler in the context of C# consists of three stages:
- Loading the IL bytecodes: The CLR loads the required IL bytecode of the method to be executed.
- Compiling IL bytecodes to native code: The JIT compiler compiles the IL bytecodes to native machine code.
- Executing the native code: The generated native code is executed.
What is the difference between a normal class property and a computed class property in C#?
A normal class property is a simple property that holds a value and includes a getter and/or a setter method. These properties can be used to store and retrieve data for an object. The setter is responsible for setting the property value, and the getter is responsible for returning the property value.
A computed class property, also known as a calculated property, is a property that does not store any data but rather computes its value based on other property values within the class. Computed properties only have a getter method, which returns the calculated result, and do not have a setter method.
Normal property:
Computed property:
In this example, FullName is a computed property that returns the concatenated first name and last name.
How can you implement a custom awaitable type in C#?
To implement a custom awaitable type in C#, you need to follow these steps:
- Create a class that represents the awaitable type.
- Implement the INotifyCompletion interface in the class for notifying when the operation is complete.
- Add a method named GetAwaiter that returns an instance of the class itself.
- Implement the IsCompleted property in the class as part of the awaitable pattern.
- Add a method named OnCompleted(Action continuation) to the class which takes an action that will be executed when the operation is complete.
- Implement the GetResult method, which will return the result of the asynchronous operation.
Here’s an example of a custom awaitable type:
Why would you use the System.Reflection namespace, and how does it relate to C#?
System.Reflection is a namespace in .NET that provides functionality to obtain type information (metadata) about classes, objects, and assemblies at runtime. It allows developers to inspect and interact with the code in a dynamic manner, providing the ability to:
- Examine type information such as properties, fields, events, and methods.
- Create and manipulate instances of objects.
- Invoke methods and access fields/properties on instances.
- Discover and examine attributes applied to types and members.
- Load and interact with assemblies.
The following example demonstrates using System.Reflection to get information about a class’s type and its methods:
What are expression trees in C# and how can they be used?
Expression trees in C# are a data structure that represents code – specifically, Expressions – in a tree-like format, where each node is an object that represents a part of the expression. Expression trees enable developers to inspect, manipulate, or interpret code in a structured way at runtime. They allow operations such as modification, compilation, and execution of the expressed code.
Expression trees are mainly used in scenarios such as:
- Building dynamic LINQ queries for data manipulation.
- Dynamic code generation for performance-critical code paths.
- Serialization and deserialization of expression trees.
- Analyzing lambda expressions for parallelism or converting them to another form.
Here’s an example of creating an expression tree for a simple lambda expression:
What is the real-world use case for the ‘yield’ keyword in C#?
The yield keyword in C# is used in iterator methods to create a stateful iterator and return a sequence of values on-the-fly, without storing the entire sequence in memory. It generates a custom implementation of the IEnumerator<T> interface based on the code in the iterator method and remembers the current execution state between MoveNext() calls. This lazy evaluation of the iterator improves memory usage and performance, especially for large or infinite sequences.
Real-world use cases for the yield keyword include:
- Implementing custom collections or sequences that need to support foreach iteration.
- Generating an infinite sequence of values or a sequence that should not be stored in memory.
- Processing large data sets or streaming data incrementally without consuming a lot of memory.
Here’s an example demonstrating the use of the yield keyword for generating an infinite sequence of even numbers:
Explain the role of the ‘volatile’ keyword in C#.
The volatile keyword in C# is applied to fields to indicate that they can be accessed by multiple threads and that the field’s value may change unexpectedly, due to optimizations performed by the .NET runtime or underlying hardware.
When a field is marked as volatile , the compiler and the runtime will not reorder or cache its read and write operations, ensuring that the most recent value is always read and that writes are immediately visible to other threads. This provides a memory barrier, forcing atomic read and write operations and preventing unexpected side effects due to optimizations.
The volatile keyword should be used in scenarios where multiple threads must access a shared field, and proper synchronization is required to maintain the consistency of data.
Here’s an example demonstrating the use of a volatile variable:
In this example, the _shouldTerminate field is used to signal the worker thread when to terminate. Marking it as volatile ensures that the worker thread will see the updated value immediately.
What are weak references, and when would you use them in C#?
In C#, weak references are references to objects that aren’t strong enough to prevent these objects from being garbage collected. They allow you to maintain a reference to an object as long as the object is alive in memory, but without preventing garbage collection (GC) from reclaiming the object when memory pressure increases. With weak references, you can access the object as long as it’s still in memory, but it will not prevent the GC from collecting the object if required.
Weak references are useful in scenarios where you want to hold a reference to a large object for caching purposes but do not want to prevent the object from being garbage collected if the memory pressure increases. This allows for more efficient memory management, especially when working with large data sets or in-memory caches.
To use a weak reference in C#, you create an instance of the WeakReference or WeakReference<T> class.
Here’s an example demonstrating the usage of a weak reference:
In this example, if the GC decides to reclaim the memory used by the MyLargeObject instance, the weakReference.TryGetTarget call returns false . Otherwise, the largeObject will remain accessible through the weak reference.
Describe how to implement a custom attribute in C#.
To implement a custom attribute in C#, you follow these steps:
- Create a class that derives from the System.Attribute class.
- Add properties, fields, or methods to the class as required to store metadata.
- Apply the attribute to elements in your code (such as classes, methods, or properties) by using the attribute syntax.
Here’s an example of creating and using a custom attribute in C#:
In this example, we created a custom attribute called CustomAttribute with a description property. We applied it to the ExampleClass and its ExampleMethod() . The AttributeUsage attribute is used to limit the targets to which the custom attribute can be applied.
Explain the concept of memory-efficient array handling in C# using ArraySegment.
The ArraySegment<T> structure in C# provides a memory-efficient way of handling arrays by allowing you to work with a segment of an existing array. This is useful in scenarios where you need to process a portion of a large array and want to avoid memory overhead caused by creating new subarrays.
The ArraySegment<T> structure represents a contiguous range of elements within an array and provides properties, such as Array , Offset , and Count , to access the underlying array and the segment boundaries.
Here’s an example that demonstrates the use of ArraySegment<T> for memory-efficient array processing:
In this example, an ArraySegment<int> object is created to represent a portion of the largeArray . The PrintArraySegment method processes the array segment without creating a new subarray, thus reducing memory overhead.
What is the Roslyn Compiler Platform, and how does it relate to C#?
The Roslyn Compiler Platform is a set of open-source compilers, code analysis APIs, and code refactoring tools developed by Microsoft for C# and Visual Basic .NET (VB.NET) languages. Roslyn exposes a powerful code analysis and transformation API, allowing developers to create more advanced static code analyzers, code fixers, and refactoring tools.
Roslyn’s relation to C#:
- It provides the default C# compiler which transforms C# code into Microsoft Intermediate Language (MSIL) code.
- It offers a modern C# language service implementation for Visual Studio.
- It lets developers take advantage of the code analysis and manipulation APIs for deeper code insights and generation.
- It supports advanced features of modern C# versions like pattern matching, expression-bodied members, and async-await constructs.
Explain the concept of duck typing and how it can be achieved in C#.
Duck typing refers to a programming concept in which the type of an object is determined by its behavior (methods and properties) rather than its explicit class or inheritance hierarchy. In other words, duck typing is based on the principle: “If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.”
C# is a statically typed language, which means duck typing is not directly supported by the language. However, you can achieve a form of duck typing in C# using dynamic keyword or reflection.
Using dynamic keyword:
But it’s important to note that using dynamic may bring performance overhead, and you lose some compile-time safety. Errors will occur at runtime if the method or property doesn’t exist on the object.
What is the difference between GetHashCode and Equals methods in C#?
GetHashCode and Equals methods are members of the System.Object class, the base class for all objects in C#. They are used to compare objects for equality and serve different purposes:
- GetHashCode : This method returns an integer (hash code) representation of the object. It is primarily used by hashing-based collections like Dictionary , HashSet , etc., to optimize the object’s lookup and storage. When implementing this method, you should make sure objects considered equal have the same hash code value.
- Equals : This method checks whether two objects are equal in their content. It uses their data members to determine equality. By default, the Equals method will compare object references, but it can be overridden to provide custom comparison logic based on the actual object content (like comparing properties).
When you override the Equals method, you should also override the GetHashCode method to maintain consistency between the two methods, ensuring objects that are considered equal have the same hash code.
Explain the concept of unmanaged resources in C# and how they can be managed.
Unmanaged resources are those not directly controlled by the .NET runtime, such as file handles, network connections, database connections, and other system resources. Because the .NET runtime’s garbage collector does not manage them, developers must handle such resources explicitly to avoid resource leaks or potential application instability.
To manage unmanaged resources properly, you can:
- Implement the IDisposable interface in your class which uses unmanaged resources. The IDisposable interface provides a Dispose method for cleaning up unmanaged resources.
- Use the using statement to ensure the Dispose method is called automatically when the object goes out of scope.
In this example, the Dispose method will be called automatically when the using block is exited, ensuring proper cleanup of the unmanaged resources.
Describe parallel programming support in C# and its benefits.
Parallel programming support in C# is provided by the System.Threading , System.Threading.Tasks , and System.Collections.Concurrent namespaces. These parallel execution features allow developers to write applications that leverage modern multi-core and multi-processor hardware for better performance and responsiveness.
Key parallel programming features in C#:
- Task Parallel Library (TPL) : Provides a high-level abstraction for executing tasks concurrently, simplifying the parallelism work like managing threads, synchronization, and exception handling.
- Parallel LINQ (PLINQ) : A parallel execution version of standard LINQ, enabling developers to easily parallelize data-intensive query operations efficiently.
- Concurrent Collections : Collections like ConcurrentDictionary , ConcurrentQueue , ConcurrentBag , and ConcurrentStack provide thread-safe data structures to help manage shared state in parallel applications.
Benefits of parallel programming in C#:
- Improved performance by taking advantage of multi-core and multi-processor systems.
- Increased responsiveness by executing time-consuming tasks concurrently without blocking the UI thread.
- Simplified parallel programming through high-level abstractions provided by TPL and PLINQ.
- Better utilization of system resources leading to more efficient, scalable applications.
How do you perform compile-time code generation in C#, and what are the benefits?
Compile-time code generation in C# can be achieved using Source Generators, which are introduced in C# 9.0 and .NET 5. Source Generators are components that run during compilation and can inspect, analyze, and generate additional C# source code to be compiled alongside the original code.
A Source Generator is a separate assembly containing one or more classes implementing the ISourceGenerator interface. Visual Studio and the .NET build system will discover Source Generators with the appropriate project references and will run them during the compilation process.
Benefits of compile-time code generation:
- Improved performance: Code generation at compile-time reduces runtime overhead.
- Code reduction: Automatically generating repetitive or boilerplate code reduces the code a developer needs to write and maintain.
- Security: Generated code is verified and secured before runtime, preventing security vulnerabilities arising from runtime code generation.
- Extensibility: Source Generators enable the creation of advanced libraries and frameworks, which can further enhance and optimize code generation and manipulation.
What is stackalloc in C#, and when should it be used?
In C#, stackalloc is a keyword that allows you to allocate a block of memory on the stack.
Normally, when we work with arrays in C#, they are created on the heap. This introduces a level of overhead, as memory must be allocated and then garbage collected when the object is no longer in use. When dealing with large arrays or high performance code, the impact of this can sometimes be significant.
The stackalloc keyword bypasses this by creating the array directly on the stack. This has 3 major implications:
- Performance: Generally, allocating memory on the stack is faster than allocating it on the heap. There’s no need to worry about garbage collection, as the memory will be automatically reclaimed when the method exits. This makes it highly efficient for small arrays.
- Memory Limit: The stack is a far more limited resource compared to the heap. The exact size depends on settings and other factors, but it’s typically in the region of 1MB. This makes stackalloc unsuitable for larger arrays.
- Lifespan: Memory allocated on the heap can exist as long as your application does, whereas memory allocated on the stack only exists until the end of the current method. Any attempt to work with stack-allocated memory outside of this will lead to issues.
The typical use cases for stackalloc are high performance scenarios that involve relatively small arrays, such as graphical or mathematical operations. Be aware that improper use can easily lead to stack overflows, causing your application to crash.
Consider using stackalloc if the following cases are true:
- You have a small array (typically few hundred elements max).
- The array is local to your method and doesn’t need to be returned or passed elsewhere.
- The overhead of garbage collection has a significant impact on performance in your use case.
Here is an example of using stackalloc :
Please note that stackalloc uses unsafe code, so you must compile with the /unsafe switch.
Explain the Tuple class and its use case in C#.
The Tuple class in C# represents a fixed-size, immutable collection of heterogeneously-typed elements. It’s part of the System namespace and provides a simple way to group objects without defining custom domain-specific classes. Tuples are useful in scenarios where you need to return multiple values from a method or store or pass around data without creating a specific data structure.
Example of using Tuple:
In C# 7.0, tuples were improved with the introduction of ValueTuple . ValueTuples are struct-based (instead of class-based) tuples that allow named elements and other enhancements:
What are local functions in C# 7.0, and how can they be used?
Local functions, introduced in C# 7.0, are functions defined within the scope of another method. They enable you to declare a helper function inside the method that needs it, keeping the helper function private and avoiding clutter in the class level namespace.
Local functions offer advantages like:
- Better organization and encapsulation of functionality.
- Access to the containing method’s variables, allowing them to share state easily.
- Limited accessibility, as local functions are not visible outside their containing method.
Example of a local function:
In this example, the Add local function is only visible within the CalculateSum method and can access the local variables (e.g., sum ) of the containing method.
Explain the concept of marshaling in .NET and its application in C#.
Marshaling is the process of converting the types, objects, and data structures of one runtime environment to another, especially in the context of communication between managed (.NET) code and unmanaged (native) code. Marshaling is widely used in .NET when you want to interact with components developed in other programming languages, operating systems, or hardware and software platforms (e.g., COM, Win32 API, or other third-party libraries).
In C#, marshaling is facilitated by the System.Runtime.InteropServices namespace, providing required attributes, methods, and structures to:
- Define the layout of structures and unions in memory.
- Map managed types to unmanaged types.
- Specify calling conventions for unmanaged functions.
- Allocate and deallocate unmanaged memory.
Example of using marshaling in C#:
In this example, we import the MessageBox function from the user32.dll native library using the DllImport attribute. This enables the managed C# code to call the unmanaged Win32 MessageBox function. The marshaling process will handle the conversion of string values and other necessary data types when calling the unmanaged function.
You’ve made it! Congratulations on completing this comprehensive set of C# interview questions and answers. Through this journey, you’ve gained valuable insights into C#, from the basics to the most advanced programming concepts. By mastering these questions, you’ve built the knowledge and confidence needed to excel in your next C# interview.
Remember that the key to success lies in continuous learning and staying updated on the latest developments in C# and the .NET ecosystem. Keep sharpening your skills and networking with fellow developers to stay informed and be more competitive in the job market. We wish you the best of luck in your upcoming interviews, and we’re confident that you’ll shine as a C# developer!
Sign up For Our Newsletter
Weekly .NET Capsules: Short reads for busy devs.
You May Also Like
Mastering StringValues in ASP.NET Core
Hey there, fellow C# enthusiasts! Today, we’re diving into the world of StringValues in ASP.NET Core—a nifty feature designed to...
The Ultimate Guide to Converting a Stream to a File in C#
Ever found yourself tangled in the web of streams and files while working on your C# projects? Don't worry; you're not alone....
What’s New in C# 13? Everything You Need To Know
In this article, we'll cover all the shiny new upgrades that C# 13 brings to the table. From revamped params collections to...
- N Latest .NET tips and tricks
- N Quick 5-minute reads
- N Practical code snippets
- TECHNOLOGIES
- An Interview Question
Basic C# Programming Problem and Solutions: Part 1
- Ehtesham Mehmood
- Sep 15, 2022
- Other Artcile
This article is for the beginners who have just begun programming in the C# language with solutions for all the basic problems of the C# programming.
Part 2 - Basic C# Programming Problem and Solutions Part 3 - Basic C# Programming Problem and Solutions
Today I am writing this article for beginners who have just begun programming in the C# language. I have solved all the basic problems of C# programming and also I have included some sections of OOP in this article that I will show you in the next part of this article series.
I have created three articles for this article series, each part contains 14 problems. Anyone that reads this article series with full concentration and that practices on their own, I am sure he/she will become very familiar with the basics of C# programming. I have provided every problem in the form of a question and a solution. Let's start.
Write a program that converts 1 lower case letter ("a" - "z") to its corresponding upper case letter ("A" - "Z"). For example if the user enters "c" then the program will show "C" on the screen.
Hint: You need to check the ASCII value in your program.
Write a program that takes three points (x1, y1), (x2, y2) and (x3, y3) from the user and the program will check wheteher or not all the three points fall on one straight line.
Write a program that takes coordinates (x, y) of a center of a circle and its radius from the user, the program will determine whether a point lies inside the circle, on the circle or outside the circle.
Write a program that takes a character from the user and determines whether the character entered is a capital letter, a small case letter, a digit or a special symbol. The following table shows the range of ASCII values for various characters.
Write a program using a switch statement that takes one value from the user and asks about the type of conversion and then performs a conversion depending on the type of conversion. If user enters:
I -> convert from inches to centimeters. G -> convert from gallons to liters. M -> convert from mile to kilometer. P -> convert from pound to kilogram.
If the user enters any other character then show a proper message.
In a company, worker efficiency is determined on the basis of the time required for a worker to complete a specific job. If the time taken by the worker is between 2 - 3 hours, then the worker is said to be highly efficient. If the time required by the worker is 3 - 4 hours, then the worker is ordered to increase their speed. If the time taken is 4 - 5 hours then the worker is given training to improve his speed and if the time taken by the worker is more than 5 hours then the worker must leave the company. If the time taken by the worker is input through the keyboard then find the efficiency of the worker.
Write a program using conditional operators to determine whether a year entered through the keyboard is a leap year or not.
Write a program using a switch statement that takes one character value from the user and checks whether the entered value is an arithmetic operator, logical operator, conditional operator, relational operator or something else.
Write a program that prints an identity matrix using a for loop, in other words takes a value n from the user and shows the identity table of size n * n.
Write a program using a for loop that prints the following series.
1 2 4 8 16 21 64 128 …nth iteration.
Write a program using a for loop that prints the following output (you need to find a pattern to print letters in this order):
Write a program using a loop that prints the following output.
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 . . . nth iteration.
Write a program to print all the ASCII values and their equivalent characters using a while loop. The ASCII values vary from 0 to 255.
Write a program to print all the ASCII values and their equivalent characters using a do-while loop. The ASCII values vary from 10 to 255.
- ASCII value
- C# programming problems
- conversion in C#
Pattern Matching in C#
- ▼C# Sharp Exercises
- Introduction
- Basic Algorithm
- Exception Handling
- Conditional Statements
- Searching and Sorting
- Regular Expression
- File Handling
- ..More to come..
C# Sharp Array : Exercises, Practice, Solution
C# sharp array [41 exercises with solution].
[ An editor is available at the bottom of the page to write and execute the scripts. Go to the editor ]
1. Write a C# Sharp program that stores elements in an array and prints them. Test Data: Input 10 elements in the array: element - 0 : 1 element - 1 : 1 element - 2 : 2 ....... Expected Output : Elements in array are: 1 1 2 3 4 5 6 7 8 9 Click me to see the solution
2. Write a C# Sharp program to read n values in an array and display them in reverse order. Test Data : Input the number of elements to store in the array :3 Input 3 number of elements in the array : element - 0 : 2 element - 1 : 5 element - 2 : 7 Expected Output : The values store into the array are: 2 5 7 The values store into the array in reverse are : 7 5 2 Click me to see the solution
3. Write a program in C# Sharp to find the sum of all array elements. Test Data : Input the number of elements to be stored in the array :3 Input 3 elements in the array : element - 0 : 2 element - 1 : 5 element - 2 : 8 Expected Output : Sum of all elements stored in the array is : 15 Click me to see the solution
4. Write a C# Sharp program to copy the elements of one array into another array. Test Data : Input the number of elements to be stored in the array :3 Input 3 elements in the array : element - 0 : 15 element - 1 : 10 element - 2 : 12 Expected Output : The elements stored in the first array are : 15 10 12 The elements copied into the second array are : 15 10 12 Click me to see the solution
5. Write a C# Sharp program in to count duplicate elements in an array. Test Data : Input the number of elements to be stored in the array :3 Input 3 elements in the array : element - 0 : 5 element - 1 : 1 element - 2 : 1 Expected Output : Total number of duplicate elements found in the array is : 1 Click me to see the solution
6. Write a program in C# Sharp to print all unique elements in an array. Test Data : Input the number of elements to be stored in the array :3 Input 3 elements in the array : element - 0 : 1 element - 1 : 5 element - 2 : 1 Expected Output : The unique elements found in the array are : 5 Click me to see the solution
7. Write a C# Sharp program to merge two arrays of the same size sorted in ascending order. Test Data : Input the number of elements to be stored in the first array :3 Input 3 elements in the array : element - 0 : 1 element - 1 : 2 element - 2 : 3 Input the number of elements to be stored in the second array :3 Input 3 elements in the array: element - 0 : 1 element - 1 : 2 element - 2 : 3 Expected Output : The merged array in ascending order is : 1 1 2 2 3 3 Click me to see the solution
8. Write a C# Sharp program to count the frequency of each element in an array. Test Data : Input the number of elements to be stored in the array :3 Input 3 elements in the array : element - 0 : 25 element - 1 : 12 element - 2 : 43 Expected Output : Frequency of all elements of array : 25 occurs 1 times 12 occurs 1 times 43 occurs 1 times Click me to see the solution
9. Write a C# Sharp program to find the maximum and minimum elements in an array. Test Data : Input the number of elements to be stored in the array :3 Input 3 elements in the array : element - 0 : 45 element - 1 : 25 element - 2 : 21 Expected Output : Maximum element is : 45 Minimum element is : 21 Click me to see the solution
10. Write a program in C# Sharp to separate odd and even integers into separate arrays. Test Data : Input the number of elements to be stored in the array :5 Input 5 elements in the array : element - 0 : 25 element - 1 : 47 element - 2 : 42 element - 3 : 56 element - 4 : 32 Expected Output : The Even elements are: 42 56 32 The Odd elements are : 25 47 Click me to see the solution
11. Write a C# Sharp program to sort elements of an array in ascending order. Test Data : Input the size of array : 5 Input 5 elements in the array : element - 0 : 2 element - 1 : 7 element - 2 : 4 element - 3 : 5 element - 4 : 9 Expected Output : Elements of array in sorted ascending order: 2 4 5 7 9 Click me to see the solution
12. Write a C# Sharp program to sort array elements in descending order. Test Data : Input the size of array : 3 Input 3 elements in the array : element - 0 : 5 element - 1 : 9 element - 2 : 1 Expected Output : Elements of the array in sorted descending order: 9 5 1 Click me to see the solution
13. Write a C# Sharp program to insert an additional value into an array (sorted list). Test Data : Input the size of array : 3 Input 3 elements in the array in ascending order: element - 0 : 5 element - 1 : 7 element - 2 : 9 Input the value to be inserted : 8 Expected Output : The exist array list is : 5 7 9 After Insert the list is : 5 7 8 9 Click me to see the solution
14. Write a C# Sharp program to insert another value in the array (unsorted list). Test Data : Input the size of array : 4 Input 4 elements in the array in ascending order: element - 0 : 1 element - 1 : 8 element - 2 : 7 element - 3 : 10 Input the value to be inserted : 5 Input the Position, where the value to be inserted :2 Expected Output : The current list of the array : 1 8 7 10 After Insert the element the new list is : 1 5 8 7 10 Click me to see the solution
15. Write a C# Sharp program to delete an element at the desired position from an array. Test Data : Input the size of array : 5 Input 5 elements in the array in ascending order: element - 0 : 1 element - 1 : 2 element - 2 : 3 element - 3 : 4 element - 4 : 5 Input the position where to delete: 3 Expected Output : The new list is : 1 2 4 5 Click me to see the solution
16. Write a C# Sharp program to find the second largest element in an array. Test Data : Input the size of array : 5 Input 5 elements in the array : element - 0 : 2 element - 1 : 9 element - 2 : 1 element - 3 : 4 element - 4 : 6 Expected Output : The Second largest element in the array is: 6 Click me to see the solution
17. Write a C# Sharp program to find the second smallest element in an array. Test Data : Input the size of array : 5 Input 5 elements in the array (value must be <9999) : element - 0 : 0 element - 1 : 9 element - 2 : 4 element - 3 : 6 element - 4 : 5 Expected Output : The Second smallest element in the array is : 4 Click me to see the solution
18. Write a program in C# Sharp for a 2D array of size 3x3 and print the matrix. Test Data : Input elements in the matrix : element - [0],[0] : 1 element - [0],[1] : 2 element - [0],[2] : 3 element - [1],[0] : 4 element - [1],[1] : 5 element - [1],[2] : 6 element - [2],[0] : 7 element - [2],[1] : 8 element - [2],[2] : 9 Expected Output : The matrix is : 1 2 3 4 5 6 7 8 9 Click me to see the solution
19. Write a C# Sharp program for adding two matrices of the same size. Test Data : Input the size of the square matrix (less than 5): 2 Input elements in the first matrix : element - [0],[0] : 1 element - [0],[1] : 2 element - [1],[0] : 3 element - [1],[1] : 4 Input elements in the second matrix : element - [0],[0] : 5 element - [0],[1] : 6 element - [1],[0] : 7 element - [1],[1] : 8 Expected Output : The First matrix is: 1 2 3 4 The Second matrix is : 5 6 7 8 The Addition of two matrix is : 6 8 10 12 Click me to see the solution
20. Write a C# Sharp program for the subtraction of two matrixes. Test Data : Input the size of the square matrix (less than 5): 2 Input elements in the first matrix : element - [0],[0] : 5 element - [0],[1] : 6 element - [1],[0] : 7 element - [1],[1] : 8 Input elements in the second matrix : element - [0],[0] : 1 element - [0],[1] : 2 element - [1],[0] : 3 element - [1],[1] : 4 Expected Output : The First matrix is : 5 6 7 8 The Second matrix is : 1 2 3 4 The Subtraction of two matrix is : 4 4 4 4 Click me to see the solution
21. Write a C# Sharp program for multiplication of two square matrices. Test Data : Input the rows and columns of first matrix : 2 2 Input the rows and columns of second matrix : 2 2 Input elements in the first matrix : element - [0],[0] : 1 element - [0],[1] : 2 element - [1],[0] : 3 element - [1],[1] : 4 Input elements in the second matrix : element - [0],[0] : 5 element - [0],[1] : 6 element - [1],[0] : 7 element - [1],[1] : 8 Expected Output : The First matrix is : 1 2 3 4 The Second matrix is : 5 6 7 8 The multiplication of two matrix is : 19 22 43 50 Click me to see the solution
22. Write a C# Sharp program to find the transpose of a given matrix. Test Data : Input the rows and columns of the matrix : 2 2 Input elements in the first matrix : element - [0],[0] : 1 element - [0],[1] : 2 element - [1],[0] : 3 element - [1],[1] : 4 Expected Output : The matrix is : 1 2 3 4 The Transpose of a matrix is : 1 3 2 4 Click me to see the solution
23. Write a C# Sharp program to find the sum of the right diagonals of a matrix. Test Data : Input the size of the square matrix : 2 Input elements in the first matrix : element - [0],[0] : 1 element - [0],[1] : 2 element - [1],[0] : 3 element - [1],[1] : 4 Expected Output : The matrix is : 1 2 3 4 Addition of the right Diagonal elements is :5 Elements in array are: Click me to see the solution
24. Write a C# Sharp program to find the sum of the left diagonals of a matrix. Test Data: Input the size of the square matrix : 2 Input elements in the first matrix : element - [0],[0] : 1 element - [0],[1] : 2 element - [1],[0] : 3 element - [1],[1] : 4 Expected Output : The matrix is : 1 2 3 4 Addition of the left Diagonal elements is :5 Click me to see the solution
25. Write a C# Sharp program to find the sum of rows and columns in a matrix. Test Data : Input the size of the square matrix: 2 Input elements in the first matrix: element - [0],[0] : 5 element - [0],[1] : 6 element - [1],[0] : 7 element - [1],[1] : 8 Expected Output : The First matrix is : The matrix is : 5 6 7 8 The sum or rows and columns of the matrix is : 5 6 11 7 8 15 12 14 Click me to see the solution
26. Write a program in C# Sharp to print or display the lower triangular of a given matrix. Test Data : Input the size of the square matrix : 3 Input elements in the first matrix : element - [0],[0] : 1 element - [0],[1] : 2 element - [0],[2] : 3 element - [1],[0] : 4 element - [1],[1] : 5 element - [1],[2] : 6 element - [2],[0] : 7 element - [2],[1] : 8 element - [2],[2] : 9 Expected Output : The matrix is : 1 2 3 4 5 6 7 8 9 Setting zero in lower triangular matrix 1 2 3 0 5 6 0 0 9 Click me to see the solution
27. Write a C# Sharp program to print or display an upper triangular matrix. Test Data : Input the size of the square matrix : 3 Input elements in the first matrix : element - [0],[0] : 1 element - [0],[1] : 2 element - [0],[2] : 3 element - [1],[0] : 4 element - [1],[1] : 5 element - [1],[2] : 6 element - [2],[0] : 7 element - [2],[1] : 8 element - [2],[2] : 9 Expected Output : The matrix is : 1 2 3 4 5 6 7 8 9 Setting zero in upper triangular matrix 1 0 0 4 5 0 7 8 9 Click me to see the solution
28. Write a C# Sharp program to calculate the determinant of a 3 x 3 matrix. Test Data : Input elements in the first matrix : element - [0],[0] : 1 element - [0],[1] : 0 element - [0],[2] : -1 element - [1],[0] : 0 element - [1],[1] : 0 element - [1],[2] : 1 element - [2],[0] : -1 element - [2],[1] : -1 element - [2],[2] : 0 Expected Output : The matrix is : 1 0 -1 0 0 1 -1 -1 0 The Determinant of the matrix is: 1 Click me to see the solution
29. Write a C# Sharp program to accept a matrix and determine whether it is a sparse matrix. Test Data : Input the number of rows of the matrix : 2 Input the number of columns of the matrix : 2 Input elements in the first matrix : element - [0],[0] : 0 element - [0],[1] : 0 element - [1],[0] : 1 element - [1],[1] : 0 Expected Output : The given matrix is sparse matrix. There are 3 number of zeros in the matrix Click me to see the solution
30. Write a C# Sharp program to accept two matrices and check equality. Test Data : Input Rows and Columns of the 1st matrix :2 2 Input Rows and Columns of the 2nd matrix :2 2 Input elements in the first matrix : element - [0],[0] : 1 element - [0],[1] : 2 element - [1],[0] : 3 element - [1],[1] : 4 Input elements in the second matrix : element - [0],[0] : 1 element - [0],[1] : 2 element - [1],[0] : 3 element - [1],[1] : 4 Expected Output : The first matrix is : 1 2 3 4 The second matrix is : 1 2 3 4 The Matrices can be compared : Two matrices are equal. Click me to see the solution
31. Write a C# Sharp program to Check whether a Given Matrix is an Identity Matrix. Test Data : Input the orders(2x2, 3x3, ...) of squere matrix : 2 Input elements in the matrix : element - [0],[0] : 1 element - [0],[1] : 0 element - [1],[0] : 0 element - [1],[1] : 1 Expected Output : The matrix is : 1 0 0 1 The matrix is an Identity Matrix. Click me to see the solution
32. Write a C# Sharp program to get only odd values from a given integer array. Test Data : Only the odd values of the said array: 1 3 5 3 Only the odd values of the said array: Click me to see the solution
33. Write a C# Sharp program that removes all duplicate elements from a given array and returns an updated array. Test Data : Original array elements: 25 Anna False 25 4/15/2021 12:10:51 PM 112.22 Anna False After removing duplicate elements from the said array: 25 Anna False 4/15/2021 12:10:51 PM 112.22 Click me to see the solution
34. Write a C# Sharp program to find the missing number in a given array of numbers between 10 and 20. Test Data : Original array elements: 10 11 12 13 14 15 16 17 18 19 20 Missing number in the said array (10-20): 0 Original array elements: 11 12 13 14 15 16 17 18 19 20 Missing number in the said array (10-20): 10 Original array elements: 10 11 12 13 14 16 17 18 19 20 Missing number in the said array (10-20): 15 Original array elements: 10 11 12 13 14 15 16 17 18 19 Missing number in the said array (10-20): 20 Click me to see the solution
35. Write a C# Sharp program to calculate the sum of the two lowest negative numbers in a given array of integers. An integer (from the Latin integer meaning "whole") is colloquially defined as a number that can be written without a fractional component. For example, 21, 4, 0, and −2048 are integers, Test Data : Original array elements: -10 -11 -12 -13 -14 15 16 17 18 19 20 Sum of two lowest negative numbers of the said array of integers: -27 Original array elements: -1 -2 -4 0 3 4 5 9 Sum of two lowest negative numbers of the said array of integers: -6 Click me to see the solution
- 1, 2, 3, 4, 5
- -3, −2, −1, 0, 1, 2, 3, 4
- 6, 7, 8, 9, 10, 11, 12, 13
37. Write a C# Sharp program that calculates the smallest gap between numbers in an array of integers. Sample Data: ({ 7, 5, 8, 9, 11, 23, 18 }) -> 1 ({ 200, 300, 250, 151, 162 }) -> 11 Click me to see the solution
38. Write a C# Sharp program that takes an array of numbers and a digit. Check whether the digit is present in this array of numbers. Sample Data: ({7, 5, 85, 9, 11, 23, 18}, "1") - > "Present" ({7, 5, 85, 9, 11, 23, 18}, "1") - > "Present" ({7, 5, 85, 9, 11, 23, 18}, "1") - > "Not present..!" Click me to see the solution
39. Write a C# Sharp program that calculates the sum of all prime numbers in an array of numbers. Sample Data: ({ 7, 5, 85, 9, 11, 23, 18 }) -> 46 ({ 200, 300, 250, 151, 162 }) -> 151 Click me to see the solution
40. Write a C# Sharp program that takes an array of integers and finds the smallest positive integer that is not present in that array. Sample Data: ({ 1,2,3,5,6,7}) -> 4 ({-1, -2, 0, 1, 3, 4, 5, 6}) -> 2 Click me to see the solution
41. Write a C# Sharp program to find two numbers in an array of integers whose product is equal to a given number. Sample Data: ({10, 18, 39, 75, 100}, 180) -> {10, 18} ({10, 18, 39, 75, 100}, 200) -> {} ({10, 18, 39, 75, 100}, 702) -> {18, 39} Click me to see the solution
C# Sharp Code Editor:
More to Come !
Follow us on Facebook and Twitter for latest update.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/csharp-exercises/array/index.php
- Weekly Trends and Language Statistics
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
- OverflowAI GenAI features for Teams
- OverflowAPI Train & fine-tune LLMs
- Labs The future of collective knowledge sharing
- About the company Visit the blog
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
What are good C# Problems to solve for practice? [closed]
I am still learning a lot of C#. And would like to hone my skills for future interviews. What are some simple C# problems to solve? The last interview I did had a pretty simple problem in it that I kind of struggled with, don't want that to happen again.
- Are there any particular skills you wish to buff up? :) Writing a game is always a good learning experience. – Ashley Grenon Commented Aug 4, 2010 at 17:41
- What kind of problem made you choke? Was it something arbitrary/nasty trick question, or something that would likely be encountered on the job? – FrustratedWithFormsDesigner Commented Aug 4, 2010 at 17:42
- It was actually something very simple. Which made me realize how little I know. They wanted a method where when you input d it printed out a multiplication table of column header times row headers up to D. for example if d=2, it would do a table with 1 times 1, 1 times 2, 2 times 1 and 2 times 2. I eventually figured it out (albeit with some help from the interviewers). And when I got home I realized how simple it is and how easily I could have figured it out had I not been nervous. I want to do enough problems like these so I would be more confident the next time around. – Khades Commented Aug 4, 2010 at 18:12
4 Answers 4
I realize this was 2 months ago, so you've probably become a C# master by now :)
But I've found the project euler problems to be very nice. They are all math problems, and they aren't language specific. So they won't help you with C# per se, but they will help wrap your mind around different ways to solve problems.
Just as an example, the first question is:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
I won't give away the answer, but it's pretty easy to figure out with code if you think about it. Hope this helps and good luck.
- At first it looked kind of complicated, but once I started working on it, it was very easy. Thank you :) – Khades Commented Nov 23, 2010 at 20:10
- The Project Euler website looks like it's no longer available... – Dan Esparza Commented Apr 26, 2012 at 20:47
- @DanEsparza that is not correct, I've been using it all month. projecteuler.net – jb. Commented Apr 26, 2012 at 23:55
I suggest checking out past problems from the ACM ICPC competitions. ACM ICPC is the granddaddy of all programming competitions. But, if you like solve a problem a day you'll definitely hone your skills :)
here's the official website: http://cm.baylor.edu/welcome.icpc
And if you don't feel like navigating here's a quick link to this year's finals problem set: http://cm.baylor.edu/ICPCWiki/attach/Problem%20Resources/2010WorldFinalProblemSet.pdf
Great exercise for the brain. :)
- oh, plus you should try googling common interview questions and solve those too! :) – Ashley Grenon Commented Aug 4, 2010 at 18:31
- The problem with those are that they're too advanced for me. I was thinking of starting out with much more simpler problems to begin with. I am already reading other interview questions here on SO and on Google. But haven't found a good source of problems I can solve :(. – Khades Commented Aug 4, 2010 at 18:46
- oh :( hmmm...well if you have any programming textbooks around, they usually have good problems to try in the back of chapters. That's a good start. :) I'll try to think of one that I own that's good enough to recommend. :) – Ashley Grenon Commented Aug 4, 2010 at 18:52
- Well here's a book you should look into: Programming Interviews Exposed: amazon.com/exec/obidos/ASIN/047012167X/books24x7com I've only skimmed through it, but it seems to be a good prep book. – Ashley Grenon Commented Aug 4, 2010 at 18:59
Here are some C # interview questions
UVa Online Judge has some nice problems but no submission for C# solutions although C/C++ is supported, Sphere Online Judge has some as well but those are mathematically oriented, although UVa is one of the biggest collections of problems, I guess you can write it in C# and test it against some of your own input or translate to C++ or Java and try it that way.
Not the answer you're looking for? Browse other questions tagged c# or ask your own question .
- The Overflow Blog
- Masked self-attention: How LLMs learn relationships between tokens
- Deedy Das: from coding at Meta, to search at Google, to investing with Anthropic
- Featured on Meta
- User activation: Learnings and opportunities
- Preventing unauthorized automated access to the network
- Feedback Requested: How do you use the tagged questions page?
Hot Network Questions
- Lilypond Orchestral score: how to show duplicated tempo marking for violins?
- How to format units inside math environment?
- 2 NICs, PC is trying to use wrong one
- If a 'fire temple' was built in a gigantic city, with many huge perpetual flames inside, how could they keep smoke from bothering non-worshippers?
- DTM and DSM from the same LAZ file - extent do not match
- In the Silmarillion or the Appendices to ROTK, do the Dwarves of Khazad-dûm know about the Balrog below prior to Durin receiving the ring?
- Is there no diagonal relationship for carbon and phosphorus?
- \ContinuedFloat with threeparttable not working
- Can I redeem myself with a better research paper if my thesis sucks?
- Will a Palm tree in Mars be approximately 2.5 times taller than the same tree on Earth?
- Book where a parent recounts an anecdote about a painting of a Russian sled pursued by wolves
- Evil machine/Alien entity kills man but his consciousness/brain remains alive within it, and he spends eons reading its mind to defeat it and escape
- World's smallest Sudoku!
- If Voyager is still an active NASA spacecraft, does it have a flight director? Is that a part time job?
- Why was Kanji used to write certain words in "Signal"?
- BTD6 Kinetic Chaos (9/26/24 Odyssey)
- Geometry nodes mapping 0-1 UV to every mesh face
- Order of function transformations
- Is mathematical Platonism possible without mind-body dualism?
- This puzzle is delicious
- What are major reasons why Republicans support the death penalty?
- Why are METAR issued at 53 minutes of the hour?
- Informal "chats" with potential grad school advisors
- Switch or switches in the context of trains in American English?
COMMENTS
There is a single operator in C#, capable of providing the remainder of a division operation. Two numbers are passed as parameters. The first parameter divided by the second parameter will have a remainder, possibly zero. Return that value. Examples Remainder(1, 3) 1 Remainder(3, 4) 3 Remainder(-9, 45) -9 Remainder …
The best way we learn anything is by practice and exercise questions. We have started this section for those (beginner to intermediate) who are familiar with C# Sharp programming. Hope, these exercises help you to improve your C# Sharp programming coding skills. Currently, following sections are available, we are working hard to add more ...
Being powerful, flexible, and well-supported has meant C# has quickly become one of the most popular programming languages available. Today, it is the 4th most popular programming language, with approximately 31% of all developers using it regularly. Follow along and check 34 most common C# Coding Interview Questions (SOLVED) for mid and experienced developers before your next tech interview.
6 kyu. Count characters in your string. 92,033 riston. Strings. Fundamentals. Loading... Practice C# coding with code challenges designed to engage your programming skills. Solve coding problems and pick up new techniques from your fellow peers.
In a typical C# interview, expect a blend of conceptual, problem-solving, and coding questions. The conceptual questions test your theoretical knowledge and understanding of C# and its surrounding ecosystem (.NET, ASP.NET, etc.). For instance, you might be asked to explain the difference between a struct and a class in C#, or describe how ...
Console.WriteLine("Stack Empty"); return -1; else. numElements--; return stackArr[numElements]; public int getSize() return numElements; The majority of questions in every coding interview will test data structures. Today, we'll help you prepare with 45 of the top C# data structure questions.
The preferred answer would be of the form: circle.Calculate(r => 2 * Math.PI * r); Since we don't have access to the private radius field of the object, we tell the object itself to calculate the circumference, by passing it the calculation function inline.. A lot of C# programmers shy away from (or don't understand) function-valued parameters.
C#. Developed around 2000 by Microsoft as part of its .NET initiative, C# is a general-purpose, object-oriented programming language designed for Common Language Infrastructure (CLI), and widely recognized for its structured, strong-typing and lexical scoping abilities. This competency area includes understanding the structure of C# programs ...
Develop fluency in 74 programming languages with our unique blend of learning, practice and mentoring. Exercism is fun, effective and 100% free, forever. Explore the 167 C# exercises on Exercism.
The size of an array is fixed. An arraylist is similar, except it doesn't have a fixed size. 12. Are you able to use a "this" command within the context of a static method? No, you cannot use a "this" command in a static method because you can only use static methods and variables in a static method. 13.
Practice C#. Learn the basics of C# programming with ease in this interactive and practical course. Master the basic syntax of the language and build a solid foundation for developing Windows applications. 4.3 (136 reviews) 33 Problems Beginner level. 3.9k Learners. Start My Journey. Please login to see the progress.
C# Program to Find Factorial of a Number. In this C# program, we will take input from the user and Find the Factorial of a Number using 3 different ways using 1) For loop 2) Recursion 3) While loop. The factorial of a positive number n is given by n!. 5!=5*4*3*2*1=120.
We have gathered a variety of C# exercises (with answers) for each C# Chapter. Try to solve an exercise by editing some code, or show the answer to see what you've done wrong. Count Your Score. You will get 1 point for each correct answer. Your score and total score will always be displayed.
Scenario-based questions that present candidates with an example scenario to test their coding and problem-solving on the spot. Why include C# tricky questions in interviews? Tricky C# interview questions are the key to evaluating a candidate's skills, suitability for the position, and overall potential contribution to your development team.
None of these are particularly difficult questions for a proficient C# programmer to answer, and they should give you a good idea of your applicants particular strengths. ... I'm with the guys that are looking for problem-solving abilities rather than the sort of thing you can look up and memorise from '101 top .NET interview Qs and As".
C# is the most popular general-purpose programming language and was developed by Microsoft in 2000, renowned for its robustness, flexibility, and extensive application range.It is simple and has an object-oriented programming concept that can be used for creating different types of applications.. Here, we will provide 50+ C# Interview Questions and Answers which are suitable for both freshers ...
Read Searching Algorithms In C# to learn more. The array to be searched is reduced by half in every iteration. Hence time complexity of the Binary search is O(LogN). Summary. I hope you like this collection of interview questions. If you have any suggestions or want me to include any new questions, please let me know through the contact page.
Welcome to the ultimate guide to C# Interview Questions and Answers! Whether you're a fresh graduate or a seasoned developer, this comprehensive guide is ... Real-world problem-solving using C#; So, sharpen your skills and be prepared for your next C# interview by diving deep into these Top 100 C# Interview Questions and Answers! Index
Boost your coding interview skills and confidence by practicing real interview questions with LeetCode. Our platform offers a range of essential problems for practice, as well as the latest questions being asked by top-tier companies.
Problem 5. Write a program using a switch statement that takes one value from the user and asks about the type of conversion and then performs a conversion depending on the type of conversion. If user enters: I -> convert from inches to centimeters. G -> convert from gallons to liters. M -> convert from mile to kilometer.
3. Check DotNetPerls they have a good selection of problems and solutions focusing in C# programming. I also like the C# Brainteasers from Jon Skeet, good code snippets to read and learn more about the language, some have very interesting and surprising results... answered Nov 10, 2008 at 6:01. Christian C. Salvadó.
Write a C# Sharp program to get only odd values from a given integer array. Test Data : Only the odd values of the said array: 1 3 5 3 Only the odd values of the said array: Click me to see the solution. 33. Write a C# Sharp program that removes all duplicate elements from a given array and returns an updated array. Test Data : Original array ...
So they won't help you with C# per se, but they will help wrap your mind around different ways to solve problems. Just as an example, the first question is: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.