0% found this document useful (0 votes)
38 views13 pages

One-Shot C#

Uploaded by

joshianiruddh29
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)
38 views13 pages

One-Shot C#

Uploaded by

joshianiruddh29
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/ 13

📄 C# One-Shot Notes

(~Created by Aniruddh Joshi on request of Diksha Bargali)

1. Class vs Interface

• Class = Blueprint that defines fields + methods together.


• Interface = Purely defines methods (no implementation) — like a contract.

🔹 Class = What it is + What it does


🔹 Interface = Only what it must do (no data)

2. Types of Collections in C#

• Array → Fixed-size.
• List → Dynamic size.
• Dictionary<TKey, TValue> → Key-value pairs.
• HashSet → Unique elements only.
• Queue → FIFO (First In First Out).
• Stack → LIFO (Last In First Out).

3. Garbage Collection in C#

• Automatic memory management.


• Cleans unused objects from memory.
• Works in generations (Gen 0, Gen 1, Gen 2).
• You can trigger manually using GC.Collect() (not recommended unless
necessary).
4. Value Type vs Reference Type

• Value Type: Stores data directly (stored in Stack).


o e.g., int, float, bool, struct
• Reference Type: Stores a reference to data (stored in Heap).
o e.g., class, array, string

5. Purpose of 'using' Statement

• Two meanings:
o Import namespaces (using System;).
o Manage resources (using block for auto-disposal like files, streams).

6. Exception Handling in C#

• Catches runtime errors using try-catch-finally.


• Prevents app crash and helps in controlled error handling.
• Example: try { } catch (Exception ex) { } finally { }

7. 'static' vs 'readonly'
static readonly

Belongs to the class, not instance Value assigned once (runtime)

Same for all instances Different for each instance

Example: static int count; Example: readonly int id;

8. Inheritance in C#

• A class can inherit properties and methods from another class using :
• Example: class Dog : Animal { }
• C# supports single inheritance, but multiple inheritance through interfaces.

9. LINQ (Language Integrated Query)

• Makes queries inside C# code for collections, databases.


• Syntax is simple like SQL.
• Example: var result = list.Where(x => x > 5);

10. 'ref' vs 'out'

• ref: Passes by reference (must be initialized before call).


• out: Passes by reference (can be initialized inside method only).

11. Access Modifiers in C#


Modifier Scope

public Accessible anywhere

private Only within the same class

protected Same class + derived classes

internal Same project/assembly

12. Purpose of Constructor

• Initializes objects when they are created.


• Can be default, parameterized, static, copy constructor.
13. Delegates

• A type-safe function pointer.


• Stores reference to a method and can call it dynamically.
• Foundation of events and callbacks.

14. Access Modifiers Explained Again (quick version)


Modifier Meaning

public Open everywhere

private Closed outside class

protected Open to derived classes

internal Open inside the project only

15. Create Asynchronous Method

• Use async keyword with await inside method.


• Example: async Task<int> GetDataAsync()

16. Nullable Types

• Allow value types to store null.


• Syntax: int? x = null;
• Useful when a value may or may not exist.

17. 'is' vs 'as' in C#

• is: Checks if object is a type. (returns bool)


• as: Tries to cast and returns null if it fails.
18. Generics

• Write reusable code without specifying data type.


• Example: List<T>, Dictionary<TKey, TValue>.
• Benefits: Type safety + performance.

19. Abstract Class vs Interface


Abstract Class Interface

Can have implementation Only method signatures

Supports fields and properties Only methods (and properties after C# 8.0)

20. Memory Management

• Handled by Garbage Collector.


• Manual disposal via IDisposable pattern when necessary.

21. Singleton Pattern

• Only one object of a class ever exists.


• Useful for settings, configurations.

22. string vs StringBuilder

• string is immutable (creates new object every time).


• StringBuilder is mutable (efficient for repeated string operations).
23. Multi-threading and Concurrency

• Using Thread, Task, or async/await.


• Care needed for shared data (locks, mutexes).

24. Purpose of 'async' and 'await'

• Write non-blocking code.


• Await suspends method until task is completed without freezing app.

25. Benefits & Limitations of async/await

✅ Benefits:

• Non-blocking
• Better performance

❌ Limitations:

• Debugging is harder
• Deadlocks if badly written

26. Boxing and Unboxing

• Boxing: Value type → Object (Heap).


• Unboxing: Object → Value type (Stack).

Example:
object obj = 123; // boxing
int num = (int)obj; // unboxing
27. string vs char[]

• string is immutable (cannot change characters).


• char[] is mutable (can modify letters).

28. Purpose of 'event' Keyword

• Used to declare an event.


• Event = Notification mechanism when something happens.

29. Handle Concurrency Issues

• Locking (lock keyword).


• Use Concurrent collections (ConcurrentDictionary, etc.).
• Minimize shared resources.

30. '==' vs '.Equals()'


'==' '.Equals()'

Compares by reference for objects Compares by value

Can be overloaded Virtual method

31. Custom Exceptions

• Create a class inheriting from Exception.


• Example: class MyCustomException : Exception { }

32. Purpose of 'virtual' Keyword

• Allows method to be overridden in derived class.


33. Namespace

• A logical container for classes, interfaces, enums.


• Helps in organization and avoiding name conflicts.

34. Dependency Injection (DI)

• Pass objects through constructor or method, instead of creating inside.


• Improves testability and loose coupling.

35. Tuples

• Group multiple values in one object.


• Example: var person = (Name: "John", Age: 30);

36. Task vs Thread


Task Thread

Lightweight Heavyweight

Based on thread pool OS-level

Better for short jobs Better for long running

37. Ensuring Thread Safety

• Locks (lock keyword).


• Volatile keyword (volatile).
• Use thread-safe collections.
38. Principles of OOP in C#

1. Encapsulation → Data hiding


2. Abstraction → Hiding complexity
3. Inheritance → Reuse code
4. Polymorphism → Same method name, different behavior

39. Extension Methods

• Add methods to existing types without modifying them.


• Syntax: public static class ExtensionClass

40. Factory and Singleton Design Patterns

• Factory → Creates objects without exposing logic.


• Singleton → Only one instance exists globally.

Here's a comprehensive C# section for your interview preparation:

1. Difference between a class and an interface in C#:


o Class: A class can have both method definitions and implementations,
can implement multiple interfaces, and can have access modifiers. A
class can be instantiated.
o Interface: An interface can only have method declarations (no
implementation), and classes or structs can implement interfaces.
Interfaces cannot be instantiated.
2. Different types of collections available in C#:
o Arrays, Lists, LinkedLists, Dictionaries, HashSets, Stacks, Queues,
SortedSets, etc., in the System.Collections and
System.Collections.Generic namespaces.
3. How does garbage collection work in C#:
o Garbage collection in C# is an automatic memory management feature.
It tracks the objects in memory, and when they are no longer referenced,
they are marked for collection, and the memory is reclaimed by the
system.
4. Difference between a value type and a reference type in C#:
o Value type: Stores the actual data. Examples: int, double, struct.
o Reference type: Stores a reference to the data's memory address.
Examples: class, string, array.
5. Purpose of the 'using' statement in C#:
o The using statement ensures that objects implementing
IDisposable are disposed of properly when they are no longer
needed, preventing memory leaks.
6. Concept of exception handling in C#:
o Exception handling in C# is done using try, catch, finally blocks.
try contains the code that may throw exceptions, catch handles
exceptions, and finally executes regardless of an exception.
7. Difference between 'static' and 'readonly' in C#:
o Static: Used for class-level variables/methods, shared across all
instances.
o Readonly: Used for variables that can only be assigned once (at
declaration or in the constructor) and cannot be modified later.
8. How to implement inheritance in C#:
o Inheritance is implemented using the : baseClass syntax. Example:
o class Derived : BaseClass { }
9. What is LINQ and how is it used in C#:
o LINQ (Language Integrated Query) allows querying collections (like
arrays, lists, etc.) in a SQL-like syntax. It is used to filter, sort, and
manipulate data.
o Example:
o var result = from item in collection where item
> 10 select item;
10. Difference between 'ref' and 'out' in C#:
o ref: The variable must be initialized before being passed.
o out: The variable doesn't need to be initialized, but it must be assigned a
value in the method.
11. Access modifiers in C# and their scopes:
o public, private, protected, internal, protected
internal, private protected.
12. Purpose of a constructor in C#:
o A constructor is used to initialize an object's state when it is created.
13. Concept of 'delegates' in C#:
o A delegate is a type-safe function pointer that allows methods to be
passed as parameters.
14. Difference between 'public', 'private', 'protected', and 'internal'
access modifiers in C#:
o public: Accessible from anywhere.
o private: Accessible only within the same class.
o protected: Accessible within the class and derived classes.
o internal: Accessible within the same assembly.
15. How to create an asynchronous method in C#:
o Use the async keyword before a method and the await keyword for
asynchronous operations.
16. public async Task DoWorkAsync() { await
Task.Delay(1000); }
17. What is a 'nullable' type in C# and when would you use it?
o A nullable type allows value types (like int, double) to hold null.
It's useful when you need to represent an absence of a value for types
that don't normally support it.
18. int? myVar = null;
19. Difference between 'is' and 'as' keywords in C#:
o is: Checks if an object is of a specific type.
o as: Tries to cast an object to a specific type and returns null if the cast
fails.
20. Concept of 'generics' in C# and example:
o Generics allow defining classes, methods, or interfaces with a
placeholder for data types.
21. public class Box<T> { public T Value { get;
set; } }
22. Difference between 'abstract' and 'interface' in C#:
o Abstract: Can contain method implementations but can’t be
instantiated. A class can inherit only one abstract class.
o Interface: Cannot contain method implementations and can be
implemented by multiple classes.
23. How to handle memory management in C#:
o C# relies on the garbage collector to manage memory. Developers can
also use Dispose and using statements for manual memory
management.
24. What is a 'singleton' pattern in C#:
o The Singleton pattern ensures a class has only one instance and provides
a global point of access to it.
25. Difference between 'string' and 'StringBuilder' in C#:
o string: Immutable; any modification creates a new instance.
o StringBuilder: Mutable; more efficient for frequent string
modifications.
26. How does C# handle multi-threading and concurrency?
o C# uses System.Threading for multi-threading and Task for
asynchronous programming. async/await simplifies concurrency
handling.
27. Purpose of the 'async' and 'await' keywords in C#:
o async: Marks a method as asynchronous.
o await: Pauses the method execution until the awaited task completes.
28. Benefits and limitations of using 'async/await' in C#:
o Benefits: Non-blocking I/O, better performance in UI and web
applications.
o Limitations: Can be tricky with exceptions, requires handling of
cancellations.
29. Concept of 'boxing' and 'unboxing' in C#:
o Boxing: Converting a value type to an object type.
o Unboxing: Converting an object type back to a value type.
30. Difference between 'String' and 'char[]' in C#:
o String: Immutable sequence of characters.
o char[]: Mutable array of characters.
31. Purpose of 'event' keyword in C#:
o The event keyword is used to declare an event, which is a way for an
object to notify other objects about changes or actions.
32. How to handle concurrency issues in C#:
o Use locks (lock keyword), semaphores, Monitor, and thread
synchronization mechanisms like Mutex and SemaphoreSlim.
33. Difference between '== operator' and '.Equals()' method in C#:
o ==: Checks for reference equality or value equality (depending on the
type).
o .Equals(): Checks for value equality by default.
34. Purpose of the 'virtual' keyword in C#:
o The virtual keyword allows a method or property to be overridden in
derived classes.
35. What is a 'namespace' in C#?
o A namespace is a container that holds classes, structs, and other types,
used to organize code and prevent naming conflicts.

You might also like