0% found this document useful (0 votes)
2 views20 pages

C#Concept with Programming

The document contains a comprehensive list of C# interview questions along with detailed answers and code examples. It covers various topics including data types, keywords, exception handling, and collections, providing insights into the differences between similar concepts. Each question is structured to enhance understanding of fundamental C# principles and practices.

Uploaded by

snehanila25
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
2 views20 pages

C#Concept with Programming

The document contains a comprehensive list of C# interview questions along with detailed answers and code examples. It covers various topics including data types, keywords, exception handling, and collections, providing insights into the differences between similar concepts. Each question is structured to enhance understanding of fundamental C# principles and practices.

Uploaded by

snehanila25
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 20

C# interview questions along with answers and program examples:

1. Question: What is the difference between IEnumerable and IEnumerator in C#?

Answer:

 IEnumerable: It represents a collection of objects that can be enumerated. It contains a


single method, GetEnumerator(), which returns an IEnumerator.
 IEnumerator: It provides the ability to iterate through the elements of a collection. It
contains methods like MoveNext(), Reset(), and a property Current to retrieve the
current element.

Example:

csharp
Copy code
using System;
using System.Collections;

class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3, 4, 5 };
IEnumerable enumerable = numbers;
IEnumerator enumerator = enumerable.GetEnumerator();

while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current);
}
}
}

2. Question: What is the use of out keyword in C#?

Answer: The out keyword is used for method parameters to indicate that the parameter is passed
by reference and will be assigned a value by the method.

Example:

csharp
Copy code
using System;

class Program
{
static void Divide(int dividend, int divisor, out int quotient)
{
quotient = dividend / divisor;
}
static void Main(string[] args)
{
int dividend = 10;
int divisor = 2;
int result;

Divide(dividend, divisor, out result);


Console.WriteLine("Quotient: " + result);
}
}

3. Question: What is the purpose of the static keyword in C#?

Answer: The static keyword is used to declare members (fields, methods, properties, etc.) that
belong to the type itself rather than to any specific instance of the type. These members can be
accessed using the type name without creating an instance of the class.

Example:

csharp
Copy code
using System;

class MathHelper
{
public static int Add(int a, int b)
{
return a + b;
}
}

class Program
{
static void Main(string[] args)
{
int sum = MathHelper.Add(5, 3);
Console.WriteLine("Sum: " + sum);
}
}

4. Question: What is the difference between String and StringBuilder in C#?

Answer:

 String: String objects are immutable, meaning their values cannot be changed after
they are created. When concatenating strings, new memory allocations are created.
 StringBuilder: StringBuilder is a mutable string type that allows efficient
manipulation of strings by modifying a single object rather than creating new ones.

Example:
csharp
Copy code
using System;
using System.Text;

class Program
{
static void Main(string[] args)
{
// Using String
string str = "Hello ";
str += "World";
Console.WriteLine(str);

// Using StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append("Hello ");
sb.Append("World");
Console.WriteLine(sb.ToString());
}
}

5. Question: What are the different access modifiers in C#? Explain each.

Answer:

 public: Accessible from anywhere.


 private: Accessible only within the containing type.
 protected: Accessible within the containing type and its derived types.
 internal: Accessible within the same assembly.
 protected internal: Accessible within the same assembly or from a derived type.

Example:

csharp
Copy code
using System;

public class MyClass


{
public int PublicField;
private int PrivateField;
protected int ProtectedField;
internal int InternalField;
protected internal int ProtectedInternalField;
}

class Program
{
static void Main(string[] args)
{
MyClass obj = new MyClass();
obj.PublicField = 10;
//obj.PrivateField = 20; // Error: PrivateField is inaccessible
//obj.ProtectedField = 30; // Error: ProtectedField is inaccessible
obj.InternalField = 40;
obj.ProtectedInternalField = 50;
}
}

6. Question: What is the difference between ref and out parameters in C#?

Answer:

 Both ref and out parameters are used for passing arguments by reference.
 ref parameters must be initialized before being passed to the method, while out
parameters do not need to be initialized before being passed.

Example:

csharp
Copy code
using System;

class Program
{
static void Modify(ref int x)
{
x += 10;
}

static void Initialize(out int y)


{
y = 10;
}

static void Main(string[] args)


{
int a = 5;
Modify(ref a);
Console.WriteLine("Modified a: " + a); // Output: Modified a: 15

int b;
Initialize(out b);
Console.WriteLine("Initialized b: " + b); // Output: Initialized b: 10
}
}

7. Question: What is the purpose of the params keyword in C#?

Answer: The params keyword allows a method to accept a variable number of arguments of the
same type. It is useful when the number of arguments is not known at compile time.

Example:
csharp
Copy code
using System;

class Program
{
static int Sum(params int[] numbers)
{
int sum = 0;
foreach (int num in numbers)
{
sum += num;
}
return sum;
}

static void Main(string[] args)


{
Console.WriteLine("Sum: " + Sum(1, 2, 3)); // Output: Sum: 6
Console.WriteLine("Sum: " + Sum(1, 2, 3, 4, 5)); // Output: Sum: 15
}
}

8. Question: What is boxing and unboxing in C#?

Answer:

 Boxing is the process of converting a value type to the corresponding reference type.
 Unboxing is the process of converting a boxed value type back to its original value type.

Example:

csharp
Copy code
using System;

class Program
{
static void Main(string[] args)
{
int num = 10; // Value type
object obj = num; // Boxing
int newNum = (int)obj; // Unboxing
Console.WriteLine("Unboxed value: " + newNum); // Output: Unboxed
value: 10
}
}

9. Question: What is the difference between == and Equals() method in C#?

Answer:
 ==: The == operator is used to compare the values of two objects. For value types, it
compares the actual values. For reference types, it compares the references.
 Equals(): The Equals() method is used to compare the contents or values of two
objects. It is overridden by most classes to provide meaningful comparison logic.

Example:

csharp
Copy code
using System;

class Program
{
static void Main(string[] args)
{
string str1 = "hello";
string str2 = "hello";
string str3 = "world";

// Using ==
Console.WriteLine("Using ==:");
Console.WriteLine(str1 == str2); // Output: True (because the values
are the same)
Console.WriteLine(str1 == str3); // Output: False (because the values
are different)

// Using Equals()
Console.WriteLine("\nUsing Equals():");
Console.WriteLine(str1.Equals(str2)); // Output: True (because the
values are the same)
Console.WriteLine(str1.Equals(str3)); // Output: False (because the
values are different)
}
}

10. Question: What is the difference between IEnumerable and IQueryable in


LINQ?

Answer:

 IEnumerable: Represents a collection that can be enumerated using the foreach loop.
LINQ queries against IEnumerable execute locally after fetching the data from the data
source.
 IQueryable: Represents a queryable collection, typically a database table, and supports
querying using LINQ operators. LINQ queries against IQueryable are translated into the
corresponding SQL queries and executed on the database server.

Example:

csharp
Copy code
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
static void Main(string[] args)
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

// IEnumerable
IEnumerable<int> evenNumbersEnumerable = numbers.Where(n => n % 2 ==
0);
Console.WriteLine("IEnumerable:");
foreach (var num in evenNumbersEnumerable)
{
Console.WriteLine(num);
}

// IQueryable
IQueryable<int> evenNumbersQueryable = numbers.AsQueryable().Where(n
=> n % 2 == 0);
Console.WriteLine("\nIQueryable:");
foreach (var num in evenNumbersQueryable)
{
Console.WriteLine(num);
}
}
}

11. Question: What is the purpose of the async and await keywords in C#?

Answer:

 async: The async keyword is used to define methods that can be executed
asynchronously.
 await: The await keyword is used to asynchronously wait for the completion of an
asynchronous task.

Example:

csharp
Copy code
using System;
using System.Threading.Tasks;

class Program
{
static async Task Main(string[] args)
{
await PrintAsync();
}

static async Task PrintAsync()


{
await Task.Delay(1000); // Simulate asynchronous operation
Console.WriteLine("Async operation completed.");
}
}

12. Question: What is the difference between a struct and a class in C#?

Answer:

 Structs are value types and are typically used for small, lightweight objects. They are
stored on the stack.
 Classes are reference types and are used for larger, more complex objects. They are
stored on the heap.

Example:

csharp
Copy code
using System;

struct Point // Struct


{
public int X;
public int Y;
}

class MyClass // Class


{
public int Number;
}

class Program
{
static void Main(string[] args)
{
Point point = new Point();
point.X = 10;
point.Y = 20;

MyClass myClass = new MyClass();


myClass.Number = 100;

Console.WriteLine("Point: (" + point.X + ", " + point.Y + ")");


Console.WriteLine("Number: " + myClass.Number);
}
}

13. Question: What is method overloading in C#?


Answer: Method overloading is the ability to define multiple methods in the same class with the
same name but different parameter lists. The compiler determines which method to call based on
the number and types of arguments provided.

Example:

csharp
Copy code
using System;

class MathOperations
{
public int Add(int a, int b)
{
return a + b;
}

public double Add(double a, double b)


{
return a + b;
}
}

class Program
{
static void Main(string[] args)
{
MathOperations math = new MathOperations();
Console.WriteLine(math.Add(5, 3)); // Output: 8
Console.WriteLine(math.Add(2.5, 3.5)); // Output: 6.0
}
}

14. Question: What is the purpose of the using statement in C#?

Answer: The using statement is used to ensure that resources are properly disposed of after use.
It is commonly used with objects that implement the IDisposable interface, such as file
streams, database connections, and network streams.

Example:

csharp
Copy code
using System;

class Program
{
static void Main(string[] args)
{
using (var fileStream = new System.IO.FileStream("example.txt",
System.IO.FileMode.Open))
{
// Perform operations with fileStream
} // fileStream.Dispose() is automatically called here
}
}

15. Question: What are delegates in C#?

Answer: Delegates are type-safe function pointers that are used to reference methods. They
allow methods to be passed as parameters to other methods or assigned to variables, providing a
way to implement callbacks and event handling.

Example:

csharp
Copy code
using System;

delegate void MyDelegate(string message);

class Program
{
static void Main(string[] args)
{
MyDelegate del = DisplayMessage;
del("Hello, world!");
}

static void DisplayMessage(string message)


{
Console.WriteLine(message);
}
}

16. Question: What is a lambda expression in C#?

Answer: A lambda expression is a concise way to define an anonymous function in C#. It allows
you to create delegate instances or expression tree types without having to explicitly define a
named method.

Example:

csharp
Copy code
using System;

class Program
{
static void Main(string[] args)
{
Func<int, int, int> add = (a, b) => a + b;
Console.WriteLine(add(5, 3)); // Output: 8
}
}
17. Question: What is the purpose of the try, catch, and finally blocks in C#
exception handling?

Answer:

 try: The try block is used to enclose the code that may throw an exception.
 catch: The catch block is used to handle the exception if it occurs. Multiple catch
blocks can be used to handle different types of exceptions.
 finally: The finally block is used to execute code that should always run, regardless
of whether an exception occurs or not. It is typically used for cleanup operations.

Example:

csharp
Copy code
using System;

class Program
{
static void Main(string[] args)
{
try
{
int result = Divide(10, 0);
Console.WriteLine("Result: " + result); // This line will not be
executed
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
Console.WriteLine("Cleanup operations");
}
}

static int Divide(int dividend, int divisor)


{
return dividend / divisor;
}
}

18. Question: What is method overriding in C#?

Answer: Method overriding is a feature of object-oriented programming that allows a subclass


to provide a specific implementation of a method that is already defined in its superclass. The
method in the subclass must have the same signature (name, parameters, and return type) as the
method in the superclass.
Example:

csharp
Copy code
using System;

class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing shape");
}
}

class Circle : Shape


{
public override void Draw()
{
Console.WriteLine("Drawing circle");
}
}

class Program
{
static void Main(string[] args)
{
Shape shape = new Circle();
shape.Draw(); // Output: Drawing circle
}
}

19. Question: What are indexers in C#?

Answer: Indexers allow objects to be indexed in a similar way to arrays. They are defined like
properties but use this keyword instead of a property name. Indexers enable instances of a class
or struct to be accessed as if they were arrays.

Example:

csharp
Copy code
using System;

class MyList
{
private int[] array = new int[5];

public int this[int index]


{
get { return array[index]; }
set { array[index] = value; }
}
}
class Program
{
static void Main(string[] args)
{
MyList list = new MyList();
list[0] = 1;
list[1] = 2;
Console.WriteLine("Element at index 0: " + list[0]); // Output:
Element at index 0: 1
Console.WriteLine("Element at index 1: " + list[1]); // Output:
Element at index 1: 2
}
}

20. Question: What is the purpose of the lock statement in C#?

Answer: The lock statement is used to synchronize access to a shared resource or critical
section of code in a multi-threaded environment. It ensures that only one thread can execute the
synchronized code block at a time, preventing race conditions.

Example:

csharp
Copy code
using System;
using System.Threading;

class Program
{
static int counter = 0;
static readonly object lockObject = new object();

static void Main(string[] args)


{
Thread t1 = new Thread(IncrementCounter);
Thread t2 = new Thread(IncrementCounter);

t1.Start();
t2.Start();

t1.Join();
t2.Join();

Console.WriteLine("Counter value: " + counter); // Output: Counter


value: 2
}

static void IncrementCounter()


{
lock (lockObject)
{
counter++;
}
}
}

21. Question: What is the difference between HashSet and List in C#?

Answer:

 HashSet: Stores unique elements only, eliminating duplicates automatically. Provides


faster lookup time for determining whether an element exists in the collection.
 List: Allows duplicate elements and preserves the order of elements. Provides fast
access to elements by index.

Example:

csharp
Copy code
using System;
using System.Collections.Generic;

class Program
{
static void Main(string[] args)
{
HashSet<int> hashSet = new HashSet<int>();
hashSet.Add(1);
hashSet.Add(2);
hashSet.Add(1); // Duplicate element, will not be added

List<int> list = new List<int>();


list.Add(1);
list.Add(2);
list.Add(1); // Duplicate element, will be added

Console.WriteLine("HashSet:");
foreach (var item in hashSet)
{
Console.WriteLine(item);
}

Console.WriteLine("\nList:");
foreach (var item in list)
{
Console.WriteLine(item);
}
}
}

22. Question: What is the purpose of the readonly keyword in C#?

Answer: The readonly keyword is used to declare fields that can only be assigned a value once,
either at the time of declaration or in the constructor of the class. Once assigned, the value of a
readonly field cannot be changed.
Example:

csharp
Copy code
using System;

class MyClass
{
public readonly int ReadOnlyField;

public MyClass(int value)


{
ReadOnlyField = value; // Assigning value in the constructor
}
}

class Program
{
static void Main(string[] args)
{
MyClass obj = new MyClass(10);
//obj.ReadOnlyField = 20; // Error: Cannot assign to 'ReadOnlyField'
because it is read-only
Console.WriteLine("ReadOnlyField: " + obj.ReadOnlyField); // Output:
ReadOnlyField: 10
}
}

23. Question: What is the difference between a shallow copy and a deep copy in
C#?

Answer:

 Shallow Copy: Copies the references to objects, so the original and copied objects refer
to the same underlying data. Changes to the data in one object will affect the other object.
 Deep Copy: Creates a new copy of the object and recursively copies all nested objects.
The original and copied objects have their own independent copies of the data.

Example:

csharp
Copy code
using System;
using System.Collections.Generic;

class MyClass
{
public int[] Numbers;

public MyClass(int[] numbers)


{
Numbers = numbers;
}
}

class Program
{
static void Main(string[] args)
{
int[] numbers = { 1, 2, 3 };
MyClass original = new MyClass(numbers);

// Shallow copy
MyClass shallowCopy = original;
shallowCopy.Numbers[0] = 10;
Console.WriteLine("Original Numbers[0]: " + original.Numbers[0]); //
Output: Original Numbers[0]: 10

// Deep copy
int[] copiedNumbers = (int[])numbers.Clone();
MyClass deepCopy = new MyClass(copiedNumbers);
deepCopy.Numbers[0] = 20;
Console.WriteLine("Original Numbers[0]: " + original.Numbers[0]); //
Output: Original Numbers[0]: 10
}
}

24. Question: What is the purpose of the yield keyword in C#?

Answer: The yield keyword is used in iterator methods to return each element of a sequence
one at a time. It allows the method to pause execution and return control to the caller, resuming
where it left off when the next element is requested.

Example:

csharp
Copy code
using System;
using System.Collections.Generic;

class Program
{
static void Main(string[] args)
{
foreach (var number in GetNumbers())
{
Console.WriteLine(number);
}
}

static IEnumerable<int> GetNumbers()


{
yield return 1;
yield return 2;
yield return 3;
}
}
25. Question: What are extension methods in C#?

Answer: Extension methods allow you to add new methods to existing types without modifying
the original type or creating a new derived type. They are defined as static methods in a static
class and must be in the same namespace as the extended type.

Example:

csharp
Copy code
using System;

public static class StringExtensions


{
public static bool IsNullOrEmpty(this string value)
{
return string.IsNullOrEmpty(value);
}
}

class Program
{
static void Main(string[] args)
{
string str = "";
Console.WriteLine(str.IsNullOrEmpty()); // Output: True
}
}

26. Question: What is the purpose of the volatile keyword in C#?

Answer: The volatile keyword is used to indicate that a field might be modified by multiple
threads that are executing at the same time. It ensures that changes to the field are visible to all
threads immediately.

Example:

csharp
Copy code
using System;
using System.Threading;

class Program
{
static volatile bool flag = false;

static void Main(string[] args)


{
new Thread(ChangeFlag).Start();

while (!flag) { } // Spin until flag becomes true


Console.WriteLine("Flag is now true.");
}

static void ChangeFlag()


{
Thread.Sleep(1000);
flag = true;
}
}

27. Question: What is the purpose of the checked and unchecked keywords in C#?

Answer:

 checked: The checked keyword is used to enable arithmetic overflow checking for
integral-type arithmetic operations. It throws an exception if an overflow occurs.
 unchecked: The unchecked keyword is used to suppress arithmetic overflow checking
for integral-type arithmetic operations. It allows overflow to occur without throwing an
exception.

Example:

csharp
Copy code
using System;

class Program
{
static void Main(string[] args)
{
int a = int.MaxValue;
int b = int.MaxValue;

checked
{
int sum = a + b; // Throws System.OverflowException
}

unchecked
{
int sum = a + b; // No exception thrown
Console.WriteLine("Sum: " + sum); // Output: Sum: -2
}
}
}

28. Question: What is the purpose of the nameof operator in C#?

Answer: The nameof operator is used to obtain the simple (unqualified) name of a variable,
type, or member as a string. It provides a way to refer to program elements in a way that is
independent of the element name.
Example:

csharp
Copy code
using System;

class Program
{
static void Main(string[] args)
{
Console.WriteLine(nameof(Program)); // Output: Program
Console.WriteLine(nameof(Program.Main)); // Output: Main

string variable = "value";


Console.WriteLine(nameof(variable)); // Output: variable
}
}

29. Question: What is the purpose of the using directive in C#?

Answer: The using directive is used to include namespaces in the current file or scope. It allows
types and members from those namespaces to be used in code without fully qualifying their
names.

Example:

csharp
Copy code
using System;

class Program
{
static void Main(string[] args)
{
DateTime now = DateTime.Now;
Console.WriteLine(now);
}
}

30. Question: What is the purpose of the async modifier in C#?

Answer: The async modifier is used to define asynchronous methods, which can perform long-
running operations without blocking the calling thread. Asynchronous methods return a Task or
Task<T> object that represents the ongoing operation.

Example:

csharp
Copy code
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
await Task.Delay(1000);
Console.WriteLine("Async operation completed.");
}
}

You might also like