Study Flashcards
What is a generic type?
A type of which represents a placeholder for any data type you choose when creating an instance of the class.
E.g. Here’s a simple example using List<T> in C# to illustrate generics:</T>
List<int> numbers = new List<int>();</int></int>
So you can see that we use an int alternatively we could create:
List<string> words = new List<string>();</string></string>
Why are generics useful?
- Generics are useful because they enable code re-usability
- Generics ensure that when you specify a type (like List<int>), the compiler checks that you only use that type. This means errors, like adding a string to a list of integers, are caught before your program runs.</int>
What is Encapsulation in programming?
Putting everything to do with an Object in one place. E.g. Car has brake pedals, steering wheel, wheels etc inside the car body. (class)
What is Polymorphism?
Base classes like Animal has a function make animal sound. We create Pig and Dog class, due to polymorphism they can call make an animal sound as they are an animal. You can change how this inherited function behaves using the OVERRIDE keyword but you need to use VIRTUAL when defining the Animal classes function you want to override.
e.g.
virtual would allow the child class to override it but you have to use override on the child classes function that you’re inheriting
class Animal // Base class (parent)
{
public VIRTUAL void animalSound()
{
Console.WriteLine(“The animal makes a sound”);
}
}
class Pig : Animal // Derived class (child)
{
public OVERRIDE void animalSound()
{
Console.WriteLine(“The pig says: wee wee”);
}
}
Without override the Pig would output “The animal makes a sound” when calling animalSound() method.
What is data abstraction?
Hint abstract
Process of hiding certain details, so you can have an abstract class Animal as the base with the Abstract function (they will never be created or called) for the sole purpose to force the child classes to define their own.
Hide Details: You only see the important features, not the messy inner workings.
Common Blueprint: It forces every similar object to have certain methods, so they all work in a predictable way.
Easier Changes: If you change how something works behind the scenes, you don’t have to change the code that uses it.
What is LINQ in C#
A built-in query language for C# that lets you query collections using readable syntax.
var filteredUsers = from user in users
where user.Id == desiredId
select user;
What is the benefit of using LINQ?
Makes it easy to filter, sort, and transform data within your code.
What is an async method? Why is it good?
An async method runs tasks without blocking the main thread,
Simplifies asynchronous programming by letting you write code that waits for tasks to complete without blocking the main thread.
Improves responsiveness
What does the await keyword do?
await keyword tells the method to wait for a task to finish without freezing the application.
Are arrays fixed size in C#
Yes they are. Use a list instead. Otherwise you’ll have to use the 2 pointer technique and we don’t like that one.
What is Single Responsibility Principle?
It means a class or module should focus on one specific task—grouping similar tasks together and keeping unrelated ones separate—so if its purpose changes, only that part of the code needs updating.
Example:
Instead of one class handling both user authentication and email notifications, create separate classes—one for authentication and one for sending emails.
This way, if you need to change authentication, you don’t affect the email logic.
What is the Open Closed Principle?
It means that a class or module should be designed to allow new features to be added without changing its existing code, keeping the system stable while making it easy to extend.
It means a class is “open” to new features but “closed” to changes.
Example: In a drawing app, have a common “draw()” method in a Shape interface.
Each shape (Circle, Square, etc.) implements its own draw().
Adding a new shape means creating a new class—no changes to existing code.
In a drawing app, define a Shape interface with a draw() method.
To add a new shape like Triangle, create a new Triangle class that implements Shape instead of modifying the existing drawing code.
What is an interface?
It’s a contract that specifies methods a class must implement, without defining how they’re done. For example, a Shape interface might require a draw() method, and each shape (like Circle or Square) provides its own version of draw().
How do interfaces support the Open/Closed Principle?
Interface = Remote Rules (Needs Power button)
* TV (Old Code) uses any remote with that button.
* Make New Remote (New Code) with Power button.
* Result: TV doesn’t change!
* ✅ Add New Remote (Open)
* ❌ Don’t Change TV (Closed)
What is the Liskov Substitution Principle?
It means that objects of a subclass should be replaceable with objects of the superclass without breaking the program. Subclasses must honor the contract of their parent classes so they work seamlessly in any context expecting the base class.
So a CEO doesn’t have a manager, so they don’t have all of the attributes a Employee or a Manager would for example thus we use Interfaces like IEmployee IManaged IManager to break it down. Need to practice this one I think. Goal is to learn to use Inheritance correctly.
What is the Interface Segregation Principle?
It means don’t force a class to implement methods it doesn’t need. Instead, split large interfaces into smaller, specific ones so that clients only depend on what they use. You can then combine these as required so that when you create objects you have access to the attributes you need to set.
What is the Dependency Inversion Principle?
Depend on ABSTRACTIONS (roles/interfaces),
not concrete DETAILS. Lets you SWAP parts.
Instead of THIS inside your class:
self.notifier = EmailNotifier() # BAD! Hardcoded!
Do THIS (pass the notifier IN):
# Somewhere else: notifier = EmailNotifier() OR SmsNotifier()
worker = Worker(notifier) # GOOD! Flexible!
What is a component in react?
A reusable piece of UI that returns JSX. (Javascript XML)
const Hello = () => {
return <h1>Hello, world!</h1>;
}
// Functional component (Preferred)
const Hello = () => <h1>Hello, world!</h1>;
What is Javascript XML in React?
Definition: JSX is HTML-like syntax in JavaScript that lets you build React components.
Key Points: Write UI in a familiar, declarative style.
Use curly braces { } to embed JavaScript.
const Greeting = () => {
const name = “Alice”;
return <h1>Hello, {name}!</h1>;
};
What are Props in ReactJS?
Read-only inputs passed from a Parent component down to a Child component.
(Like function arguments for components).
// Child component: receives & uses props
function Greeting(props) {
// Access data via props object (e.g., props.name)
return <h1>Hello, {props.name}!</h1>;
}
// Parent component: defines & passes data via props
function App() {
const user = “Bob”; // Data to pass down
return (
<div>
{/* Pass data to Greeting via the ‘name’ prop */}
<Greeting name={user} />
</div>
);
}
/* Output:
<h1>Hello, Bob!</h1>
*/
What is State in React?
Definition:
State gives component’s memory (for data) that can change and affect the UI when updated.
Usage:
Managed with useState in functional components
e.g. Show Password Visibility
const [show, setShow] = useState(false); // State: false means hidden
<input type={show ? “text” : “password”} />
// When state is updated (onClick)
// TRUE type = text
// FALSE type = password
<button onClick={() => setShow(!show)} > {show ? “Hide” : “Show”}
</button>
What is Event Handling in React?
Definition:
React uses camelCase event names (e.g., onClick, onChange) and expects functions instead of strings.
Key Points:
\+ Uses synthetic events for cross-browser consistency. \+ Often used to update state or handle user interactions.
// Button click updates state
<button onClick={() => setCount(count + 1)}>Increment</button>
// Input change updates state
<input onChange={e => setText(e.target.value)} value={text} />
What is Conditional Rendering in React?
Definition:
Displaying elements based on conditions using JavaScript inside JSX.
Examples:
Using a ternary operator:
{isLoggedIn ? <Dashboard></Dashboard> : <LoginPage></LoginPage>}
Using logical AND:
{errorMessage && <div className="error">{errorMessage}</div>}
What are Lists and Keys used for in React?
Lists:
Render arrays of data into JSX elements using methods like Array.map().
Keys:
Provide a unique identifier for each element in a list to help React track changes efficiently.
Example:
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
What are controlled components in React forms?
Definition:
Controlled components are form elements whose values are driven by React state. React acts as the single source of truth.
Key Points:
The input’s value comes from state. An onChange handler updates the state when the user types.
Example:
const [name, setName] = useState(“”);
<input value={name} onChange={e => setName(e.target.value)} />
Now, the name state always reflects the input’s value.
What is “Lifting State Up” in React and how is it used?
Definition:
Moving shared state to the closest common parent component.
How It Works:
The parent holds the state and passes it (and updater functions) down via props.
Example:
// Parent component:
function Parent() {
const [list, setList] = useState([]);
return (
<div>
<Child onAddItem={item => setList([…list, item])} />
{/* Other components can use ‘list’ */}
</div>
);
}
// Child component:
function Child(props) {
return (
<button onClick={() => props.onAddItem(“New Item”)}>
Add Item
</button>
);
}
What is the Context API in React and how is it used?
Definition:
Shares values (data, functions) globally without prop drilling.
Usage Steps:
Create a context: const MyContext = React.createContext(null); Wrap a parent with <MyContext.Provider value={...}> Access the context in any child with useContext(MyContext)
Example:
// Provider at a high level:
<MyContext.Provider value={userObject}>
<App></App>
</MyContext.Provider>
// In a child component:
const user = useContext(MyContext);
console.log(user.name);
What is useEffect in React?
Purpose:
Run side effects (e.g., data fetching, subscriptions, DOM updates) after render.
Key Point:
Use a dependency array ([] runs once on mount; [vars] re-runs when vars change).
Example:
get some data and when that api finishes you pass that to the useState
What is useRef in React?
Purpose:
Create a mutable reference that persists across renders; commonly used to access DOM elements.
Key Point:
Updating a ref does not trigger a re-render.
Example:
const inputRef = useRef(null);
<input ref={inputRef} type=”text” />
<button onClick={() => inputRef.current.focus()}>Focus Input</button>
How to create a char array from a string c#
char[] charArray = myString.ToCharArray();
Adding a character to a string c#
string result = myString + myChar;
(concatenation)
Accessing the first character of a string c#
char firstChar = myString[0];
Getting the length of a string c#
int len = myString.Length;
Creating a map/dictionary in C#
Dictionary<string, int> map = new Dictionary<string, int>();
Checking if a dictionary key exists c#
if (map.ContainsKey(“key”)) { /* … */ }
Creating a substring from a string c#
string sub = myString.Substring(startIndex, length);
How to iterate through a dictionary c#
foreach (var entry in map)
{
Console.WriteLine($”Key: {entry.Key}, Value: {entry.Value}”);
}
Which Leetcode questions should we prepare using
**26. Remove Duplicates from Sorted Array (Easy) – Fundamental array manipulation.
**
**27. Remove Element (Easy) – Practice with in‑place removal in arrays.
**
88. Merge Sorted Array (Easy) – Merging two sorted arrays.
- Majority Element (Easy) – Simple frequency counting in arrays.
- Best Time to Buy and Sell Stock (Easy) – Basic array analysis.
- Rotate Array (Medium) – Array rotation logic.
- Roman to Integer (Easy) – String parsing and conversion.
- Longest Common Prefix (Easy) – Common string processing pattern.
- Valid Palindrome (Easy) – Two-pointer technique on strings.
- Two Sum II – Input Array Is Sorted (Medium) – Two-pointer approach with sorted arrays.
- Container With Most Water (Medium) – Two pointers and optimization.
- Longest Substring Without Repeating Characters (Medium) – Sliding window technique.
- Valid Sudoku (Medium) – Matrix and hash map usage.
- Set Matrix Zeroes (Medium) – Matrix manipulation in place.
- Ransom Note (Easy) – Using hash maps for frequency counts.
- Two Sum (Easy) – Classic hash map problem.
- Linked List Cycle (Easy) – Linked list cycle detection.
- Add Two Numbers (Medium) – Linked list arithmetic.
- Same Tree (Easy) – Basic binary tree recursion.
- Maximum Depth of Binary Tree (Easy) – Understanding tree traversal.
- Number of Islands (Medium) – Grid/graph traversal using DFS/BFS.
- Search Insert Position (Easy) – Binary search fundamentals.
- Palindrome Number (Easy) – Math and string conversion.
- Plus One (Easy) – Array manipulation (carry-over logic).
- House Robber (Medium) – Introductory dynamic programming.
What command to create new dotnet console application?
dotnet new console -n enternamehere
What commands to add entity framework design and SQLServer
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
What is the N+1 query issue in Entity Framework Core?
For bonus points how can you avoid it.
It’s when you grab a list (e.g., users) with 1 query, then run extra queries (e.g., for each user’s orders), totaling N+1 queries. Too many queries = slow!
Why It Happens:
Lazy Loading: EF Core auto-fetches related data (like orders) when you use it, triggering a query per item.
Manual Loading: You loop and fetch related data one by one, adding more queries.
To avoid:
Eager Loading: you can use eager loading with methods like .Include() to fetch both the main entities and their related data in a single, efficient query.
Give an example of Eager loading in code, how would you use the .Include() ?
var users = await context.Users
.Include(u => u.Orders) // Load orders in the same query
.ToListAsync();
How can we also deal with N+1 problem and why is it using Split Queries?
Goal: Avoid Cartesian explosion by splitting the query into multiple SQL statements.
.AsSplitQuery()
var users = await context.Users
.Include(u => u.Orders)
.AsSplitQuery() // Split into multiple queries
.ToListAsync();
What Happens:
EF Core runs 2 separate queries:
SELECT * FROM Users SELECT * FROM Orders WHERE UserId IN (1, 2, 3...)
Pros:
Avoids data duplication (no JOIN).
Better for queries with multiple Include() or ThenInclude() calls.
Cons:
Slightly more roundtrips to the database.
What does ACID stand for?
A - Atomicity - All or nothing (succeeds or it fails)
C - Consistency - Database should stay consistent, reflecting a real world logical state.
I - Isolation - One transaction at a time / don’t interfere with each other
D - Durability - Once a change is committed its changes are permanent and will survive a system failure. (writing to hard drives)
“Explain Atomicity with a bank transfer example.”
You don’t transfer only some money if it fails midway you have to transfer all the money to the account.
“Why is Consistency crucial for application data integrity?”
Consistency is crucial as the database needs to reflect real world state.
“What concurrency problem does Isolation solve?”
Isolation stops the concurrency problem called Lost Update where one transaction would be overwritten by another
“What guarantee does Durability provide after a transaction commits?”
Saves it to solid storage such as a hard drive for persistence so that in event of system failure the data still exists
What are the requirements for 1NF?
One Value Per Box: Each cell in your table gets only one piece of info (no lists!).
Unique Rows: Every row needs a unique ID (a primary key).
No Repeating Columns: Don’t have columns like Class1, Class2, Class3. Put repeating stuff in a separate, related table.
What is a partial dependency, and which normal form eliminates it (2NF)? Provide an example
What it is: A non-key field depends on only part of a composite primary key (a key made of multiple columns), not the whole key.
Which NF eliminates it: Second Normal Form (2NF).
Example:
Imagine a table OrderDetails with a primary key made of (OrderID, ProductID).
Columns: OrderID, ProductID, Quantity, ProductName.
Here, ProductName depends only on ProductID (just part of the key). It doesn’t care about the OrderID. This is a partial dependency.
2NF Fix: Move ProductName to a separate Products table with ProductID as its key. The OrderDetails table would then only have OrderID, ProductID, and Quantity.
What is a transitive dependency, and which normal form eliminates it (3NF)? Provide an example.
What it is: A non-key field depends on another non-key field, which in turn depends on the primary key. Think of it like a chain reaction: Key -> Non-Key A -> Non-Key B.
Which NF eliminates it: Third Normal Form (3NF).
Example:
Imagine a Students table with StudentID as the primary key.
Columns: StudentID, AdvisorID, AdvisorOfficeNumber.
Here, AdvisorOfficeNumber depends on AdvisorID (a non-key field), and AdvisorID depends on StudentID (the key). The dependency StudentID -> AdvisorID -> AdvisorOfficeNumber is a transitive dependency.
3NF Fix: Move AdvisorOfficeNumber to a separate Advisors table with AdvisorID as its key. The Students table would then only have StudentID and AdvisorID.
What are the requirements for 2NF?
Must be 1NF First: Fix 1NF issues before worrying about 2NF.
No Partial Dependencies: Non-key fields must depend on the entire primary key (especially important if your key is made of multiple columns). No field should depend on just part of the key.
What are the requirements for 3NF?
Must be 2NF First: Fix 2NF issues before worrying about 3NF.
No Transitive Dependencies: Non-key fields must depend only on the primary key, not on other non-key fields. (If changing non-key Field B means you also have to change non-key Field C, that’s a transitive dependency you need to fix).
Why 204 No Content (not 200 OK) for PUT:
PUT means the client sent the full desired state.
200 OK usually sends data back. Client doesn’t need the same data sent back.
204 No Content = “Success, I did it, nothing more to send.” It’s more efficient and standard for PUT.
Ok() / Ok(value)
Code: 200 OK
Use: General success (esp. GET w/ data).
NotFound() / NotFound(value)
Code: 404 Not Found
Use: Resource doesn’t exist.
BadRequest() / BadRequest(error)
Code: 400 Bad Request
Use: Invalid client request (bad data/validation).
NoContent()
Code: 204 No Content
Use: Success, no data back (good for PUT/DELETE).
CreatedAtAction() / CreatedAtRoute()
Code: 201 Created
Use: Successful POST. Returns Location header + new item.
Unauthorized()
Code: 401 Unauthorized
Use: Authentication needed (login).
Forbid()
Code: 403 Forbidden
Use: Logged in, but no permission for this action.
Problem()
Code: Usually 500 Internal Server Error
Use: Unexpected server error (catch blocks).
Conflict()
Code: 409 Conflict
Use: Request conflicts with server state (e.g., duplicate unique item).