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.
this be used within a Static method?We can't use this in static method because keyword this returns a reference to the current instance of the class containing it.
Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class and call with the name of a class not by instance so we can't use this keyword in the body of static Methods, but in case of Extension Methods we can use it as the functions parameters.
Suppose we have two stacks and no other temporary variable. Is to possible to "construct" a queue data structure using only the two stacks?
Keep two stacks, let's call them inbox and outbox.
Enqueue:
inboxDequeue:
outbox is empty, refill it by popping each element from inbox and pushing it onto outboxoutboxIn the worst case scenario when outbox stack is empty, the algorithm pops n elements from inbox stack and pushes n elements to outbox, where n is the queue size. This gives 2*n operations, which is O(n). But when outbox stack is not empty the algorithm has O(1) time complexity that gives amortised O(1).
public class Queue<T> where T : class
{
private Stack<T> input = new Stack<T>();
private Stack<T> output = new Stack<T>();
public void Enqueue(T t)
{
input.Push(t);
}
public T Dequeue()
{
if (output.Count == 0)
{
while (input.Count != 0)
{
output.Push(input.Pop());
}
}
return output.Pop();
}
}The different types of class in C# are:
Struct and a Class in C#?Class and struct both are the user defined data type but have some major difference:
Struct
System.Value Type.Class
System.Object Type.virtual keyword used in code?The virtual keyword is used while defining a class to specify that the methods and the properties of that class can be overridden in derived classes.
finally block in C#?Finally block will be executed irrespective of exception. So while executing the code in try block when exception is occurred, control is returned to catch block and at last finally block will be executed. So closing connection to database / releasing the file handlers can be kept in finally block.
The idea behind linear search is to compare the search item with the elements in the list one by one (using a loop) and stop as soon as we get the first copy of the search element in the list. Now considering the worst case in which the search element does not exist in the list of size N then the Simple Linear Search will take a total of 2N+1 comparisons (N comparisons against every element in the search list and N+1 comparisons to test against the end of the loop condition).
for (int i = 0; i < length; i++) { // N+1 comparisons
if (array[i] == elementToSearch) { // N comparisons
return i; // I found the position of the element requested
}
}The idea of Sentinel Linear Search is to reduce the number of comparisons required to find an element in a list. Here we replace the last element of the list with the search element itself and run a while loop to see if there exists any copy of the search element in the list and quit the loop as soon as we find the search element. This will reduce one comparison in each iteration.
while(a[i] != element) // N+2 comparisons worst case
i++;In that case the while loop makes only one comparison in each iteration and it is sure that it will terminate since the last element of the list is the search element itself. So in the worst case ( if the search element does not exists in the list ) then there will be at most N+2 comparisons (N comparisons in the while loop and 2 comparisons in the if condition). Which is better than (2N+1) comparisons as found in Simple Linear Search.
Take note that both the algorithms (Simple Linear and Sentinel) have time complexity of O(n).
/// <summary>
/// Gets the index of first founded item
/// </summary>
/// <typeparam name="T">The type of array</typeparam>
/// <param name="array">Input array</param>
/// <param name="value">Value of searching item</param>
/// <param name="equalityComparer">Custom comparer</param>
/// <returns>The index of founded item or -1 if not found</returns>
public static int BetterLinearSearch < T > (this IEnumerable < T > array, T value, IEqualityComparer < T > equalityComparer = null) {
if (equalityComparer == null) equalityComparer = new DefaultEqualityComparer < T > ();
int arrayLength = array.Count();
T lastItem = array.Last();
array = array.SetElement(arrayLength - 1, value);
int index = 0;
while (!equalityComparer.Equals(array.ElementAt(index), value))
index++;
if (index < arrayLength - 1) return index;
if (equalityComparer.Equals(lastItem, value)) return arrayLength - 1;
return - 1;
}static long TotalAllEvenNumbers(int[] intArray) {
return intArray.Where(i => i % 2 == 0).Sum(i => (long)i);
}or
static long TotalAllEvenNumbers(int[] intArray) {
return (from i in intArray where i % 2 == 0 select (long)i).Sum();
}You can prevent a class from overriding in C# by using the sealed keyword.
Explain what is space complexity of that solution?
Two words are anagrams of each other if they contain the same number of characters and the same characters. There are two solutions to mention:
O(n log n).O(n)O(n)The major space cost in your code is the hashmap which may contain a frequency counter for each lower case letter from a to z. So in this case, the space complexity is supposed to be constant O(26).
To make it more general, the space complexity of this problem is related to the size of alphabet for your input string. If the input string only contains ASCII characters, then for the worst case you will have O(256) as your space cost. If the alphabet grows to the UNICODE set, then the space complexity will be much worse in the worst scenario.
So in general its O(size of alphabet).
public static bool AreAnagrams(string s1, string s2)
{
if (s1 == null) throw new ArgumentNullException("s1");
if (s2 == null) throw new ArgumentNullException("s2");
var chars = new Dictionary<char, int>();
foreach (char c in s1)
{
if (!chars.ContainsKey(c))
chars[c] = 0;
chars[c]++;
}
foreach (char c in s2)
{
if (!chars.ContainsKey(c))
return false;
chars[c]--;
}
return chars.Values.All(i => i == 0);
}throw and throw ex?Yes, there is a difference:
throw ex, that thrown exception becomes the "original" one. So all previous stack trace will not be there.If you do throw, the exception just goes down the line and you'll get the full stack trace.
static void Main(string[] args)
{
try
{
Method2();
}
catch (Exception ex)
{
Console.Write(ex.StackTrace.ToString());
Console.ReadKey();
}
}
private static void Method2()
{
try
{
Method1();
}
catch (Exception ex)
{
//throw ex resets the stack trace Coming from Method 1 and propogates it to the caller(Main)
throw ex;
}
}
private static void Method1()
{
try
{
throw new Exception("Inside Method1");
}
catch (Exception)
{
throw;
}
}class ClassA
{
public ClassA() { }
public ClassA(int pValue) { }
}
// client program
class Program
{
static void Main(string[] args)
{
ClassA refA = new ClassA();
}
}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:
class ClassA
{
public ClassA() : this(10)
{ }
public ClassA(int pValue)
{ }
}I have this string
s1 = "My name is X Y Z"and I want to reverse the order of the words so that
s1 = "Z Y X is name My"Is it possible to do it in-place (without using additional data structures) and with the time complexity being O(n)?
Reverse the entire string, then reverse the letters of each individual word.
After the first pass the string will be
s1 = "Z Y X si eman yM"and after the second pass it will be
s1 = "Z Y X is name My"Reversing the entire string is easily done in O(n), and reversing each word in a string is also easy to do in O(n). O(n)+O(n) = O(n). Space complexity is O(1) as reversal done in-place.
static char[] ReverseAllWords(char[] in_text)
{
int lindex = 0;
int rindex = in_text.Length - 1;
if (rindex > 1)
{
//reverse complete phrase
in_text = ReverseString(in_text, 0, rindex);
//reverse each word in resultant reversed phrase
for (rindex = 0; rindex <= in_text.Length; rindex++)
{
if (rindex == in_text.Length || in_text[rindex] == ' ')
{
in_text = ReverseString(in_text, lindex, rindex - 1);
lindex = rindex + 1;
}
}
}
return in_text;
}
static char[] ReverseString(char[] intext, int lindex, int rindex)
{
char tempc;
while (lindex < rindex)
{
tempc = intext[lindex];
intext[lindex++] = intext[rindex];
intext[rindex--] = tempc;
}
return intext;
}==) and Equals() Method in C#?The == Operator (usually means the same as ReferenceEquals, could be overrided) compares the reference identity while the Equals() (virtual Equals()) method compares if two objects are equivalent.
Consider:
delegate void Printer();
static void Main()
{
List<Printer> printers = new List<Printer>();
int i=0;
for(; i < 10; i++)
{
printers.Add(delegate { Console.WriteLine(i); });
}
foreach (var printer in printers)
{
printer();
}
}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.
??) in C#?The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise, it returns the right operand.
string name = null;
string myname = name ?? "Laxmi";
Console.WriteLine(myname); get and set - instead of simply using public fields for those variables?Where method in C#. Explain.Rust has been Stack Overflow’s most loved language for four years in a row and emerged as a compelling language choice for both backend and system developers, offering a unique combination of memory safety, performance, concurrency without Data races...
Clean Architecture provides a clear and modular structure for building software systems, separating business rules from implementation details. It promotes maintainability by allowing for easier updates and changes to specific components without affe...
Azure Service Bus is a crucial component for Azure cloud developers as it provides reliable and scalable messaging capabilities. It enables decoupled communication between different components of a distributed system, promoting flexibility and resili...