0% found this document useful (0 votes)
17 views24 pages

C#Sharp Question Answer

The document provides a comprehensive overview of C#, covering fundamental concepts such as value types, reference types, classes, interfaces, inheritance, polymorphism, and exception handling. It includes explanations and code examples for various features like constructors, destructors, access modifiers, collections, and LINQ. Additionally, it discusses keywords like 'static', 'readonly', 'const', and operators such as '??' and the ternary operator.

Uploaded by

technovitybiet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views24 pages

C#Sharp Question Answer

The document provides a comprehensive overview of C#, covering fundamental concepts such as value types, reference types, classes, interfaces, inheritance, polymorphism, and exception handling. It includes explanations and code examples for various features like constructors, destructors, access modifiers, collections, and LINQ. Additionally, it discusses keywords like 'static', 'readonly', 'const', and operators such as '??' and the ternary operator.

Uploaded by

technovitybiet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

## 1. What is C#?

**Explanation:**
C# is a modern, object-oriented programming language developed by Microsoft for building
applications on the .NET platform.
**Example:**
```csharp
// This is a simple C# program
using System;
class HelloWorld {
static void Main() {
Console.WriteLine("Hello, World!");
}
}
```

---

## 2. What are value types and reference types in C#?


**Explanation:**
Value types store data directly and are usually stored on the stack. Reference types store the
address of the data (reference) and are stored on the heap.
**Example:**
```csharp
int a = 10; // value type
string b = "Hello"; // reference type
```

---

## 3. What is the difference between `==` and `.Equals()`?


**Explanation:**
The `==` operator checks for value equality for value types and reference equality for
reference types unless overloaded. The `.Equals()` method checks for value equality and can
be overridden for custom behavior.
**Example:**
```csharp
string s1 = "abc";
string s2 = new string(new char[] { 'a', 'b', 'c' });
Console.WriteLine(s1 == s2); // True, compares value
Console.WriteLine(s1.Equals(s2)); // True, compares value
```

---
## 4. What is a namespace?
**Explanation:**
A namespace is used to organize code and prevent name conflicts by grouping related
classes, interfaces, and methods.
**Example:**
```csharp
namespace MyApplication {
class Program { }
}
```

---

## 5. What is a class? What is an object?


**Explanation:**
A class is a blueprint for creating objects, which are instances of classes.
**Example:**
```csharp
class Dog {
public string Name;
}
Dog d = new Dog();
d.Name = "Buddy";
```

---

## 6. What is a struct?
**Explanation:**
A struct is a value type that can contain fields, methods, and constructors but does not
support inheritance.
**Example:**
```csharp
struct Point {
public int X, Y;
}
Point p = new Point();
p.X = 5; p.Y = 10;
```

---
## 7. What is an interface?
**Explanation:**
An interface defines a contract (methods/properties) that implementing classes must fulfill
but provides no implementation.
**Example:**
```csharp
interface IFly {
void Fly();
}
class Bird : IFly {
public void Fly() { Console.WriteLine("Flying"); }
}
```

---

## 8. What is an abstract class?


**Explanation:**
An abstract class cannot be instantiated and may contain abstract (no body) and non-
abstract (with body) members.
**Example:**
```csharp
abstract class Animal {
public abstract void Speak();
}
class Dog : Animal {
public override void Speak() { Console.WriteLine("Woof"); }
}
```

---

## 9. What is encapsulation?
**Explanation:**
Encapsulation is the idea of hiding internal details and only exposing what is necessary
through public members.
**Example:**
```csharp
class Person {
private string name;
public string Name {
get { return name; }
set { name = value; }
}
}
```

---

## 10. What is inheritance?


**Explanation:**
Inheritance allows a class (derived) to inherit members from another class (base).
**Example:**
```csharp
class Animal { public void Eat() { } }
class Dog : Animal { }
Dog d = new Dog();
d.Eat(); // Inherited from Animal
```

---

## 11. What is polymorphism?


**Explanation:**
Polymorphism lets one interface be used for different types of objects, usually via method
overriding or interfaces.
**Example:**
```csharp
class Animal { public virtual void Speak() { Console.WriteLine("..."); } }
class Cat : Animal { public override void Speak() { Console.WriteLine("Meow"); } }
Animal a = new Cat();
a.Speak(); // Calls Cat's Speak
```

---

## 12. What is method overloading?


**Explanation:**
Method overloading allows multiple methods with the same name but different parameter
lists.
**Example:**
```csharp
void Print(int n) { }
void Print(string s) { }
```
---

## 13. What is method overriding?


**Explanation:**
Method overriding lets a derived class provide its own implementation of a method
declared in a base class, using `override`.
**Example:**
```csharp
class Base { public virtual void Show() { Console.WriteLine("Base"); } }
class Derived : Base { public override void Show() { Console.WriteLine("Derived"); } }
```

---

## 14. What is the difference between `ref` and `out` parameters?


**Explanation:**
`ref` requires the parameter to be initialized before passing; `out` does not, but must be
assigned in the method.
**Example:**
```csharp
void TestRef(ref int x) { x = 10; }
void TestOut(out int y) { y = 20; }
int a = 5, b;
TestRef(ref a);
TestOut(out b);
```

---

## 15. What is a constructor?


**Explanation:**
A constructor is a special method called when an object is created, used for initialization.
**Example:**
```csharp
class Car {
public string Model;
public Car(string model) { Model = model; }
}
Car c = new Car("Honda");
```

---
## 16. What is a destructor?
**Explanation:**
A destructor is a special method that is called when an object is being garbage collected for
cleanup.
**Example:**
```csharp
class Demo {
~Demo() {
// Cleanup code here
}
}
```

---

## 17. What is the `static` keyword?


**Explanation:**
The `static` keyword makes a member belong to the type itself, not to any instance.
**Example:**
```csharp
class MathHelper {
public static int Add(int a, int b) { return a + b; }
}
int result = MathHelper.Add(2, 3);
```

---

## 18. What is the `readonly` keyword?


**Explanation:**
A `readonly` field can only be assigned at declaration or in the constructor and can’t be
changed afterwards.
**Example:**
```csharp
class Test {
public readonly int x = 10;
public Test(int y) { x = y; }
}
```

---

## 19. What is the `const` keyword?


**Explanation:**
A `const` field’s value is set at compile time and cannot be changed.
**Example:**
```csharp
const double PI = 3.14159;
```

---

## 20. What are properties in C#?


**Explanation:**
Properties are members that provide a mechanism to read, write, or compute the values of
private fields.
**Example:**
```csharp
class Employee {
private int age;
public int Age {
get { return age; }
set { age = value; }
}
}
```

---

## 21. What is an indexer?


**Explanation:**
An indexer allows an object to be indexed like an array.
**Example:**
```csharp
class Sample {
int[] arr = new int[10];
public int this[int i] {
get { return arr[i]; }
set { arr[i] = value; }
}
}
Sample s = new Sample();
s[0] = 5;
```

---
## 22. What is the difference between array and ArrayList?
**Explanation:**
An array is fixed-size and type-safe; ArrayList is dynamic and can store any type (not type-
safe).
**Example:**
```csharp
int[] arr = new int[3] { 1, 2, 3 };
ArrayList list = new ArrayList();
list.Add(1);
list.Add("Hello");
```

---

## 23. What is the difference between `public`, `private`, `protected`, and `internal`?
**Explanation:**
- `public`: accessible from anywhere
- `private`: accessible only within the class
- `protected`: accessible in the class and its derived classes
- `internal`: accessible within the same assembly
**Example:**
```csharp
public class A { private int x; protected int y; internal int z; }
```

---

## 24. What is a delegate?


**Explanation:**
A delegate is a type-safe reference to a method (function pointer).
**Example:**
```csharp
public delegate void MyDelegate(string msg);
void Print(string msg) { Console.WriteLine(msg); }
MyDelegate d = Print;
d("Hello");
```

---

## 25. What is an event?


**Explanation:**
An event is a way for a class to notify other classes or objects when something of interest
occurs, using delegates.
**Example:**
```csharp
class Button {
public event Action Clicked;
public void Click() { Clicked?.Invoke(); }
}
Button btn = new Button();
btn.Clicked += () => Console.WriteLine("Button Clicked");
btn.Click();
```

---

## 26. What is exception handling?


**Explanation:**
Exception handling is a mechanism for handling runtime errors with `try`, `catch`, and
`finally` blocks.
**Example:**
```csharp
try {
int x = int.Parse("abc");
} catch (FormatException) {
Console.WriteLine("Invalid format");
} finally {
Console.WriteLine("Always runs");
}
```

---

## 27. What is boxing and unboxing?


**Explanation:**
Boxing is converting a value type to object; unboxing is converting the object back to value
type.
**Example:**
```csharp
int n = 5;
object obj = n; // Boxing
int m = (int)obj; // Unboxing
```
---

## 28. What is the difference between `==` operator and `Equals()` method for strings?
**Explanation:**
Both compare string values, but `Equals()` can be overridden for custom types.
**Example:**
```csharp
string a = "test";
string b = "test";
bool res1 = (a == b); // true
bool res2 = a.Equals(b); // true
```

---

## 29. What is a sealed class?


**Explanation:**
A sealed class cannot be inherited.
**Example:**
```csharp
sealed class FinalClass { }
```

---

## 30. What is partial class?


**Explanation:**
A partial class can be split across multiple files.
**Example:**
```csharp
// File1.cs
partial class Sample { void A() { } }
// File2.cs
partial class Sample { void B() { } }
```

---

## 31. What is a nullable type?


**Explanation:**
A nullable type allows a value type to represent all values of its type plus null.
**Example:**
```csharp
int? age = null;
```

---

## 32. What are generics?


**Explanation:**
Generics allow the creation of classes, methods, and interfaces with a placeholder for the
data type.
**Example:**
```csharp
List<int> numbers = new List<int>();
```

---

## 33. What is LINQ?


**Explanation:**
LINQ (Language Integrated Query) allows querying collections (arrays, lists, etc.) in a SQL-
like way.
**Example:**
```csharp
var even = from n in new[] {1,2,3,4} where n % 2 == 0 select n;
```

---

## 34. What is the `var` keyword?


**Explanation:**
`var` allows implicit typing; the compiler infers the variable's type from the assignment.
**Example:**
```csharp
var n = 5; // int
```

---

## 35. What is the difference between `break` and `continue`?


**Explanation:**
`break` exits a loop; `continue` skips the rest of the current loop iteration.
**Example:**
```csharp
for(int i=0;i<5;i++) {
if(i==2) continue;
if(i==4) break;
Console.Write(i); // Output: 0 1 3
}
```

---

## 36. What is a namespace alias?


**Explanation:**
A namespace alias gives an alternate name for a namespace.
**Example:**
```csharp
using Proj = Project.MyNamespace;
```

---

## 37. What is the `base` keyword?


**Explanation:**
`base` is used to access members of the base class from a derived class.
**Example:**
```csharp
class Parent { public void Show() { } }
class Child : Parent {
public void Display() { base.Show(); }
}
```

---

## 38. What is the `this` keyword?


**Explanation:**
`this` refers to the current instance of the class.
**Example:**
```csharp
class Car {
string model;
public Car(string model) { this.model = model; }
}
```

---
## 39. What is a static constructor?
**Explanation:**
A static constructor initializes static fields of a class and runs only once.
**Example:**
```csharp
class Test {
static int count;
static Test() { count = 1; }
}
```

---

## 40. What is an access modifier?


**Explanation:**
Access modifiers define the visibility of types and members.
**Example:**
```csharp
public class A { private int x; }
```

---

## 41. What is a jagged array?


**Explanation:**
A jagged array is an array of arrays, where each inner array can have a different length.
**Example:**
```csharp
int[][] arr = new int[2][];
arr[0] = new int[3];
arr[1] = new int[2];
```

---

## 42. What is a multidimensional array?


**Explanation:**
A multidimensional array has more than one dimension, like a matrix.
**Example:**
```csharp
int[,] matrix = new int[2,3];
```
---

## 43. What is the difference between `throw` and `throw ex`?


**Explanation:**
`throw` rethrows the current exception preserving the stack trace; `throw ex` resets it.
**Example:**
```csharp
try { ... }
catch (Exception ex) {
throw; // preserves stack trace
// throw ex; // resets stack trace
}
```

---

## 44. What is the difference between compile-time and run-time errors?


**Explanation:**
Compile-time errors are caught by the compiler; run-time errors happen while the program
is running.
**Example:**
```csharp
// Compile-time error: int x = "abc";
// Run-time error: int.Parse("abc");
```

---

## 45. What is the `params` keyword?


**Explanation:**
`params` lets you pass a variable number of arguments to a method.
**Example:**
```csharp
void PrintNumbers(params int[] numbers) {
foreach (var n in numbers) Console.WriteLine(n);
}
PrintNumbers(1,2,3,4);
```

---

## 46. What are collections in C#?


**Explanation:**
Collections are classes that store groups of objects, such as `List<T>`, `Dictionary<K,V>`,
`Queue<T>`, etc.
**Example:**
```csharp
List<string> names = new List<string>();
names.Add("Alice");
```

---

## 47. What is the difference between `List<T>` and `ArrayList`?


**Explanation:**
List<T> is generic and type-safe; ArrayList stores objects (not type-safe).
**Example:**
```csharp
List<int> nums = new List<int>();
ArrayList list = new ArrayList();
list.Add(1); list.Add("Hello");
```

---

## 48. What is the `foreach` loop?


**Explanation:**
`foreach` is used to iterate over a collection or array.
**Example:**
```csharp
int[] nums = {1,2,3};
foreach(int n in nums) Console.WriteLine(n);
```

---

## 49. What is the ternary operator?


**Explanation:**
The ternary operator is a shorthand for if-else: `condition ? expr1 : expr2`.
**Example:**
```csharp
int a = 10, b = 20;
int max = (a > b) ? a : b;
```
---

## 50. What is the null-coalescing operator (`??`)?


**Explanation:**
Returns the left-hand operand if it's not null; otherwise, returns the right-hand operand.
**Example:**
```csharp
string name = null;
string display = name ?? "Unknown";
```

---

## 51. What is the difference between `abstract` and `virtual` methods?


**Explanation:**
An abstract method has no implementation and must be overridden; a virtual method has a
default implementation and can be overridden.
**Example:**
```csharp
abstract class A { public abstract void Foo(); }
class B : A { public override void Foo() { } }

class C { public virtual void Bar() { } }


class D : C { public override void Bar() { } }
```

---

## 52. What is type casting?


**Explanation:**
Type casting converts a variable from one type to another (explicitly or implicitly).
**Example:**
```csharp
int n = 10;
double d = n; // implicit
int x = (int)d; // explicit
```

---

## 53. What is implicit and explicit casting?


**Explanation:**
Implicit casting happens automatically; explicit casting requires a cast operator and may
lose data.
**Example:**
```csharp
double d = 9.8;
int n = (int)d; // explicit
```

---

## 54. What is the `is` operator?


**Explanation:**
`is` checks if an object is compatible with a given type.
**Example:**
```csharp
object obj = "hello";
if (obj is string) { /* true */ }
```

---

## 55. What is the `as` operator?


**Explanation:**
`as` tries to cast an object to a type; returns null if it fails.
**Example:**
```csharp
object obj = "test";
string str = obj as string; // str = "test"
```

---

## 56. What is a thread?


**Explanation:**
A thread is a unit of execution. C# supports multithreading for concurrent processing.
**Example:**
```csharp
using System.Threading;
Thread t = new Thread(() => Console.WriteLine("Running"));
t.Start();
```

---
## 57. What is deadlock?
**Explanation:**
A deadlock occurs when two or more threads are waiting for each other to release
resources, so all are blocked.
**Example:**
```csharp
// Two threads lock resources in different order, causing deadlock
```

---

## 58. What is async and await?


**Explanation:**
`async` and `await` are used for asynchronous programming, allowing non-blocking
operations.
**Example:**
```csharp
async Task<int> GetDataAsync() {
await Task.Delay(1000);
return 42;
}
```

---

## 59. What is a lambda expression?


**Explanation:**
A lambda is an anonymous function that can be used as a delegate or expression tree.
**Example:**
```csharp
Func<int,int> square = x => x*x;
Console.WriteLine(square(5)); // 25
```

---

## 60. What is an anonymous method?


**Explanation:**
An anonymous method is a method without a name, defined using the `delegate` keyword.
**Example:**
```csharp
Action<int> print = delegate(int x) { Console.WriteLine(x); };
print(10);
```

---

## 61. What is the difference between `Dispose` and `Finalize`?


**Explanation:**
`Dispose` is called explicitly to free resources; `Finalize` is called by the garbage collector.
**Example:**
```csharp
class Demo : IDisposable {
public void Dispose() { /* cleanup */ }
~Demo() { /* cleanup */ }
}
```

---

## 62. What is garbage collection?


**Explanation:**
Garbage collection automatically frees memory used by objects no longer in use.
**Example:**
```csharp
// No need to manually free memory for most objects in C#
```

---

## 63. What is an extension method?


**Explanation:**
An extension method adds new methods to existing types without modifying them.
**Example:**
```csharp
public static class StringExtensions {
public static bool IsCapitalized(this string str) {
return !string.IsNullOrEmpty(str) && char.IsUpper(str[0]);
}
}
Console.WriteLine("Hello".IsCapitalized()); // True
```

---

## 64. What is a tuple?


**Explanation:**
A tuple is a data structure that holds a group of items of different types.
**Example:**
```csharp
var tuple = (1, "apple", true);
Console.WriteLine(tuple.Item2); // apple
```

---

## 65. What is a dictionary?


**Explanation:**
A dictionary is a collection of key-value pairs.
**Example:**
```csharp
Dictionary<string,int> ages = new Dictionary<string,int>();
ages["Tom"] = 30;
```

---

## 66. What is an enum?


**Explanation:**
An enum is a special value type used to define a group of named constants.
**Example:**
```csharp
enum Days { Sun, Mon, Tue }
Days today = Days.Mon;
```

---

## 67. What is the purpose of the `using` statement?


**Explanation:**
The `using` statement ensures disposal of resources (like files) that implement IDisposable.
**Example:**
```csharp
using (StreamReader sr = new StreamReader("file.txt")) {
string line = sr.ReadLine();
}
```

---
## 68. What is the difference between `readonly` and `const`?
**Explanation:**
`const` is compile-time constant; `readonly` is runtime constant (can be set in constructor).
**Example:**
```csharp
const int X = 5;
readonly int Y;
public Example() { Y = 10; }
```

---

## 69. What is a design pattern?


**Explanation:**
A design pattern is a reusable solution to common software design problems.
**Example:**
```csharp
// Singleton pattern example
class Singleton {
private static Singleton instance;
private Singleton() { }
public static Singleton Instance {
get {
if (instance == null) instance = new Singleton();
return instance;
}
}
}
```

---

## 70. What is a singleton pattern?


**Explanation:**
Singleton pattern ensures a class has only one instance and provides a global point of
access.
**Example:**
```csharp
// See above Singleton example
```

---
## 71. What is MVC?
**Explanation:**
MVC (Model-View-Controller) is a pattern to separate data (Model), UI (View), and logic
(Controller).
**Example:**
```csharp
// ASP.NET MVC uses Controller, View, Model classes
```

---

## 72. What is dependency injection?


**Explanation:**
Dependency injection is a technique where dependencies are passed to a class instead of
being created inside it.
**Example:**
```csharp
class Service { }
class Consumer {
private Service _service;
public Consumer(Service service) { _service = service; }
}
```

---

## 73. What is a unit test?


**Explanation:**
A unit test is a test written to verify a small piece of code (method/class) works as
expected.
**Example:**
```csharp
[Test]
public void Add_TwoNumbers_ReturnsSum() {
Assert.AreEqual(5, Add(2,3));
}
```

---

## 74. What is a mock object?


**Explanation:**
A mock object simulates the behavior of real objects in tests.
**Example:**
```csharp
var repo = new Mock<IRepository>();
repo.Setup(r => r.Get()).Returns("data");
```

---

## 75. What is XML documentation?


**Explanation:**
XML documentation uses comments (`///`) to describe code for tools like IntelliSense.
**Example:**
```csharp
/// <summary>Adds two numbers</summary>
int Add(int a, int b) { return a+b; }
```

---

## 76. What is a try-catch-finally block?


**Explanation:**
It is used to handle exceptions, ensuring that `finally` always runs.
**Example:**
```csharp
try { /* code */ }
catch (Exception) { /* handle */ }
finally { /* always runs */ }
```

---

## 77. What is the difference between interface and abstract class?


**Explanation:**
An interface has only declarations, no implementation; an abstract class can have both.
**Example:**
```csharp
interface IFoo { void Bar(); }
abstract class Baz { public abstract void Bar(); public void Qux() { } }
```

---
## 78. What is the difference between stack and heap memory?
**Explanation:**
Stack stores value types and method calls; heap stores objects and reference types.
**Example:**
```csharp
int n = 5; // stack
object obj = new object(); // heap
```

---

## 79. What is the difference between `String` and `StringBuilder`?


**Explanation:**
`String` is immutable; `StringBuilder` is mutable and efficient for frequent changes.
**Example:**
```csharp
string s = "a";
s += "b"; // creates new string
StringBuilder sb = new StringBuilder("a");
sb.Append("b"); // appends in place
```

---

## 80. How do you comment code in C#?


**Explanation:**
Single-line comments use `//`, multi-line use `/* ... */`, and XML documentation uses `///`.
**Example:**
```csharp
// Single-line comment
/*
Multi-line comment
*/
/// <summary>XML doc comment</summary>
```

You might also like