Friday, December 19, 2025

mock interview .net up to 2 years experiences

Tuesday, October 21, 2025 60 دقائق قراءة 133 مشاهدة

In this article you’ll find a collection of the most common interview questions for .NET Core with SQL Server. What makes this one different is its coverage and simplicity — most articles stop at 10 questions with heavy explanations, but here you’ll get a wider, clearer view without overcomplicating things. It’s designed especially for developers with up to 2 years of experience. At the end of this article, you’ll also find real cases for the most common problems, so you can see how the theory actually applies in practice.

Preparing for a .NET developer interview can feel overwhelming, especially if you’re in the early stages of your career. Interviewers usually focus on testing your fundamentals: databases, C# concepts, OOP principles, ASP.NET Core basics, and some hands-on coding challenges.

This article is designed as a Mock Interview Guide, covering the most common questions you might face as a junior .NET developer (up to 2 years of experience).

We’ll move step by step across the main topics:

  • Databases
  • LINQ and Entity Framework Core
  • C# & OOP Concepts
  • ASP.NET Core and APIs
  • devops and cloud


Think of this as a mock interview flow — starting with databases and working our way into coding and application-level concepts.


What is SQL Relational and what’s the difference with NoSQL?

SQL is fundamentally Relational and Schema-based. This means data is organized into tables with fixed rows and columns (a predefined schema), and relationships are explicitly defined using keys (like Primary and Foreign keys

for examples :SQL Server, MySQL


no sql or Non-Relational:, is an umbrella term for database systems that do not use the traditional tabular relational model.

Data Models: Instead of tables, they use various models:

  • Document: Stores data in JSON-like documents (e.g., MongoDB).

  • Key-Value: Simple dictionary/hash table storage (e.g., Redis).

  • Wide-Column: Data organized by column families, flexible per row (e.g., Cassandra).


What are SQL Keys? And what’s the difference between Primary Key and Unique Key?

  • SQL Keys are constraints used to uniquely identify rows in a table and establish relationships between tables.
  • Primary Key:
  • Ensures each row is uniquely identified.
  • Does not allow NULL values.
  • Only one Primary Key is allowed per table.
  • Automatically creates a clustered index (in SQL Server).
  • Unique Key:
  • Ensures uniqueness of values in a column.
  • Allows one NULL (depends on DBMS, but SQL Server allows one).
  • A table can have multiple Unique Keys.
  • Creates a non-clustered index (in SQL Server).

👉 In short:

  • Use Primary Key for the main unique identifier of a record.
  • Use Unique Key when you need other columns to also enforce uniqueness but still allow NULLs.



What is a Foreign Key and why is it important?


  • A Foreign Key is a column (or a set of columns) used to create a link between two tables.
  • It references the Primary Key of another table, ensuring that data between tables remains consistent and valid.
  • It enforces Referential Integrity — meaning you can’t insert a record in a child table that doesn’t exist in the parent table.

👉 Example in concept:

If you have a Students table and a Departments table, the DepartmentId in Students would be a Foreign Key that references Departments.Id.



What’s the difference between TRUNCATE, DELETE, and DROP in SQL?

  • DELETE:
  • Removes specific rows from a table using a WHERE clause.
  • Can be rolled back if used inside a transaction.
  • Triggers are fired.
  • Slower on large tables because it logs each row deletion.
  • TRUNCATE:
  • Removes all rows from a table without logging each row individually.
  • Cannot use WHERE clause.
  • Faster than DELETE on large tables.
  • Usually cannot be rolled back in some DBMS.
  • Resets auto-increment/identity counters.
  • DROP:
  • Completely removes the table (or database) from the database.
  • Cannot be rolled back.
  • Table structure and data are gone permanently.


What are the different types of SQL commands?


  1. DDL – Data Definition Language
  • Commands that define or modify database structure.
  • Examples:
  • CREATE → create a table, database, or index
  • ALTER → modify table structure
  • DROP → delete table or database
  1. DML – Data Manipulation Language
  • Commands that deal with data inside tables.
  • Examples:
  • SELECT → read data
  • INSERT → add data
  • UPDATE → modify existing data
  • DELETE → remove data
  1. DCL – Data Control Language
  • Commands to control access and permissions.
  • Examples:
  • GRANT → give privileges
  • REVOKE → remove privileges
  1. TCL – Transaction Control Language
  • Commands to manage transactions.
  • Examples:
  • COMMIT → save changes
  • ROLLBACK → undo changes
  • SAVEPOINT → mark a point in a transaction



What are CHAR and VARCHAR in SQL? What’s the difference? What is Unicode?


CHAR(n):

  • Fixed-length string.
  • Always takes up n characters, padding with spaces if the value is shorter.
  • Good for consistent-length data, e.g., country codes.

VARCHAR(n):

  • Variable-length string.
  • Only uses as much space as the string actually has, up to n characters.
  • Good for dynamic-length data, e.g., names, emails.



Unicode:

  • Standard for representing text in multiple languages.
  • SQL data types: NCHAR, NVARCHAR → store Unicode characters.
  • Allows storing Arabic, Chinese, emojis, etc. without issues.


What’s the difference between WHERE and HAVING? How does GROUP BY work?

  • WHERE:
  • Filters rows before any grouping happens.
  • Works on individual rows.
  • GROUP BY:
  • Groups rows that have the same values in specified columns.
  • Often used with aggregate functions like COUNT, SUM, AVG, etc.
  • HAVING:
  • Filters after the grouping is done.
  • Used to filter aggregated results.

Example in concept:

  • WHERE → “Give me students with Age > 18” → filters individual rows first.
  • GROUP BY → “Group students by DepartmentId” → aggregates rows by department.
  • HAVING → “Show only departments with more than 10 students” → filters after aggregation.



What is the purpose of the DISTINCT keyword in SQL, and how does it differ from GROUP BY?

The DISTINCT keyword in SQL is used to remove duplicate rows from the result set. When you use it, SQL checks for duplicate values in the selected columns and returns only unique combinations.

However, GROUP BY is more powerful — it not only groups identical values together but also allows you to perform aggregate calculations like COUNT(), SUM(), AVG(), etc.


In short:

  • DISTINCT → removes duplicates, shows unique records only.
  • GROUP BY → groups data and allows performing aggregations.

Performance-wise, GROUP BY is slightly heavier because it performs grouping operations, while DISTINCT is simpler and just eliminates duplicates.




What is a JOIN and its types?

 them. Imagine you have student data stored in one place and department data stored somewhere else. If you want to display the student’s name along with their department, you need to link the two — that’s where JOIN comes in.

  • INNER JOIN: Returns only rows that have matching values in both sources. For example, only students who actually belong to a department will appear.
  • LEFT JOIN: Returns all rows from the left table, even if there’s no match in the right table. Missing values are filled with NULL.
  • RIGHT JOIN: Same as LEFT JOIN, but returns all rows from the right table instead.
  • FULL JOIN: Returns all rows from both sides, whether or not there’s a match.
  • CROSS JOIN: Combines every row from the first table with every row from the second table. It’s mostly used in special cases or calculations.


What’s the difference between a Nested Query (Subquery) and a JOIN?


A Nested Query or Subquery is a query inside another query. First, it produces a result, and then that result is used as a condition in the main query. For example, a subquery might first fetch all departments named "IT," and then the main query fetches all students belonging to those departments.

A JOIN, on the other hand, fetches all the data together in one go, without an inner query. This usually makes the query faster and the results more straightforward.

Key differences:

  • Performance: JOINs are usually faster; subqueries can slow down with large datasets.
  • Readability: JOINs are direct and clear; subqueries can be a bit harder to read because of the nested structure.
  • Usage: Use JOIN when you want to combine data from multiple tables. Use a subquery when you need a specific result as a condition.




What is Database Normalization? Why is it important?

Normalization is a structured way to organize data in a database so it’s clean, efficient, and consistent.

The main idea behind it is avoiding redundancy (repeated information) and maintaining data integrity (keeping everything accurate and reliable).

Imagine you have one big messy table that stores everything — students, departments, courses, and addresses — all in one place.

Soon you’ll notice problems:

  • The same department name repeats 100 times.
  • If one department changes its name, you have to update it everywhere.
  • You risk inconsistent data (like “Computer Science” in one place and “Comp Sci” in another).

Normalization solves this by dividing data into smaller logical tables, where each table focuses on one topic (students in one, departments in another, etc.), and linking them with relationships using Primary Keys and Foreign Keys.

Let’s break it down simply — each “form” is like a step to make the database cleaner:

1️⃣ First Normal Form (1NF):

  • Every column must have atomic values (only one piece of information, not a list or multiple values).
  • Each record (row) is unique.
  • No repeating columns (like phone1, phone2, phone3).

Think of it as: “Make it clean — one cell, one value.”

2️⃣ Second Normal Form (2NF):

  • It must already satisfy 1NF.
  • And every non-key column must depend on the whole primary key, not just part of it.
  • This mostly matters when you have composite keys (primary key made of more than one column).

The idea here: “Don’t mix columns that belong to different entities.”

3️⃣ Third Normal Form (3NF):

  • Must already be in 2NF.
  • And there should be no transitive dependency — meaning, one non-key column shouldn’t depend on another non-key column.

Example idea: if a “Student” table stores both “City” and “ZipCode,” and ZipCode determines the City, that’s a transitive dependency — better move “City” and “ZipCode” to a separate table.

When not to over-normalize:

While normalization is great for keeping data accurate, it can sometimes make queries slower — especially in reporting or analytics — because you need to join many tables together.

So in real-life systems, sometimes developers use denormalization to improve performance (they keep a few calculated or repeated fields intentionally).



 How do you improve SQL query performance?


Improving SQL performance is all about reducing how much data SQL has to scan and helping it find what it needs faster.

There isn’t one magic trick — it’s about combining multiple small optimizations that make a big difference.

1️⃣ Use Indexes wisely

An Index works like the index in a book — it helps SQL Server find data faster without scanning every row.

For example, if you search by StudentId a lot, putting an index on that column means SQL can jump directly to the right record instead of checking all rows.

🧠 Note:

Indexes improve read speed but can slow down writes (INSERT, UPDATE, DELETE), because every change has to update the index too.

So use them only on frequently searched columns.

*2️⃣ Avoid SELECT ***

Always select only the columns you need.

When you use SELECT *, SQL loads unnecessary data from disk to memory — wasting time and resources.

3️⃣ Use WHERE filters early

Filtering data early helps SQL work on a smaller dataset.

If you can filter before joining or grouping, do it — it saves processing time.

4️⃣ Optimize JOINS

Make sure you join tables on indexed columns and use the right type of JOIN.

For example, INNER JOINs are usually faster than FULL JOINs because they return fewer rows.

5️⃣ Avoid too many Subqueries

Sometimes Subqueries cause SQL to re-run the same logic many times.

Using a JOIN or a temporary table can be more efficient in those cases.

6️⃣ Check Execution Plans

SQL Management Studio (SSMS) can show the Execution Plan, which tells you what’s slowing down your query — like table scans, missing indexes, or inefficient joins.

Developers who know how to read an execution plan stand out in interviews 👀

7️⃣ Keep statistics updated

SQL uses internal statistics to decide the best way to execute a query.

If they’re outdated, it might pick a slow plan — so updating them regularly improves performance.

8️⃣ Avoid unnecessary DISTINCT, ORDER BY, and LIKE '%...%'

These operations are costly because they force SQL to sort or scan everything.

Only use them when really needed.

In short:

The goal isn’t to make the query look fancy — it’s to make SQL do less work.


What is an Index in SQL, and how does it improve query performance?

An Index in SQL is a special data structure that helps the database find rows much faster, without scanning the entire table.

You can think of it like an index in a book — instead of checking every page, you jump directly to the page number that contains your topic.

Indexes are especially useful in large tables where searching, filtering, or joining data happens frequently.

For example, when a query filters rows based on conditions in a WHERE clause or uses columns in JOIN or ORDER BY, the database uses the index to locate matching rows quickly.

Internally, most databases store indexes using a B-tree or balanced tree structure, which keeps data sorted and allows for very fast lookups.

However, indexes are not free — they improve read performance but can reduce write performance (because every time you insert, update, or delete data, the index also needs to be updated).

They also consume extra disk space.

So, the best practice is to create indexes only on columns that are frequently used in searching, filtering, or joining — not on every column.




how you doing pagination in SQL?


Pagination means splitting large data sets into smaller pages so the user doesn’t see everything at once and to reduce server load.

How to do it in SQL?

  • Usually we use OFFSET and FETCH / LIMIT depending on the database type.
  • Idea: specify where to start (OFFSET) and how many rows to fetch (LIMIT/FETCH).
  • Analogy: you have a book with 1000 pages, and the user wants to see 10 pages at a time → you fetch the page number they requested.

Why use it?

  • Performance improvement: don’t fetch all data at once.
  • Better user experience: faster and lighter pages.
  • Essential for APIs when results are large.


1️⃣ OFFSET / FETCH:

  • Use Case:
  • Small to medium tables.
  • When high-speed pagination isn’t critical.
  • Pages are predefined and data doesn’t change much during browsing.
  • Pros:
  • Easy to implement.
  • Good for dashboards or small reports.
  • Cons:
  • Slow for very large tables, especially on later pages.
  • Dynamic inserts/deletes can shift rows, causing duplicates or skipped rows.

2️⃣ Keyset / Seek Method:

  • Use Case:
  • Very large datasets (millions of rows).
  • When fast, consistent page load is needed.
  • Suitable for real-time browsing with frequently changing data.
  • Pros:
  • Fast and lightweight.
  • Safe with dynamic data changes.
  • Cons:
  • Less flexible with complex ordering.
  • Requires a stable ordering column (usually ID or timestamp).

3️⃣ ROW_NUMBER():

  • Use Case:
  • Flexible ordering by any column(s).
  • Pagination with grouped data using Partition.
  • Pros:
  • Very flexible and suitable for complex analytics.
  • Cons:
  • Can be slower than Keyset on very large tables.


ROW_NUMBER() is a SQL function that assigns a sequential number to each row based on a specified order.

Idea:

  • When doing pagination, you can assign a number to each row.
  • Then you select the rows you want to display based on that number (e.g., rows 11–20 for page 2).

Advantages:

  • Flexible: you can order by any column(s).
  • Useful if you don’t want to use OFFSET/FETCH or Keyset Pagination.
  • Can be combined with Partitioning to handle independent groups (e.g., per user).




so What are the different types of Indexes in SQL and when do you use each?

  1. Clustered Index
  • A clustered index defines the physical order of data in a table — meaning the table data is stored based on the index key.
  • Each table can have only one clustered index because the data itself can only be sorted one way.
  • It’s best for columns that are frequently searched in range queries or used for sorting (like OrderDate or EmployeeID).
  • Example use: finding all records between two dates efficiently.
  1. Non-Clustered Index
  • This index doesn’t change the physical order of the data. Instead, it creates a separate structure that points to the location of data rows.
  • You can have multiple non-clustered indexes on a table.
  • Useful for columns frequently used in WHERE clauses or JOINs but not necessarily for sorting.
  1. Unique Index
  • Ensures that all values in the indexed column are unique.
  • It’s automatically created when you define a PRIMARY KEY or UNIQUE constraint.
  • Used when you need both fast lookups and data integrity.
  1. Composite Index (Multi-column Index)
  • Built on two or more columns together.
  • Useful when queries often filter or sort by multiple columns in combination.
  • For example, searching by both FirstName and LastName together.
  1. Full-Text Index
  • Used for searching textual data — especially when you need to find specific words or phrases inside large text columns.
  • Ideal for features like “search by keyword” in blogs or document systems.

Each index type helps in different ways, but the goal is always the same — to improve data retrieval speed without overloading write operations.



What’s the difference between a Clustered Index and a Non-Clustered Index?


A Clustered Index defines the physical order of data in a table.

This means the table’s data rows are actually stored on disk in the same order as the index key. Because of that, a table can have only one clustered index — it determines how the entire table is physically organized.

When you search for data using a clustered index, the database goes directly to the exact location of the data since it’s already sorted in that order.


It’s usually created on primary key columns or columns that are frequently sorted or used in range queries (like OrderDate).

A Non-Clustered Index, on the other hand, does not affect the physical order of data.

It creates a separate structure that contains the indexed column and a pointer (or reference) to the actual data row in the table.

You can have multiple non-clustered indexes in a single table.

They are used to improve performance for queries that often filter or join on non-primary key columns.


✅ In short:


Clustered Index : Data is stored in index order, allow Only one per table faster for range queries uses for Primary key, sorting columns.



Non-Clustered Index: Index stored separately, allow Multiple per table and slightly slower (needs lookup), uses for WHERE or JOIN columns.



When should you avoid creating too many indexes on a table?

You should avoid creating too many indexes when your table is frequently updated or modified, because each index adds extra work during write operations.

Every time you perform an INSERT, UPDATE, or DELETE, the database must also update all related indexes to keep them in sync with the data.

This increases overhead and can significantly slow down write performance.

In addition, each index consumes storage space and increases the time required for maintenance operations like backups and rebuilds.

Another common issue is index fragmentation — when data changes cause indexes to become inefficient, leading to slower queries over time.

That’s why best practice is to:

  • Create indexes only on columns used frequently in WHERE, JOIN, and ORDER BY clauses.
  • Avoid indexing columns that change very often (like LastLoginTime or ModifiedDate).
  • Periodically review and tune your indexes using execution plans and performance reports.

In short:

Indexes speed up reads but slow down writes — balance them carefully based on how your data is used.




What is Index Fragmentation and how can you fix it?


Index Fragmentation happens when the logical order of pages in an index no longer matches their physical order on disk.

In simple terms, the data becomes “scattered” — so when SQL Server reads the index, it has to jump around the disk instead of reading pages sequentially.

There are two main types of fragmentation:

  1. Internal Fragmentation:
  • Occurs when data pages have empty space due to frequent inserts, updates, or deletes.
  • The page isn’t full, so it wastes space and reduces read efficiency.
  1. External Fragmentation:
  • Happens when the order of index pages on disk is not sequential, causing extra disk reads (like reading random pages instead of a smooth flow).

Fragmentation reduces performance, especially for large range queries or sequential scans.

🧩 How to Fix It:

There are two main ways to fix index fragmentation:

  1. REORGANIZE the index – It’s a light operation that defragments indexes logically and reorders the leaf pages.
  • Use it when fragmentation is between 5% and 30%.
  1. REBUILD the index – This recreates the index completely, physically reordering the pages and removing fragmentation.
  • Use it when fragmentation is above 30%.
  • It’s heavier and takes more time, but gives the best results.

You can check fragmentation using SQL Server’s system views like

sys.dm_db_index_physical_stats.



What is a Transaction in SQL? Explain ACID properties


🇬🇧 English Explanation:

A Transaction in SQL is a set of SQL operations that are executed as a single unit of work.

It ensures that either all operations succeed or none of them do, maintaining data integrity.

The main goal of a transaction is to keep the database in a consistent state — even if there’s a crash, error, or power failure.

🔑 ACID Properties:

  1. Atomicity
  2. All operations in a transaction must complete successfully; if one fails, the whole transaction is rolled back.
  3. (“All or nothing” rule)
  4. Consistency
  5. The database must move from one valid state to another valid state. Data integrity rules must never be violated.
  6. Isolation
  7. Each transaction runs independently. One transaction’s changes are not visible to others until it’s committed.
  8. Durability
  9. Once a transaction is committed, the changes are permanent — even if the system crashes immediately after.



What are SQL functions? What are their types?

An SQL Function is a predefined operation that performs a specific task and returns a value.

The main idea is to simplify data manipulation — allowing you to perform calculations, transformations, or conversions directly inside your SQL queries instead of writing extra logic in your application code.

So instead of handling data in C# or your backend, you can use SQL functions inside the SELECT statement to format, convert, calculate, or process values easily.

Example:

SELECT UPPER(name), ROUND(salary, 2) FROM employees;

👉 This converts the employee name to uppercase and rounds the salary to two decimal places.

🔸 Types of Functions in SQL

There are mainly two built-in types plus one user-defined category:

1️⃣ Single Row (Scalar) Functions

These functions operate on each row individually and return one value per row.

So if you have 10 rows, you’ll get 10 results.

Common categories:

🧩 String Functions:

  • UPPER() → Converts text to uppercase
  • LOWER() → Converts text to lowercase
  • CONCAT() → Joins two or more strings
  • LEN() → Returns the length of a string
  • SUBSTRING() → Extracts part of a string

🧩 Numeric Functions:

  • ROUND() → Rounds a number
  • ABS() → Returns the absolute value
  • POWER() → Raises a number to a power
  • CEIL() / FLOOR() → Rounds a number up or down

🧩 Date Functions:

  • GETDATE() → Returns the current date and time
  • YEAR(), MONTH(), DATEDIFF() → Work with date parts or calculate date differences

🧩 Conversion Functions:

  • CAST(), CONVERT() → Change data types (e.g., number → string)

🧩 System Functions:

  • USER_NAME() → Returns the current username
  • DB_NAME() → Returns the current database name

Example:

SELECT UPPER('osama');

Result → "OSAMA"

2️⃣ Multi-row (Aggregate) Functions

These functions operate on a group of rows and return one result per group or per table.

For example, if you have 100 employees, you can calculate their total salaries or average pay.

Common examples:

  • COUNT() → Counts the number of rows
  • SUM() → Adds up values
  • AVG() → Calculates average
  • MAX() / MIN() → Finds the highest or lowest value

Example:

SELECT COUNT(*) FROM employees;

Result → total number of employees in the table.

3️⃣ User-Defined Functions (UDFs)

A User-Defined Function is a custom function created by the user to perform a specific logic and return either a single value or a table.

You can use UDFs inside SELECT, WHERE, or even JOIN statements — just like built-in functions.

In SQL Server, UDFs are of three types:

TypeDescriptionScalar FunctionReturns a single value (like text or number).Inline Table-Valued Function (iTVF)Returns a table generated from one single query.Multi-Statement Table-Valued Function (mTVF)Returns a table after executing multiple SQL statements inside the function.

🧠 Summary:

In SQL, a Function is used to perform a specific operation and return a result — either on each row or on a whole group of row




What is a Stored Procedure, and what’s the difference between a Procedure and a Function in SQL?


A Stored Procedure is a precompiled set of SQL statements stored in the database.

It’s used to perform a specific task or a series of operations, such as inserting, updating, or validating data.

You can think of a stored procedure like a mini program inside your database. It can:

  • Take input parameters
  • Perform complex logic (including loops, conditions, and transactions)
  • And optionally return data or status messages

Stored Procedures are usually used to:

  • Improve performance (since they’re precompiled)
  • Encapsulate business logic inside the database
  • Enhance security, by limiting direct access to tables



⚖️ Difference Between Function and Stored Procedure

A Function and a Stored Procedure in SQL might look similar — both store reusable logic —

but they serve different purposes and behave differently.

🎯 Purpose

  • Function: mainly used to return a value (or result) that you can use inside a query, for example inside SELECT or WHERE.

Stored Procedure: used to perform actions like INSERT, UPDATE, DELETE, or even execute multiple statements in sequence.



📤 Return Type

  • Function: must return a value — either a single value or a table (if it’s table-valued).
  • Stored Procedure: may return zero, one, or multiple results, or even just execute logic without returning anything.

🔗 Usage in SQL

  • Function: can be used inside SELECT, WHERE, or JOIN statements.
  • Stored Procedure: cannot be directly used inside a SELECT — you must call it separately using EXEC or EXECUTE.

🔄 Transactions

  • Function: cannot handle transactions like BEGIN TRAN, COMMIT, or ROLLBACK.
  • Stored Procedure: can handle them — perfect for controlling complex data changes safely.

⚙️ Parameters

  • Function: accepts only input parameters.
  • Stored Procedure: can have input, output, or both, giving it more flexibility for passing data in and out.

🚀 Performance

  • Function: lightweight — usually used for quick calculations or formatting data.
  • Stored Procedure: heavier — used for complex business logic or multi-step operations.




What is a Trigger in SQL? When do we use it?


A Trigger is a special type of stored procedure that automatically runs (or “fires”) when a specific event happens in the database.

That event can be an INSERT, UPDATE, or DELETE operation on a table.

In other words — a trigger is event-driven, not manually executed.

Main uses of triggers:

  • To enforce business rules automatically
  • To maintain data integrity across tables
  • To log changes or track audits
  • To prevent invalid data from being inserted or deleted

There are different types of triggers depending on when they run:

  • AFTER Trigger: runs after an INSERT, UPDATE, or DELETE
  • INSTEAD OF Trigger: runs instead of the action (useful for views)
  • BEFORE Trigger: in some databases (like MySQL), runs before the event

But — triggers should be used carefully, because:

  • They can slow performance if they run too often
  • They make debugging harder (since they run automatically in the background)




What is a View in SQL? What’s the difference between a View and a Table?


A View in SQL is a virtual table — it doesn’t store data physically like a real table.

Instead, it stores a query definition that pulls data from one or more tables whenever you access it.

Think of it as a saved SELECT query.

When you query the view, the database executes that saved query and returns the results as if it were a table.

🔸 Why Views Are Used:

  1. Security & Access Control:
  2. You can show only specific columns or rows to users instead of giving full access to the tables.
  3. → Example: a view that shows employees' names and departments but hides their salaries.
  4. Simplify Complex Queries:
  5. You can create a view from a complex join or subquery and reuse it easily.
  6. Data Abstraction:
  7. Applications can query the view without worrying about how the data is stored internally.
  8. Consistency:
  9. When the underlying tables change, the view automatically reflects those updates.


🗃️ Storage

  • Table: physically stores data in the database — the actual records (rows and columns) are saved on disk.

View: doesn’t store any data. It’s basically a stored query definition — every time you call it, SQL runs the query and shows the result.

Performance

  • Table: faster for read and write operations (like SELECT, INSERT, UPDATE, DELETE) because the data is already stored.
  • View: slightly slower, because it has to execute the underlying query each time you access it.

✏️ Updatability

  • Table: fully updatable — you can INSERT, UPDATE, or DELETE freely.
  • View: depends on its complexity.
  • Simple views (from one table, no joins) can be updatable.
  • Complex views (joins, group by, aggregates) are usually read-only.

🔒 Security

  • Table: requires you to give direct access to the real data.
  • View: can improve security by showing only part of the data — for example, certain columns or filtered rows.

🔁 Maintenance

  • Table: you must update it manually — add, edit, or remove rows yourself.
  • View: automatically reflects changes from the base tables — since it’s based on a query, any change in the source tables appears instantly.

🧩 Summary in short:

  • Table = stores actual data physically.
  • View = virtual table (a stored query) that shows data dynamically from tables.



🧩 In short:
A Table = real storage.
A View = saved lens to look at that data differently.


What is SQL Injection, and how can you prevent it?


SQL Injection is a security vulnerability that happens when an attacker inserts (or “injects”) malicious SQL code into an application’s input fields — like login forms, search boxes, or URL parameters — to manipulate the database.

Basically, it happens when your SQL query is built using unvalidated user input.

If the app doesn’t properly handle it, the attacker can:

  • Access sensitive data (like user passwords)
  • Modify or delete tables
  • Bypass authentication
  • Even drop the entire database

💣 Example Scenario (Conceptually, not code):

Suppose the application takes user input and puts it directly inside a SQL query without checking it.

An attacker can type something malicious like:

' OR '1'='1

This tricks the SQL engine into always returning true — letting the attacker log in without a real password.



🧰 How to Prevent SQL Injection:

  1. Use Parameterized Queries (Prepared Statements)
  2. Don’t concatenate user input directly into SQL strings.
  3. Frameworks like ADO.NET, Entity Framework, or Laravel automatically handle parameters safely.
  4. Use Stored Procedures Safely
  5. Stored procedures can reduce risk if used correctly — but avoid dynamic SQL inside them.
  6. Validate and Sanitize Input
  7. Make sure user input follows the expected pattern (e.g., email format, number range, etc.).
  8. Use ORM Frameworks
  9. Like Entity Framework in .NET — they abstract queries and parameterize automatically.
  10. Least Privilege Principle
  11. Don’t give your application database user full admin rights — limit it to only what’s needed.
  12. Use Web Application Firewalls (WAF)
  13. Helps detect and block malicious requests before they reach the app.



What is LINQ?


LINQ (Language Integrated Query) is a feature in C# that allows developers to query and manipulate data directly within the C# language — without writing complex loops or SQL statements.

It provides a consistent way to work with different data sources like collections, arrays, XML, and databases using a single, easy-to-read syntax.

Simply put, LINQ helps you filter, sort, group, and transform data in a clean and expressive way.



Types of LINQ Syntax

There are two main ways to write LINQ in C#:

  1. Query Syntax – Looks similar to SQL.
  2. Example: from item in collection where condition select item
  3. It’s easier to read, especially for people familiar with SQL.
  4. Method Syntax – Uses methods and lambda expressions.
  5. Example: collection.Where(x => x > 10).OrderBy(x => x)
  6. It’s more powerful and flexible — supports chaining and complex operations.

💡 Most developers use Method Syntax in real projects because it integrates naturally with C# and supports features like Async, Include, and advanced filtering.




Types of LINQ

LINQ isn’t just one thing — it’s a unified query model that works with different data sources.

Depending on where your data comes from, there are several LINQ types:

  1. LINQ to Objects
  • Works with in-memory data like lists, arrays, or collections.
  • Example use case: filtering or sorting items in a list without touching the database.
  1. LINQ to SQL
  • Used to query SQL Server databases directly using C#.
  • Translates LINQ queries into SQL commands automatically.
  • It allows you to use strongly typed C# models instead of writing SQL manually.
  1. LINQ to Entities (Entity Framework)
  • Similar to LINQ to SQL, but works through the Entity Framework ORM.
  • It supports multiple database providers (not just SQL Server).
  • Great for larger projects that use EF Core or EF6.
  1. LINQ to XML
  • Used to read, query, and modify XML documents easily.
  • Very handy for data interchange formats.
  1. LINQ to DataSet
  • Works with ADO.NET DataSets and DataTables.
  • Useful when working with disconnected data in traditional apps.

💡 Summary:

LINQ gives a single, consistent query language to handle different data types — whether your data is in memory, in a database, or in an XML file.




LINQ Operators

LINQ operators are building blocks that let you shape, filter, and transform data in a clear, declarative way — similar to SQL keywords like SELECT, WHERE, and GROUP BY.

They’re divided into categories based on what they do:

1. Filtering Operators

Used to pick specific elements based on a condition.

👉 Common ones:

  • Where() — filters data based on a condition.
  • OfType<T>() — filters elements by data type.

2. Projection Operators

Used to transform data or pick specific fields.

👉 Common one:

  • Select() — extracts or transforms each element.

3. Sorting Operators

Used to order the results.

👉 Common ones:

  • OrderBy(), OrderByDescending(), ThenBy(), ThenByDescending().

4. Grouping Operators

Used to group data based on a key.

👉 Common one:

  • GroupBy() — groups elements that share a common attribute.

5. Joining Operators

Used to combine data from multiple collections or tables.

👉 Common one:

  • Join() — similar to SQL JOIN.
  • GroupJoin() — for hierarchical joins.

6. Aggregation Operators

Used to calculate values from a sequence.

👉 Common ones:

  • Count(), Sum(), Average(), Min(), Max().

7. Quantifier Operators

Used to check if some or all elements meet a condition.

👉 Common ones:

  • Any(), All(), Contains().

8. Element Operators

Used to get specific elements.

👉 Common ones:

  • First(), FirstOrDefault(), Single(), SingleOrDefault(), Last().

💡 In short:

LINQ operators are like “verbs” — they describe what you want to do with your data, and LINQ handles the “how”.



Select vs SelectMany

Select

  • Used to project each element into a new form (one-to-one).
  • It keeps the original structure — if each element contains a list, the result will be a list of lists.

SelectMany

  • Used to flatten collections — it takes a collection of collections and flattens it into a single sequence.
  • (Think of it as combining multiple sub-lists into one big list.)

💡 In short:

  • Select() → one-to-one projection.
  • SelectMany() → flattens nested collections.



First vs FirstOrDefault

First()

  • Returns the first element in a collection that matches a condition.
  • If no element is found → it throws an exception (InvalidOperationException).
  • Used when you’re sure that the data exists.

FirstOrDefault()

  • Same as First(), but if no element matches → it returns the default value (like null for reference types or 0 for numbers).
  • Used when the data might not exist and you want to avoid exceptions.

💡 In short:

  • First() → Must exist, or error.
  • FirstOrDefault() → Might exist, returns null/default if not found.



Single vs SingleOrDefault

Single()

  • Returns exactly one element from the sequence.
  • If zero or more than one element exists, it throws an exception.
  • Used when you’re sure there’s only one match (like a unique ID).

SingleOrDefault()

  • Same as Single(), but if no element is found, it returns the default value instead of throwing an error.
  • Still throws an exception if more than one element exists.

💡 In short:

  • Single() → Exactly one match, otherwise error.
  • SingleOrDefault() → Zero or one match only.



Single vs SingleOrDefault

Single()

  • Returns exactly one element from the sequence.
  • If zero or more than one element exists, it throws an exception.
  • Used when you’re sure there’s only one match (like a unique ID).

SingleOrDefault()

  • Same as Single(), but if no element is found, it returns the default value instead of throwing an error.
  • Still throws an exception if more than one element exists.

💡 In short:

  • Single() → Exactly one match, otherwise error.
  • SingleOrDefault() → Zero or one match only.



Deferred vs Immediate Execution in LINQ?

  • Means the query is not executed immediately when you define it — it only runs when you actually use (enumerate) the data, such as inside a foreach loop or when calling .ToList().
  • This allows lazy evaluation, meaning LINQ waits until it really needs the data.
  • Example idea (without code):
  • If you define a LINQ query but don’t loop through it yet, nothing happens.
  • Once you start iterating over the results, that’s when the database or collection is actually queried.
  • Benefit: You get better performance and fresh data because it executes at the last possible moment.

🧠 In short:

Deferred execution = Query runs later, only when data is requested.

🔹 Immediate Execution:

  • Here, the query runs as soon as it’s defined, and the results are stored in memory right away.
  • Usually happens when you use methods like .ToList(), .Count(), .First(), .Sum(), etc.
  • So instead of waiting, the system executes and caches results immediately.

🧠 In short:

Immediate execution = Query runs now, data is materialized right away.





whats the difference between IEnumerable and IQueryable?


🔹 IEnumerable

Concept:

IEnumerable works with data already loaded into memory — like List, Array, or any in-memory collection.

It iterates over each element after the data has been retrieved.

Execution: Happens on the client side (in memory), not in the database.

So when you filter or sort, all data is first loaded into memory and then filtered.

Use case:

Use IEnumerable when you already have your data in memory — for example, when you want to loop, filter, or transform a small set of objects inside your C# app.

Drawback:

It’s slower with large datasets because it loads everything first, consuming memory.

🔹 IQueryable

Concept:

IQueryable works with data before it’s fetched from the database.

The LINQ expression is translated into an SQL query, which the database executes directly.

Execution: Happens on the server side (database).

C# only sends the query; the actual filtering, sorting, or joining happens inside SQL Server (or any database provider).

Use case:

Use IQueryable when you’re working with Entity Framework or another ORM and want filtering, sorting, or projections to happen in SQL — for efficiency.

Advantage:

It’s much faster for large data because only the needed records are fetched.


Real-World Analogy:

Imagine you have 10,000 students in a database.

  • With IEnumerable, your app downloads all 10,000 records,
  • then filters in memory the ones older than 20 — heavy and slow.
  • With IQueryable, the filter (WHERE Age > 20) runs in SQL,
  • so only the matching rows are sent to your app — faster and cleaner.

IEnumerable executes on the client side and is used for in-memory collections,

while IQueryable executes on the server side and is used for querying databases.

IQueryable translates LINQ expressions into SQL, making it much more efficient for large datasets.


WHATS EF Core ?

EF Core is an ORM (Object-Relational Mapper) for .NET that lets you work with databases using C# objects instead of writing raw SQL.


Entity Framework Approaches

Entity Framework (EF) provides three main approaches to define and manage your database and models:

1️⃣ Code First

  • You start by writing C# classes (models) first.
  • EF then creates the database automatically based on those models.
  • It uses migrations to sync changes between the code and database.
  • Best for: new projects or when you have full control over the database design.

Pros:

✅ Full flexibility in designing models in code.

✅ Easy to version-control.

✅ Perfect for Agile development.

Cons:

❌ You must understand migrations well.

❌ Sometimes tricky when syncing with existing DBs.

2️⃣ Database First

  • You already have an existing database, and EF generates models automatically from it.
  • It reads your tables, relationships, and creates corresponding C# entity classes.
  • Best for: legacy databases or systems where DB is already defined.

Pros:

✅ Quick setup if DB already exists.

✅ Keeps model aligned with the database.

Cons:

❌ Less flexibility when modifying structure from code.

❌ You must re-scaffold if DB changes.

3️⃣ Model First (Legacy - EF6 only)

  • You draw the model visually (using EDMX designer).
  • EF then generates both the C# classes and the database.
  • Mostly replaced by Code First in modern EF Core.

Pros:

✅ Easy for beginners to visualize relationships.

Cons:

❌ Not supported in EF Core.

❌ Hard to maintain in large projects.



what's Migration?


In Entity Framework Core, Migrations are used to keep your database schema in sync with your C# models — without manually editing the database.

There are mainly three types or phases of migrations, depending on the context and purpose:


1️⃣ Automatic / Add Migration

  • This is the step where EF detects the changes in your models (like adding a property or table) and creates a migration script.
  • Command example (just for concept): Add-Migration AddStudentsTable
  • It does not update the database yet, it just prepares the migration file.

Purpose:

To record schema changes in code and make them ready for deployment.

2️⃣ Apply Migration (Update Database)

  • This step executes the migration and actually applies the changes to the database.
  • Example concept: running “Update-Database”.
  • It creates or modifies tables, columns, keys, etc., in the database according to your model changes.

Purpose:

To sync your actual database with your current models.

3️⃣ Remove or Revert Migration

  • Used when you added a migration by mistake or want to roll back to a previous version.
  • Example concept: “Remove-Migration” or “Revert Migration.”
  • Useful during development to undo schema changes safely before applying them to production.

Purpose:

To maintain clean and controlled versioning of your database changes.



🧩 Bonus: Seed Migrations

  • Sometimes considered a “type,” where you add initial data seeding inside the migration (like default admin users or roles).
  • Helps you keep data consistency along with schema versioning.



Yes — OnModelCreating is inside the DbContext class.

It’s a protected method that you override inside your custom DbContext class.

The purpose of OnModelCreating is to configure the model — meaning how your C# classes (entities) map to your database tables.

You use it when you want to:

  • Define relationships (one-to-many, many-to-many, etc.)
  • Configure table names, column names, or constraints
  • Apply fluent API configurations instead of using [DataAnnotations]
  • Seed initial data using modelBuilder.Entity<T>().HasData()

Example (conceptually, no code required here):

When EF creates your database schema, it calls OnModelCreating once — so whatever rules or configurations you define there will apply to how EF builds the model.




Lazy vs Eager vs Explicit Loading in Entity Framework


When working with related data (like navigation properties), Entity Framework gives you three main strategies to load related entities.

1. Eager Loading

  • Loads everything upfront in a single query using Include().
  • Useful when you know you’ll definitely need related data.
  • Fewer trips to the database (one query), but can be heavier because it pulls more data even if you don’t need all of it.

🧠 Think of it like: “Get me the student and all his courses right now.”

Pros: Better performance for predictable queries.

Cons: May load unnecessary data.

2. Lazy Loading

  • Loads related data only when accessed — not at first.
  • When you access a navigation property, EF automatically sends a new query to fetch it.
  • Requires special configuration (like virtual navigation properties or proxies).

🧠 Think of it like: “Just give me the student now — I’ll get his courses later if I need them.”

Pros: Saves resources if related data isn’t always needed.

Cons: Multiple database calls → can cause performance hits (the “N+1 problem”).

3. Explicit Loading

  • You manually control when to load related data.
  • The main entity is loaded first, and then you explicitly call a method (like Load()) to bring in related entities.
  • Similar to lazy loading, but you decide exactly when it happens.

🧠 Think of it like: “Give me the student first. Later, when I decide, I’ll tell you to load his courses.”

Pros: Full control over when data is fetched.

Cons: More manual work — you have to trigger it yourself.




Include and ThenInclude in Entity Framework


When you use Entity Framework and you have relationships between tables (like one-to-many or many-to-many), EF does not automatically load related data unless you ask it to.

That’s where Include() and ThenInclude() come in — they’re used for Eager Loading, meaning EF will load related entities together in a single query.

🧠 Include()

Used to load related entities directly connected to the main entity.

Example (conceptually):

If you have Students and each student has Courses, you can Include(Courses) to fetch both at once.

🧩 ThenInclude()

Used when you want to go deeper — to include related data from a related entity.

Think of it like a “chain.”

For example, if Course has a Teacher, you can do Include(Courses).ThenInclude(Teacher) — this tells EF to load the student, their courses, and each course’s teacher.


💡 Summary:

  • Include() → loads first-level related data.
  • ThenInclude() → loads deeper levels (nested navigation properties).
  • Both help reduce multiple database calls and improve performance when used wisely.



Change Tracking in Entity Framework

Change Tracking means EF automatically keeps track of changes made to entities after they are retrieved from the database.

When you call SaveChanges(), EF checks what’s new, modified, or deleted — and updates the database accordingly.

Key idea:

  • When you fetch data, EF starts tracking it.
  • If you change any property, EF detects it and marks the entity’s state.
  • Then, when you call SaveChanges(), EF runs the appropriate SQL commands (INSERT, UPDATE, DELETE).

Main Entity States:

  1. Added → A new entity to be inserted into the database.
  2. Modified → An existing entity with updated values.
  3. Deleted → An entity marked for removal.
  4. Unchanged → No modifications detected.
  5. Detached → Not being tracked by the context (not attached to DbContext).

💡 Change Tracking helps keep your code cleaner — you don’t need to manually tell EF which records changed.


Introduction to Object-Oriented Programming (OOP) in C#

OOP (Object-Oriented Programming) is a programming paradigm that organizes code around objects — real-world entities that have state (data) and behavior (methods).

It helps make code modular, reusable, and easier to maintain.

🧠 Four Main Principles of OOP:



1-Inheritance – Allows a class to reuse and extend features from another class.

→ Example: A Student class can inherit from a general Person class.



How Many Classes Can a Class Inherit From in C#?


In C#, a class can inherit only from one base class — this is called Single Inheritance.

That means you can’t have a class inheriting from two or more parent classes.

However, a class can implement multiple interfaces, which allows flexibility similar to multiple inheritance but without the risks.

 The Diamond Problem

The Diamond Problem happens in languages that allow Multiple Inheritance (like C++).

It occurs when a class inherits from two classes that both inherit from the same base class, forming a diamond shape in the inheritance hierarchy.

Example concept (no code needed):

Imagine you have:


  • Class A (base)
  • Class B and Class C inherit from A
  • Class D inherits from both B and C

Now, if both B and C have overridden a method from A, class D doesn’t know which version to use — from B or C?

That’s the Diamond Problem (ambiguity).


💡 C# avoids this issue completely by not allowing multiple class inheritance.

Instead, C# uses interfaces — they can be implemented by multiple classes safely, because interfaces don’t have state or method bodies (until default interface methods in later versions).



2-Abstraction :

Abstraction is the process of hiding complex implementation details and showing only the essential features to the user.

It focuses on what an object does, not how it does it.

This is typically achieved through abstract classes and interfaces.

Abstraction helps simplify large systems, making them easier to use, extend, and maintain.



What is the difference between an abstract class and an interface C#?



An abstract class is a class that cannot be instantiated directly. It serves as a base class and can contain both implemented methods and abstract (unimplemented) methods. It can also have fields and constructors. It allows sharing common logic among derived classes.



An interface is a contract that defines a set of methods (and properties) that a class must implement. It doesn’t contain any code, fields, or constructors. A class can implement multiple interfaces, which makes interfaces ideal for enforcing consistency without inheritance limitations.



The main difference is that an abstract class can contain shared logic and partial implementation, while an interface only defines method signatures.

A class can inherit from only one abstract class but can implement multiple interfaces.

Use an abstract class when you want to share common code, and use an interface when you just want to enforce structure and behavior across unrelated classes.



in short:

Abstract classes can have concrete methods and constructors while interfaces (prior to C# 8.0) could only have method signatures. Also, C# supports multiple interface implementation but single inheritance.






What is the difference between an abstract class and an regular class C#?


A regular class is a class you can instantiate directly. It usually contains fully implemented methods and doesn’t enforce any structure on other classes. You use it when you have complete, ready-to-use logic without needing inheritance rules.



An abstract class cannot be instantiated directly. It’s meant to serve as a base class for other classes. It can contain both implemented and abstract methods (methods without a body). Any class that inherits from it must implement those abstract methods.


The main difference is that a regular class can be used directly, while an abstract class is meant only for inheritance. The regular class doesn’t enforce rules, but the abstract class enforces implementation of abstract methods in its derived classes.



3-Encapsulation:

Encapsulation means wrapping data (fields) and the methods that operate on that data into a single unit — usually a class — and restricting direct access to the internal state.

It’s about protecting data from unauthorized or unintended modification by making fields private and exposing controlled access through public getters and setters.

This ensures data integrity, reduces coupling, and makes the code more maintainable.




whats diff Encapsulation vs Abstraction?


Encapsulation is about hiding data and controlling how it’s accessed and modified within a class,

while Abstraction is about hiding implementation details and exposing only what’s necessary.

In short —

Encapsulation protects how data works internally,

Abstraction simplifies how the system is presented externally.




Imagine you have a class called BankAccount, and it has a variable named balance.

You don’t want anyone outside the class to directly modify that balance, right?

You don’t want code like this:

account.balance = -1000;

😅

So, what do you do?

You make the variable private, and instead provide public methods like Deposit(amount) or Withdraw(amount)

so that people can interact with the balance in a safe and controlled way.

🔹 In short, Encapsulation protects the data itself inside the class

and prevents external code from messing with it directly.

It’s basically a shield for your code.

👉 Simply put: it protects the “how” — how the data is stored and managed internally.



Now, this one is a bit different.

Abstraction isn’t about protecting the data — it’s about simplifying how others interact with a complex system.

For example, when you start a car using a “Start” button,

you don’t need to know what happens inside the engine — the spark, the fuel, the ignition, etc.

All you care about is pressing the button and the car starts.

That’s Abstraction.

Same in programming:

You let the user know what can be done, not how it’s done inside.

For instance, if you have an interface called IPayment

with a method ProcessPayment(),

the user knows they just need to call that method —

they don’t (and shouldn’t) care how the payment is actually processed inside.

👉 Simply put: it protects the “user” — they don’t have to deal with internal complexity.


⚖️ In summary:


  • Encapsulation = Protects data from direct access (controls how the code works internally).
  • Abstraction = Hides complex details and exposes only the necessary parts (simplifies external interaction).

✅ In one line:


Encapsulation protects the code from people,
Abstraction protects people from the code. 😄



4-Polymorphism :


Polymorphism means “many forms” — it allows the same method or object to behave differently based on the context.

In OOP, it simply means that a single function, class, or interface can take multiple forms depending on how it’s used.

It helps you write flexible and extendable code without constantly rewriting logic.

There are two main types:


1️⃣ Compile-time Polymorphism (Static Binding)

Happens at compile time.

Usually done through Method Overloading — when you have multiple methods with the same name but different parameters (type, number, or order).

👉 Example (conceptually):

You can have a Print() method that works for both text and numbers — same name, different behavior.

2️⃣ Run-time Polymorphism (Dynamic Binding)

Happens during program execution.

Achieved through Method Overriding — when a child class provides its own version of a method defined in the parent class.

👉 Example (conceptually):

A parent class Shape might have a Draw() method.

Each subclass like Circle, Rectangle, or Triangle overrides Draw() differently.

So, when you call shape.Draw(), the program decides at runtime which version to use.

✅ In short:


  • Overloading → same method name, different parameters (decided at compile time).
  • Overriding → same method name, redefined in child class (decided at runtime).



What does the virtual keyword do in C#?

The virtual keyword in C# is used to allow a method, property, or event to be overridden in a derived (child) class.

By default, methods in C# are non-overridable — meaning if you define a method in a base class, the child class can’t change its behavior unless it’s declared virtual.

When a method is marked as virtual, it says:

“Hey, this behavior can be changed by subclasses if needed.”

🧠 Purpose:

It’s part of Polymorphism — one of the main pillars of OOP — allowing a child class to provide a new version (override) of a method while keeping the same signature.

In short:

  • You declare a method virtual in the base class.
  • You use override in the derived class to modify its behavior.
  • If you don’t override, the base version is used by default.






What is the difference between Value Types and Reference Types in C#?

In C#, data types are divided mainly into two categories:

Value Types and Reference Types — and the difference between them comes down to how and where the data is stored in memory.

💾 Value Types

  • Stored directly in the stack memory.
  • When you assign one value type to another, a copy of the data is made — meaning changes to one don’t affect the other.
  • Common examples:
  • int, float, bool, char, struct, enum
  • They hold actual values (e.g., int x = 5; — the value 5 is stored directly in memory).

Key idea:

Each variable has its own copy of the data.

🧠 Reference Types

  • Stored in the heap memory, while the variable itself holds a reference (or pointer) to that memory location.
  • When you assign one reference type to another, both variables refer to the same object in memory — meaning if you change one, the other is affected.
  • Common examples:
  • class, array, string, interface, delegate
  • They hold references to the actual data, not the data itself.

Key idea:

Multiple variables can point to the same object in memory.

⚖️ In short:

  • Value Type → stores actual data in the stack (copied by value).
  • Reference Type → stores a pointer to data in the heap (copied by reference).


Difference Between Array and List in C#?


Array

  • Fixed size -cannot change after creation
  • Faster access
  • Best when number of items is known
  • Direct index access


List

  • Dynamic size — grows and shrinks automatically
  • Slightly slower but more flexible
  • Many built-in methods: Add, Remove, Find…


whats Struct vs Class?

Both structs and classes are used to define custom data types in C#,

but they differ mainly in how they are stored and behave in memory.

🧩 1. Type Category

  • Class → Reference Type (stored on the heap, accessed by reference).
  • Struct → Value Type (stored on the stack, copied by value).

🧠 2. Memory & Performance

  • When you assign one class variable to another, both refer to the same object in memory.
  • When you assign one struct variable to another, a copy of the data is made.
  • So structs are faster for small, lightweight data; classes are better for large, complex objects.

🧱 3. Inheritance

  • Class supports inheritance (can inherit and be inherited).
  • Struct cannot inherit from another struct or class (but it can implement interfaces).

⚙️ 4. Default Constructor

  • Class can define a default (parameterless) constructor.
  • Struct cannot define one — it always has an implicit default constructor that initializes all fields to their default values.

🧮 5. Use Cases

  • Use struct for small data containers (like Point, Color, Coordinate).
  • Use class for entities that have behavior, logic, or need to support inheritance.

📦 6. Garbage Collection

  • Classes are managed by the Garbage Collector (because they’re reference types).
  • Structs are destroyed automatically when they go out of scope (since they’re value types).






whats Types of Classes in C#?


C# supports several types of classes, depending on how you want them to behave:

  1. Normal (Concrete) Class
  • A standard class you can create instances of.
  • Can have fields, properties, methods, and constructors.
  1. Abstract Class
  • Cannot be instantiated directly.
  • Can contain abstract methods (no body) that must be implemented by derived classes.
  • Can also contain normal methods with implementation.
  1. Sealed Class
  • Cannot be inherited.
  • Useful to prevent further derivation, usually for security or performance reasons.
  1. Static Class
  • Cannot be instantiated.
  • Can contain only static members (fields, methods, properties).
  • Commonly used for utility/helper methods (e.g., Math class).
  1. Partial Class
  • Allows a class definition to be split across multiple files.
  • Compiler merges all parts into a single class at compile time.
  1. Nested (Inner) Class
  • A class defined inside another class.
  • Helps organize code and encapsulate functionality.
  1. Generic Class
  • Allows defining a class with placeholders for types.
  • Makes the class reusable with different data types (e.g., List<T>).



What is an Event in C#?


An event in C# is a way for a class to notify other classes or objects that something has happened.

It follows the publisher–subscriber model:

  • One class (the publisher) defines and raises the event.
  • Other classes (the subscribers) respond to it by attaching event handlers (methods that run when the event occurs).

Events are usually used in user interfaces, real-time systems, or any situation where you want your program to react dynamically — for example, a button click, file download completion, or sensor update.

Under the hood, events are built on top of delegates, which define the method signature that subscribers must follow.

So basically, an event is a safe way to call methods in other classes when something specific happens.



Difference Between Delegate and Event?


A delegate in C# is a type that defines a method signature and can hold references to one or more methods.

Think of it as a function pointer — it allows methods to be passed around and invoked dynamically.

An event, on the other hand, is a layer of control built on top of a delegate.

It’s used to restrict access — only the class that declares the event can raise (invoke) it,

while other classes can only subscribe (+=) or unsubscribe (-=).

👉 In short:

  • Delegate → defines the method signature and can directly call the methods.
  • Event → wraps the delegate to enforce safety and follows the publisher-subscriber pattern.

So every event internally uses a delegate, but not every delegate is an event.


What is a Tuple in C#?


A Tuple in C# is a lightweight data structure that can hold multiple values of different types in a single object — without creating a custom class or struct.

It’s often used when you want to return more than one value from a method, or quickly group related data together.

✅ Example idea (without code):

You can have a tuple that stores (string name, int age, bool isActive).

So instead of creating a class called Person, you can just group those values temporarily.

Tuples are immutable, meaning their values cannot be changed after creation.


Tuple vs Record in C#?

🔹 Tuple:

A Tuple is a lightweight data container that groups multiple values without naming them as a real type.

It’s usually temporary, used for quick grouping or returning multiple values from a method.

  • You can think of it as: “just hold these few values together for now.”
  • Tuples are immutable and don’t support behavior (no methods, logic, etc.).
  • The main goal: group data quickly, not model an entity.

🔹 Record:

A Record is a real type introduced in C# 9, mainly used for immutable data models — similar to classes, but designed for data storage (like DTOs).

It supports properties with names, methods, and can even inherit.

  • Records are used for modeling data, not just holding values.
  • They come with built-in features like:
  • Value-based equality (two records with same data are considered equal).
  • Easy cloning using with expressions.
  • Cleaner syntax.



Immutable vs Mutable ?

 Mutable:

A mutable object can be changed after it’s created.

That means you can modify its properties, fields, or contents without creating a new object.

🧩 Example (conceptually):

You can change the value of a List, add or remove elements — the same list in memory changes.

So:

  • The object’s identity stays the same.
  • Its internal data changes.

👉 “Mutable = Changeable”

🔹 Immutable:

An immutable object cannot be changed after it’s created.

If you want to “change” it, you actually create a new object with the new value.

🧩 Example (conceptually):

string in C# is immutable — when you modify it, you’re actually creating a new string in memory.

So:

  • The old object remains the same.
  • A new one is created with updated data.

👉 “Immutable = Unchangeable (fixed after creation)”




whats Access Modifiers in C#?


Access modifiers define the level of accessibility of classes, methods, and variables — in other words, who can see or use them.

C# provides six main access modifiers:

  1. public → Accessible from anywhere in the project or even other projects.
  2. private → Accessible only inside the same class.
  3. protected → Accessible within the same class and derived (child) classes.
  4. internal → Accessible only within the same assembly/project.
  5. protected internal → Accessible from the same assembly OR derived classes (even in another assembly).
  6. private protected → Accessible only within the same assembly AND derived classes.

🧠 Example (conceptually):

  • public → “open to everyone.”
  • private → “mine only.”
  • protected → “mine and my kids.”
  • internal → “visible inside this project only.”
  • protected internal → “mine, my kids, and everyone in my project.”
  • private protected → “mine and my kids, but only if they’re in my project.”





Difference between readonly, const, and static?


1. const (Constant):

  • Value is known and fixed at compile time.
  • It cannot be changed after compilation.
  • It’s implicitly static, meaning there’s only one copy shared by all instances.
  • Must be initialized when declared.

🧠 Example use case:

When you have universal constants like PI = 3.14 or DaysInWeek = 7.

2. readonly:

  • Value is assigned only once, but at runtime (inside the constructor or when declared).
  • Each object can have its own value.
  • Not implicitly static — unless you explicitly declare it so.

🧠 Example use case:

When the value depends on something provided during object creation — like user settings, timestamps, or IDs.

3. static:

  • Belongs to the class itself, not to any instance.
  • Shared by all objects.
  • Useful for data or methods that are common to all instances.

🧠 Example use case:

Counters, configuration values, or utility methods that don’t depend on object data.



what's constructor?

A constructor in C# is a special method that is called automatically when an object is created from a class.

It is mainly used to initialize fields or set up resources for the new object.

Key points:

  • Has the same name as the class.
  • Has no return type.
  • Runs automatically when you create an instance using new.
  • Can be overloaded (you can have multiple constructors with different parameters).
  • If you don’t define one, C# automatically provides a default constructor.


Types of Constructors in C#:

  1. Default Constructor
  2. A constructor with no parameters.
  3. It’s automatically called when you create an object without passing any arguments.
  4. It usually initializes default values for the class fields.
  5. Parameterized Constructor
  6. A constructor that takes parameters.
  7. It’s used to assign custom or initial values to fields when creating the object.
  8. It gives more control over how an object is initialized.
  9. Static Constructor
  10. A special constructor that executes only once — when the class is loaded into memory for the first time.
  11. It’s used to initialize static fields or perform class-level setup.
  12. It can’t take parameters and can’t be called manually.
  13. Private Constructor
  14. A constructor that can’t be accessed from outside the class.
  15. It’s used to prevent object creation from external code — for example, in Singleton or utility classes.
  16. This ensures only the class itself can control how and when instances are created.

🧠 Purpose:

Used to control object creation — so that external code can’t make new instances.





Primary Constructor is a new feature in C# 12. It allows you to define constructor parameters directly in the class definition instead of writing a full constructor in the traditional way.

  • The class takes values at creation, and the properties are automatically linked to the parameters.
  • Makes the code shorter and cleaner, especially for simple classes meant to hold data.
  • Commonly used for immutable classes or records.

Think of it as a shortcut: instead of writing a full constructor and manually assigning variables, you declare them right with the class.


the diff between Regular one and Primary?

Regular Constructor:

  • You write a full constructor inside the class.
  • Variables are declared in the class and manually assigned from the parameters.
  • Suitable for complex classes or when you have additional logic inside the constructor.

Primary Constructor (C# 12):

  • You can define parameters directly at the class declaration.
  • Properties are automatically linked to the parameters without manual assignment.
  • Makes the code shorter and cleaner, great for simple classes or immutable records.

Key Difference:

  • Regular: more flexible, manual, better for complex logic.
  • Primary: concise, automatic, ideal for data-holding or immutable objects.



What are try, catch, finally in C#?


In C#, try, catch, and finally are used for exception handling, which means managing errors that occur during program execution.

  • try:
  • The block of code that you suspect might throw an exception.
  • You “try” to execute it safely.
  • catch:
  • The block that handles exceptions if one occurs in the try block.
  • You can have multiple catch blocks to handle different types of exceptions.
  • finally:
  • The block that always executes, regardless of whether an exception was thrown or not.
  • It’s commonly used to release resources like closing files, database connections, or network streams.

Key Points:

  • Exception handling prevents your program from crashing unexpectedly.
  • The finally block ensures cleanup even if an error happens.
  • try is mandatory, catch is optional if you have finally, but at least try+catch is the common pattern.


What is the purpose of the 'finally' block in a try-catch-finally statement?


Purpose of the finally Block in C#

  • The finally block is part of the try-catch-finally construct.
  • Its purpose is to execute code regardless of whether an exception occurred or not.
  • It’s typically used for cleaning up resources, such as closing files, releasing database connections, or disposing objects.

Key Points:

  • Executes always, even if the try block succeeds or a catch block handles an exception.
  • Helps prevent resource leaks by ensuring cleanup happens.
  • Optional, but highly recommended when dealing with unmanaged resources.




What is the difference between 'throw' and 'throw ex' in exception handling?


Difference Between throw and throw ex in C#

  • throw
  • Re-throws the current exception while preserving the original stack trace.
  • This means you can track exactly where the exception originally occurred, which is very important for debugging.
  • throw ex
  • Throws the same exception object but resets the stack trace to the current location.
  • This makes it look like the exception started from the throw ex line, so you lose the original origin of the error.

Key Points:

  • Use throw when you want to propagate an exception while keeping the stack trace intact.
  • Avoid throw ex unless you intentionally want to reset the stack trace.


What is the purpose of the 'finally' block in a try-catch-finally statement?


🔹 Purpose of the finally Block in C#

  • The finally block is part of the try-catch-finally construct.
  • Its purpose is to execute code regardless of whether an exception occurred or not.
  • It’s typically used for cleaning up resources, such as closing files, releasing database connections, or disposing objects.

Key Points:

  • Executes always, even if the try block succeeds or a catch block handles an exception.
  • Helps prevent resource leaks by ensuring cleanup happens.
  • Optional, but highly recommended when dealing with unmanaged resources.



 Why is memory read faster than write?

Reading from memory is usually faster than writing because of how memory hardware and CPU caching work.

⚙️ 1. Reading is simpler

When the CPU reads, it just fetches data from memory (or from cache) — it’s a one-way operation.

But when it writes, it needs to:


  • Find the memory address
  • Ensure it’s not being used by another process
  • Sometimes flush or update cache lines
  • Wait for confirmation from the memory controller

So writing involves more steps and synchronization.

2. CPU caching behavior

Modern CPUs use write-back caches — when you write data, it first goes to cache and only later gets written to main memory.

That delay adds complexity, while reads can often be served instantly from cache.

💾 3. Memory hardware design

Memory chips (like DRAM) are optimized for read speed because most operations in software are read-heavy.

The hardware is literally designed to make reads faster than writes — writing needs extra electrical cycles to change cell states.

💡 In short:


  • Read: fetch data quickly
  • Write: needs to modify memory safely → slower



What is Asynchronous Programming?

Asynchronous programming means your program doesn’t wait for long-running tasks (like database queries, API calls, or file reading) to finish before moving on.

Instead, it keeps doing other work while waiting for the result — this makes your application faster and more responsive.



Keywords: async and await


  • async → Marks a method as asynchronous (it can use await inside).
  • await → Tells the program to wait only for that specific task to finish — without freezing the entire program.

Simple Real-life Example



It’s like when you order food at a restaurant — you don’t stand at the counter until it’s ready (that’s synchronous).

Instead, you go sit, talk with friends, and when your food is ready, they call you (that’s asynchronous).


Why We Use Async Programming

English:

  • Improves app performance
  • Prevents UI freezing
  • Makes apps more scalable and responsive

Why We Use Async Programming


  • Improves app performance
  • Prevents UI freezing
  • Makes apps more scalable and responsive

💬 Typical Async Operations

  • Database operations → ToListAsync(), FirstOrDefaultAsync()
  • API calls → HttpClient.GetAsync()
  • File I/O → ReadAsync(), WriteAsync()






⚙️ What does the async keyword do in C#?


The async keyword in C# is used to mark a method as asynchronous, meaning it can contain one or more await expressions inside.

It allows your method to perform long-running operations (like database queries or API calls) without blocking the main thread.

When you mark a method as async, it tells the compiler that this method might pause its execution when it reaches an await, and later resume when the awaited task completes.

It always returns a Task, Task<T>, or void (in special cases like event handlers).




Key Points:


  • async enables the use of await inside a method.
  • The method usually returns Task or Task<T>.
  • It helps keep apps responsive (especially UI apps).
  • It doesn’t create a new thread by itself — it just allows non-blocking operations.


⚙️ What is the purpose of the await keyword in C#?

English:

The await keyword is used inside an async method to pause the execution of that method until the awaited task is completed, without blocking the thread.

In simple terms, it tells C#:

“Wait for this task to finish, but don’t freeze the program while waiting.”

When the task completes, the method resumes from where it left off — keeping the app responsive (especially in UI or web apps).

So await makes asynchronous code look and behave like normal sequential code, which makes it much easier to read and maintain.



🧩 Key Points:


  • await can only be used inside an async method.
  • It pauses the method until the awaited task completes.
  • It does not block the main thread.
  • Makes async code look like normal synchronous code.



⚙️ How async and await work together — Step by Step?


  1. When you mark a method with the async keyword, you’re telling C#:
“This method might take some time — let’s run it asynchronously.”
  1. Inside that method, when C# sees an await keyword (like await SomeTask()),
  2. it pauses the execution of the current method at that point.
  3. While waiting, the thread is freed to do other work — it’s not blocked.
  4. That’s why your UI or web server stays responsive.
  5. When the awaited task finishes,
  6. C# automatically resumes the method from where it left off.
  7. If the task throws an exception, it will be re-thrown when execution resumes —
  8. so you can handle it with a regular try-catch.

Result:

You get non-blocking, efficient, and clean code that feels synchronous even though it’s not.



Task vs Task<T>

In C#, a Task represents a unit of work that runs asynchronously

it’s basically a promise that something will finish later.

There are two main types:

  1. Task (no return value)
  2. → used when your async method doesn’t return anything (like void, but async-safe).
  3. Example: saving data to a file or sending an email.
  4. It just says, “I’m working on it — I’ll tell you when I’m done.”
  5. Task<T> (returns a value)
  6. → used when your async method returns a result.
  7. For example, Task<int> means “I’ll give you an integer result later.”

So when you use await, you’re basically saying:

“Wait for this task to finish and give me the result if it has one.”

Why Tasks are important:

They make async code predictable and composable —

you can chain them, wait for multiple tasks, or handle errors in one place.



What is the correct way to implement async/await pattern in C#?


Correct way to implement async/await pattern in C#:


The correct way to use the async/await pattern is to:

  1. Mark your method with async
  2. → This tells the compiler that your method contains asynchronous operations.
  3. Use await before any asynchronous call
  4. → This pauses the method until the awaited task finishes without blocking the thread.
  5. Return Task or Task<T> (never void, except for event handlers)
  • Task → when the method doesn’t return a value
  • Task<T> → when it returns a value
  • Using async void hides exceptions and makes error handling harder.
  1. Always await async methods
  2. → Never just call them without await, otherwise they run in the background and exceptions may be lost.
  3. Avoid blocking calls like .Result or .Wait()
  4. → These block the thread and can cause deadlocks.

Best practice summary:

  • Use async/await all the way down.
  • Return Task/Task<T>, not void.
  • Handle exceptions with try...catch inside the async method.
  • Don’t mix sync and async code unless necessary.




What is Task.Run() in C#?

Task.Run() is a method used to run code on a separate background thread, not the main thread.

It’s part of the Task Parallel Library (TPL), and it helps offload CPU-bound operations so they don’t block your main thread (for example, the UI thread).

In simple words:

It’s like saying: “Run this work in the background so my main program doesn’t freeze.”

🔹 When to use Task.Run()

You use Task.Run() when you have CPU-bound work — heavy processing like:

  • Complex calculations
  • File processing
  • Image compression
  • Encryption/decryption

It keeps your app responsive because the heavy work runs in the background thread pool.

⚠️ When NOT to use Task.Run()


Don’t use it for I/O-bound work (like database queries, HTTP requests, reading files asynchronously),

because those already have async methods — e.g., await httpClient.GetAsync().

Using Task.Run() in those cases just adds unnecessary thread overhead.

🧠 In short:

  • Task.Run() moves code to a background thread (for CPU-bound work).
  • await Task.Run(...) still awaits completion, but without blocking the UI thread.
  • It’s useful in desktop apps (WPF/WinForms) to keep the UI smooth.
  • Avoid it in ASP.NET unless you’re really doing CPU-heavy logic — because ASP.NET already manages threads efficiently.




How to run 3 tasks at the same time in C#?


To run multiple tasks concurrently, you use the Task Parallel Library (TPL) — usually with Task.WhenAll() or Task.WhenAny().

Concept:

Instead of running one task, waiting for it to finish, then starting the next,

you can start all tasks together and let them run in parallel.

🧠 The key idea:

Each Task runs independently, and await Task.WhenAll(...) waits for all of them to finish.

Example (conceptually — not coding here):

  • Task 1 → Fetch data from API
  • Task 2 → Read a file
  • Task 3 → Process data

You can launch them at once → they all start working simultaneously in the background.

Your program doesn’t block; it just waits for all results to come back when you call Task.WhenAll().

💡 Important:

  • This doesn’t mean they’re all on different physical CPUs necessarily — the runtime handles scheduling across threads.
  • The performance gain depends on whether the tasks are I/O-bound (like API calls, DB queries) or CPU-bound.


To run multiple tasks concurrently, you use the Task Parallel Library (TPL) — usually with Task.WhenAll() or Task.WhenAny().

Concept:

Instead of running one task, waiting for it to finish, then starting the next,

you can start all tasks together and let them run in parallel.

🧠 The key idea:

Each Task runs independently, and await Task.WhenAll(...) waits for all of them to finish.

Example (conceptually — not coding here):

  • Task 1 → Fetch data from API
  • Task 2 → Read a file
  • Task 3 → Process data

You can launch them at once → they all start working simultaneously in the background.

Your program doesn’t block; it just waits for all results to come back when you call Task.WhenAll().

💡 Important:

  • This doesn’t mean they’re all on different physical CPUs necessarily — the runtime handles scheduling across threads.
  • The performance gain depends on whether the tasks are I/O-bound (like API calls, DB queries) or CPU-bound.


async/await does not automatically make your code run in parallel — it just makes it non-blocking.

When you mark a method async and use await, what happens is:

  • The method can pause when it hits an await (for example, waiting for an I/O operation, like a web request or database query).
  • During that wait, the current thread is freed — it can go do other work.
  • When the awaited operation finishes, the method resumes from where it left off.

So, async = non-blocking,

not = “run in parallel” or “use multiple threads”.

If you actually want to run multiple tasks at the same time, you need to create multiple tasks (for example using Task.Run() or async operations) and then await them all together, like this:

await Task.WhenAll(Task1(), Task2(), Task3());




⚙️ 1. What is .NET Framework / .NET Core ?


.NET is a software development framework created by Microsoft that provides a controlled environment for developing and running applications.

It supports multiple languages (like C#, VB.NET, F#) and platforms (Windows, macOS, Linux).


⚙️ 2. What is the difference between .NET Framework and .NET Core (or .NET 6/7)?

.NET Framework → Works only on Windows.

.NET Core / .NET 6+ → Cross-platform (Windows, Linux, macOS).

.NET Core is faster, modular, and open-source.




What is the CLR in .NET?

CLR stands for Common Language Runtime

it’s the heart of the .NET Framework (and .NET Core).

It’s the runtime environment that manages the execution of all .NET programs.

Think of it as the engine that runs your C#, VB.NET, or F# code.

🧠 The CLR is responsible for:

  1. Memory Management — handles allocation and garbage collection automatically.
  2. Exception Handling — manages runtime errors in a structured way.
  3. Type Safety — ensures variables are used correctly (no invalid casting, etc.).
  4. Security — enforces code access and verification.
  5. Thread Management — handles multithreading and synchronization.
  6. JIT Compilation — converts IL (Intermediate Language) code to native machine code before execution.

In short:

CLR = The engine that makes .NET code run safely and efficiently.



Memory Management, Garbage Collection, and Cache Memory in .NET?



1. Memory Management in .NET

Memory management in .NET is handled automatically by the CLR (Common Language Runtime).

It decides when and how memory is allocated and freed, so you don’t need to manually manage memory like in C++.

There are two main memory areas in .NET:

  • Stack: Stores value types (like int, bool, structs) and keeps track of method calls.
  • It’s fast and automatically cleaned up when methods finish.
  • Heap: Stores reference types (like class, object, string).
  • Managed by the Garbage Collector (GC).

♻️ 2. Garbage Collection (GC)

Garbage Collection is an automatic memory cleanup process in .NET.

It detects and removes objects that are no longer used by the application to free up memory.

How it works:

  • When you create an object (e.g., new Student()), it’s stored on the Heap.
  • Once that object is no longer referenced by any variable,
  • the GC marks it as “unreachable” and removes it automatically.

The .NET Garbage Collector runs in generations:

  • Gen 0: short-lived objects (e.g., local variables, temporary data).
  • Gen 1: medium-lived objects.
  • Gen 2: long-lived objects (e.g., global or static data).

You can also trigger garbage collection manually using GC.Collect(),

but it’s not recommended unless you know what you’re doing — the CLR usually does it better.

3. Cache Memory

Cache memory in .NET isn’t the same as RAM — it’s a temporary storage mechanism used to speed up data access.

Instead of fetching data from the database or a file every time,

you store it temporarily in cache, so the system can reuse it faster.

Types of caching:

  • In-memory cache (like using MemoryCache in .NET)
  • Distributed cache (like Redis or SQL Server cache)

Purpose: Improve performance and reduce expensive data operations.


Main Properties of Memory Cache?

  • Set(key, value, options)
  • Used to store data in the cache. You specify the key, value, and optional cache options such as expiration using MemoryCacheEntryOptions.
  • Get(key) and TryGetValue(key, out value)
  • Used to retrieve cached data.
  • Get returns the cached value directly, while TryGetValue returns true or false depending on whether the key exists, and stores the result in the out variable.
  • Remove(key)
  • Used to delete a specific item from the cache using its key.
  • MemoryCacheEntryOptions
  • Defines cache expiration policies, such as absolute expiration, sliding expiration, or priority settings for when the system is low on memory.




1. Where is the data stored in MemoryCache?

It’s stored in the server’s memory (RAM), not in external storage.

🔁 2. What happens to MemoryCache data when the app restarts?

It’s lost — because it’s only in memory.

⚙️ 3. What interface is used to inject caching in .NET Core?

IMemoryCache

🌐 4. Can multiple servers share the same MemoryCache?

❌ No, each instance has its own in-memory cache (use DistributedCache or Redis instead).


Main Properties of MemoryCache

  • Set(key, value, options)
  • Used to store data in the cache. You specify the key, value, and optional cache options such as expiration using MemoryCacheEntryOptions.
  • Get(key) and TryGetValue(key, out value)
  • Used to retrieve cached data.
  • Get returns the cached value directly, while TryGetValue returns true or false depending on whether the key exists, and stores the result in the out variable.
  • Remove(key)
  • Used to delete a specific item from the cache using its key.
  • MemoryCacheEntryOptions
  • Defines cache expiration policies, such as absolute expiration, sliding expiration, or priority settings for when the system is low on memory.


What is Distributed Cache in .NET Core?


Distributed Cache is used when you have multiple servers (for example, your app is deployed on a cloud or load-balanced environment) and you want all servers to share the same cache data.

Unlike MemoryCache, which stores data in the local server’s RAM, distributed cache stores it in an external shared storage (like Redis or SQL Server).

So no matter which server handles the request, it can access the same cached data.

🧠 Main purpose:

✅ Keep cache data shared between multiple app instances.

✅ Improve scalability and performance in cloud or multi-server setups.


Common Distributed Cache Providers in .NET?

  1. Redis Cache → Fast, in-memory, widely used for large systems.
  2. SQL Server Cache → Stores cache data in a SQL database (slower but simple).
  3. NCache → Enterprise-grade distributed caching system for .NET.

What is Redis Cache in .NET Core?

Redis (Remote Dictionary Server) is a fast, in-memory, key-value data store that can be used as a Distributed Cache in .NET.

It keeps data in RAM, which makes it super fast — and it can be shared across multiple servers, unlike MemoryCache.

It’s often used for:

  • Storing session data
  • Caching database queries or API responses
  • Real-time leaderboard or analytics data
  • Pub/Sub messaging

🧠 Key Advantages:

  • ⚡ Extremely fast (all in-memory operations)
  • 🔁 Shared cache between multiple app instances
  • 🔒 Data persistence options (can store snapshots to disk)
  • 🚀 Perfect for scalable cloud systems


You add Redis using:

  • Microsoft.Extensions.Caching.StackExchangeRedis package.
  • Configure it in Program.cs using AddStackExchangeRedisCache().

Then inject it via the IDistributedCache interface — same interface used for any distributed cache provider (Redis, SQL, etc.).



When to choose Redis:

  • Multi-server / cloud applications
  • Shared cache between services
  • Large datasets needing high performance
  • Persistent or reliable caching




ASP.NET Core Application Life Cycle?


The ASP.NET Core Life Cycle describes what happens from the moment a request hits your application until the response is sent back to the client.

It helps you understand how requests are processed, how middleware works, and when controllers or Razor pages are executed.

Let’s go step-by-step 👇

🧩 1. Application Startup

When the application starts, two main classes are involved:

  • Program.cs
  • Startup.cs (in older versions)

The application pipeline is built here — this means:

  • Services are registered in the Dependency Injection (DI) container.
  • Middleware components are added to handle requests and responses.

⚙️ 2. Middleware Pipeline

Once a request comes in, it travels through the middleware pipeline.

Each middleware can:

  • Process the request,
  • Pass it to the next middleware, or
  • Short-circuit the pipeline and return a response.

Examples of common middleware:

  • Authentication
  • Routing
  • Exception handling
  • Static files
  • Endpoints (Controllers / Razor Pages)

This pipeline is what defines the core of ASP.NET Core’s flexibility.

📬 3. Routing

When the request reaches the Routing Middleware,

it matches the URL to a specific endpoint — for example:

  • A Controller Action
  • A Razor Page
  • A Minimal API endpoint

If no route matches, ASP.NET Core returns a 404 Not Found.

🧠 4. Controller / Action Execution

If the route points to a controller, the MVC Middleware takes over:

  • It finds the correct controller and action.
  • Model binding occurs (it maps incoming data like query strings or form data to method parameters).
  • Then the controller action runs and returns a result (like a View, JSON, or redirect).

🧾 5. Result Execution

The action result (e.g., ViewResult, JsonResult) is executed and converted into an HTTP response.

ASP.NET Core writes that response into the HTTP response stream,

and the middleware pipeline starts sending it back to the client.

6. Response Sent to Client

Finally, the response travels back through the middleware (in reverse order)

and reaches the client — e.g., a browser, mobile app, or API consumer.

At this point, the request is complete.



🇬🇧 ASP.NET Core Life Cycle vs ASP.NET MVC Life Cycle

🔹 Similarities:

  • Both handle requests through a pipeline.
  • Both use Routing to match requests to controllers or endpoints.
  • Both have controllers, actions, model binding, and result execution.
  • Middleware in ASP.NET Core is roughly similar to HTTP modules and handlers in classic MVC.

🔹 Differences:

  1. Middleware vs HTTP Modules:
  • ASP.NET Core uses explicit middleware configured in Startup.cs/Program.cs.
  • Classic MVC uses HTTP Modules & Handlers that are configured in web.config.
  1. Lightweight & Modular:
  • ASP.NET Core is lighter, cross-platform, and faster.
  • MVC is tied to System.Web, Windows-only, and heavier.
  1. Dependency Injection (DI):
  • ASP.NET Core has built-in DI; you can inject services everywhere.
  • Classic MVC requires third-party DI frameworks like Ninject, Autofac.
  1. Request Pipeline Control:
  • In Core, you have full control over the request pipeline order.
  • In classic MVC, the pipeline order is mostly predefined and less flexible.
  1. Hosting & Environment:
  • Core apps can run on Kestrel, IIS, or self-hosted.
  • Classic MVC only runs on IIS.


ASP.NET Core Life Cycle vs ASP.NET MVC Life Cycle

🔹 Similarities:

  • Both handle requests through a pipeline.
  • Both use Routing to match requests to controllers or endpoints.
  • Both have controllers, actions, model binding, and result execution.
  • Middleware in ASP.NET Core is roughly similar to HTTP modules and handlers in classic MVC.

🔹 Differences:

  1. Middleware vs HTTP Modules:
  • ASP.NET Core uses explicit middleware configured in Startup.cs/Program.cs.
  • Classic MVC uses HTTP Modules & Handlers that are configured in web.config.
  1. Lightweight & Modular:
  • ASP.NET Core is lighter, cross-platform, and faster.
  • MVC is tied to System.Web, Windows-only, and heavier.
  1. Dependency Injection (DI):
  • ASP.NET Core has built-in DI; you can inject services everywhere.
  • Classic MVC requires third-party DI frameworks like Ninject, Autofac.
  1. Request Pipeline Control:
  • In Core, you have full control over the request pipeline order.
  • In classic MVC, the pipeline order is mostly predefined and less flexible.
  1. Hosting & Environment:
  • Core apps can run on Kestrel, IIS, or self-hosted.
  • Classic MVC only runs on IIS.




🇬🇧 What is the purpose of MVC architecture?

The MVC (Model–View–Controller) architecture is designed to separate the application into three main components, which makes the code cleaner, more organized, and easier to maintain.

🎯 Purpose:

  • To separate concerns — each layer has its own responsibility.
  • To make the app easier to test, scale, and modify without breaking everything.

🧩 Main Components:

  1. Model
  2. Handles data, business logic, and database interaction.
  3. (Example: getting data from SQL Server, applying calculations.)
  4. View
  5. Handles the presentation/UI — what the user sees (HTML, CSS, Razor).
  6. It should not contain logic except for displaying data.
  7. Controller
  8. Acts as the “middleman” between Model and View.
  9. It receives requests, processes data (via Model), and returns the right View.

💡 Example in short:

When a user requests a page:

  • The Controller handles the request.
  • It calls the Model to get or modify data.
  • Then it sends that data to the View for display.


What is the purpose of the Model in MVC architecture?


The Model in MVC represents the data, business logic, and rules of the application.

It is the core part that deals with how data is stored, processed, and validated.

🎯 Main Purposes:

  1. Manages Data:
  2. The Model is responsible for retrieving data from the database and saving changes back to it.
  3. (e.g., using Entity Framework or ADO.NET)
  4. Applies Business Logic:
  5. It contains rules and logic — like calculations, validations, or conditions — that define how the system behaves.
  6. Isolates Logic from UI:
  7. The Model doesn’t care how data looks on the screen — it only focuses on the data itself and its behavior.

💡 Example:

If you’re building a student management system,

a Student model might have:

  • Properties: Name, Grade, Email
  • Logic: automatically calculate average grade or check if the student passed.


What is a ViewModel in ASP.NET MVC?


A ViewModel is a class that’s specifically designed to pass data between the Controller and the View.

It contains only the data that the View needs — nothing more, nothing less.

Think of it as a custom-shaped container that combines data from one or more models, or adds extra fields for displaying purposes.

💡 Example conceptually (without code):

Imagine you have two models: Student and Course.

If your page (View) needs to display a student's name and their enrolled courses, you don’t want to send both models separately — you create a ViewModel that combines just those needed pieces.

🧠 Purpose:

  • To decouple your database models from your UI
  • To simplify data passing between Controller → View
  • To avoid overexposing unnecessary fields from your database

In short:

Model = represents data in the database
ViewModel = represents data for the View (UI)



What are View Data, View Bag, and Temp Data in ASP.NET MVC?

These three are all used to pass data from the Controller to the View,

but each one works a little differently in how long the data “lives”.

🧩 1. ViewData

  • Type: ViewDataDictionary
  • Works like a dictionary (key-value pairs).
  • Data exists only for the current request (Controller → View).
  • You have to cast data when retrieving it because it’s stored as an object.

🧠 Example idea: use it for simple one-time data like a message or title.

🧩 2. ViewBag

  • Type: Dynamic property built on top of ViewData.
  • Easier to use (no casting), more “friendly” syntax.
  • Also exists only during the current request.

So basically, ViewBag is just a simpler wrapper around ViewData.


🧩 3. TempData

  • Type: TempDataDictionary
  • Stores data until it’s read, even after a redirect to another action.
  • Great for messages or alerts that you want to show after redirecting (like “User saved successfully!”).





What are Partial Views and Layout Pages in ASP.NET MVC?


Partial View


A Partial View is like a reusable piece of a web page.

You use it when you have a section that repeats across multiple pages — like a sidebar, header, or list.

It helps you:

  • Avoid duplicating HTML.
  • Keep your code clean and organized.
  • Update UI components in one place instead of many.

🧠 Think of it as a “mini-view” inside a bigger page.


🧱 Layout Page


A Layout Page is the master template of your website.

It defines the overall structure — header, footer, navigation, etc.

Your other views just “plug into” this layout using the @RenderBody() placeholder.

Benefits:

  • Ensures consistency across pages.
  • Easier maintenance (change layout once → all pages update).

⚖️ In short:

  • Partial View → small reusable section (part of a page).
  • Layout Page → main structure shared by all pages.

Partial View

A Partial View is like a reusable piece of a web page.

You use it when you have a section that repeats across multiple pages — like a sidebar, header, or list.

It helps you:

  • Avoid duplicating HTML.
  • Keep your code clean and organized.
  • Update UI components in one place instead of many.

🧠 Think of it as a “mini-view” inside a bigger page.

🧱 Layout Page

A Layout Page is the master template of your website.

It defines the overall structure — header, footer, navigation, etc.

Your other views just “plug into” this layout using the @RenderBody() placeholder.

Benefits:

  • Ensures consistency across pages.
  • Easier maintenance (change layout once → all pages update).

⚖️ In short:

  • Partial View → small reusable section (part of a page).
  • Layout Page → main structure shared by all pages.

Partial View


A Partial View is like a reusable piece of a web page.

You use it when you have a section that repeats across multiple pages — like a sidebar, header, or list.

It helps you:

  • Avoid duplicating HTML.
  • Keep your code clean and organized.
  • Update UI components in one place instead of many.

🧠 Think of it as a “mini-view” inside a bigger page.

🧱 Layout Page

A Layout Page is the master template of your website.

It defines the overall structure — header, footer, navigation, etc.

Your other views just “plug into” this layout using the @RenderBody() placeholder.

Benefits:

  • Ensures consistency across pages.
  • Easier maintenance (change layout once → all pages update).

⚖️ In short:

  • Partial View → small reusable section (part of a page).
  • Layout Page → main structure shared by all pages.

Partial View

A Partial View is like a reusable piece of a web page.

You use it when you have a section that repeats across multiple pages — like a sidebar, header, or list.

It helps you:

  • Avoid duplicating HTML.
  • Keep your code clean and organized.
  • Update UI components in one place instead of many.

🧠 Think of it as a “mini-view” inside a bigger page.

🧱 Layout Page

A Layout Page is the master template of your website.

It defines the overall structure — header, footer, navigation, etc.

Your other views just “plug into” this layout using the @RenderBody() placeholder.

Benefits:

  • Ensures consistency across pages.
  • Easier maintenance (change layout once → all pages update).

⚖️ In short:

  • Partial View → small reusable section (part of a page).
  • Layout Page → main structure shared by all pages.



Partial View

A Partial View is like a reusable piece of a web page.

You use it when you have a section that repeats across multiple pages — like a sidebar, header, or list.

It helps you:

  • Avoid duplicating HTML.
  • Keep your code clean and organized.
  • Update UI components in one place instead of many.

🧠 Think of it as a “mini-view” inside a bigger page.


🧱 Layout Page

A Layout Page is the master template of your website.

It defines the overall structure — header, footer, navigation, etc.

Your other views just “plug into” this layout using the @RenderBody() placeholder.

Benefits:

  • Ensures consistency across pages.
  • Easier maintenance (change layout once → all pages update).

⚖️ In short:

  • Partial View → small reusable section (part of a page).
  • Layout Page → main structure shared by all pages.


Razor Syntax in ASP.NET Core?


Razor is a lightweight syntax used to write server-side code inside HTML.

It’s part of the View Engine, allowing you to mix C# code and HTML in one file (like .cshtml).

🧠 Purpose:

  • Helps you dynamically generate HTML on the server before sending it to the browser.
  • Keeps your code clean and readable, without having to use lots of <% %> tags (like old ASP).

🧩 Example of what Razor does:

Instead of embedding C# code with old-style syntax, Razor uses @ to switch between HTML and C# easily.

Benefits:

  • Simple and fast to write.
  • Automatically encodes data (protects against XSS).
  • Integrates smoothly with MVC models and controllers.



🇬🇧 Tag Helpers

Tag Helpers make it easier to work with HTML elements using C# logic —

They look like regular HTML tags but add server-side power to them.

For example:

Instead of writing @Html.ActionLink(), you can just use:

<a asp-controller="Home" asp-action="Index">Home</a>

and Razor will generate the right link automatically.

🧠 Purpose:

  • Makes your HTML more natural and intuitive.
  • Reduces the need for @Html.* helpers.
  • Easier to read and maintain.




which used for client-side validation in ASP.NET MVC?

When you enable client-side validation in ASP.NET MVC, the framework uses data- attributes* (like data-val, data-val-required, etc.) in the HTML elements.

These attributes are then interpreted by the jQuery Validation plugin to perform validation on the client (browser) without submitting the form.



Summary:

Client-side validation: jQuery Validation + Unobtrusive JavaScript.

Server-side validation: Data Annotations + ModelState.IsValid.




 What is the purpose of the RouteConfig.cs file in ASP.NET MVC?



In ASP.NET MVC, the RouteConfig.cs file is used to define the routing rules of your application.

Routing is the process that maps incoming URLs to specific controller actions.

For example, when a user visits /Products/Details/5, the routing engine figures out that it should call the Details action of the ProductsController and pass 5 as a parameter.

The purpose of RouteConfig.cs is to centralize all these URL patterns so that your application knows how to respond to requests.

It also allows you to define default routes, optional parameters, and even custom routes for specific cases.



what's Attribute Routing?



Attribute Routing is a way to define routes directly on controller actions or controllers using attributes, instead of defining them all in RouteConfig.cs.

For example, you can put [Route("products/details/{id}")] on an action method, and ASP.NET MVC will automatically map that URL to the action.

Benefits:

  • Makes routes clearer and closer to the action they belong to.
  • Easier to maintain for large applications with many routes.
  • Supports more customized and complex URL patterns.

It doesn’t replace RouteConfig.cs completely but can be used together with conventional routing.




what's Action Results in ASP.NET MVC?

In ASP.NET MVC, Action Results are the responses that a controller action returns to the browser.

The framework provides different types of Action Results depending on what you want to send back:

  • ViewResult: Renders a view (HTML page).
  • JsonResult: Returns JSON data (used in APIs or AJAX).
  • RedirectResult / RedirectToActionResult: Redirects to another URL or action.
  • ContentResult: Returns plain text or custom content.
  • FileResult: Returns a file to download.
  • EmptyResult: Returns nothing.

The purpose is to abstract the response type so that your controller doesn’t need to handle the raw HTTP response manually.




Model Binding and Validation in ASP.NET MVC?


Model Binding is the process where ASP.NET MVC automatically maps HTTP request data (like form inputs, query strings, or route data) to parameters of your action methods or model objects.

This allows you to work with strongly typed objects directly in your actions instead of manually parsing form values.

Validation works hand-in-hand with model binding. You can use Data Annotations in your models to define rules like required fields, string lengths, ranges, or custom validations.

  • Client-side validation happens in the browser using jQuery Validation.
  • Server-side validation happens in the controller using ModelState.IsValid.

This ensures data integrity and improves user experience by showing errors before or after submission.






Filters vs Middleware in ASP.NET MVC/Core?


Filters in ASP.NET MVC are action-level or controller-level components that let you execute code before or after an action method runs.

Types of filters include:

  • Authorization filters – check user permissions.
  • Action filters – run code before/after an action.
  • Exception filters – handle exceptions globally or per-controller.
  • Result filters – run code before/after rendering the result.

Filters are closer to the MVC pipeline and are aware of controllers, actions, and models.

Middleware in ASP.NET Core works at a lower, application-level pipeline. It intercepts HTTP requests and responses as they flow through the app, before reaching MVC.

  • Middleware is useful for cross-cutting concerns like logging, authentication, error handling, CORS, or response compression.
  • Middleware runs globally for every request, not per controller/action.

Key difference:

  • Filters: Controller/action specific, part of MVC.
  • Middleware: Global, part of the HTTP pipeline, unaware of MVC specifics.




what's Dependency Injection?



Dependency Injection (DI) is a design pattern that lets you inject the dependencies a class needs instead of the class creating them itself.

  • This improves loose coupling, testability, and maintainability.
  • In ASP.NET Core, DI is built-in, and services are usually registered in Program.cs or Startup.cs.

How to register services:

  • You tell the DI container what implementation to use for an interface or class.

Three main lifetimes/types of services:

  1. Singleton: One instance is created and shared throughout the app’s lifetime.
  2. Scoped: One instance per HTTP request.
  3. Transient: A new instance every time the service is requested.

This allows precise control over how long each service lives and when it’s reused.



hink of Dependency Injection (DI) like ordering coffee at a café instead of making it yourself.

  • Your class (the customer) doesn’t make the coffee (dependency).
  • The café (DI container) gives you the coffee ready to use.
  • This way, your class just uses it and doesn’t worry about how it’s made.

Service lifetimes in simple terms:

  1. Singleton:
  • Only one coffee machine for the whole café. Everyone gets coffee from the same machine.
  • In code: One instance for the entire app lifetime.
  1. Scoped:
  • Each table gets its own coffee machine, but everyone at the same table shares it.
  • In code: One instance per HTTP request.
  1. Transient:
  • Every person gets their own coffee machine.
  • In code: A new instance every time it’s requested.

So, DI helps your classes focus on what they need without worrying about how it’s created, and lifetimes control how often the instance is reused.


Types of Dependency Injection

  1. Constructor Injection – injected through the constructor (most common).
  2. Property Injection – injected via a public property.
  3. Method Injection – injected through a method parameter.



What is the purpose of the [ValidateAntiForgeryToken] attribute in ASP.NET MVC?



The [ValidateAntiForgeryToken] attribute is used in ASP.NET MVC to protect forms from Cross-Site Request Forgery (CSRF) attacks.

  • CSRF happens when a malicious site tricks a logged-in user’s browser into submitting a request to your site without their knowledge.
  • When you use [ValidateAntiForgeryToken], MVC checks for a hidden token in the form submission that matches the token stored in the user’s session or cookie.
  • If the token is missing or doesn’t match, the request is rejected, preventing unauthorized actions.

Purpose: Ensures that only forms generated by your site can be submitted, keeping your application secure.





what's Middleware & Request Pipeline in ASP.NET Core?


In ASP.NET Core, middleware are components that process HTTP requests and responses as they move through the request pipeline.

Each middleware can do something before or after the next component in the pipeline runs.

For example:

  • Authentication middleware checks if the user is logged in.
  • Routing middleware decides which controller or endpoint should handle the request.
  • Exception middleware handles errors globally.
  • Static file middleware serves images, CSS, or JS files directly.

👉 The order of middleware matters — ASP.NET Core processes them in the same order they are registered in the Program.cs (or previously Startup.cs).

You register them using methods like:

  • app.Use() → adds middleware that both reads and passes control to the next one.
  • app.Run() → adds a terminal middleware that ends the pipeline.
  • app.Map() → conditionally branches the pipeline (e.g., for /api routes).

In short:

Middleware = building blocks that handle requests step by step before the response goes back to the client.




Which annotation is used for model validation to specify that a property must have a value?

The [Required] attribute is used in ASP.NET MVC/Core to ensure that a property in a model must have a value.

  • If the property is empty or null, validation will fail, and an error message can be displayed.
  • It’s commonly used in forms to make sure users don’t leave fields blank.
  • Works both on the server-side and, when combined with unobtrusive validation, on the client-side too.

Example use case: Name, Email, or Password fields that must be filled in a form.




What is the main difference between ASP.NET MVC and ASP.NET Web API?


Difference between ASP.NET MVC and Web API:

ASP.NET MVC is mainly used to build web applications that return HTML views.

  • You typically render pages that the user sees in the browser.
  • Controllers return View() results.
  • Supports Razor views and full MVC pattern (Model-View-Controller).

ASP.NET Web API is used to build RESTful services that return data (like JSON or XML).

  • It’s for client applications (like mobile apps, SPAs, or other services) to consume.
  • Controllers return data objects rather than views.
  • Focuses on HTTP verbs (GET, POST, PUT, DELETE).

In short: MVC = for HTML pages, Web API = for data/services.




what's the CQRS(Command and Query Responsibility Segregation)?


CQRS stands for Command and Query Responsibility Segregation — a design pattern that separates reading data (Queries) from writing/updating data (Commands).

Instead of having one big service or repository that does everything (insert, update, get), you split them into two sides:

  • Command Side: Handles create, update, delete operations.
  • Query Side: Handles read operations (fetching data).

🧠 Benefits:

  • Better scalability — you can optimize reads and writes separately.
  • Easier to maintain and test.
  • Works great with MediatR, Event Sourcing, and Microservices.

🧩 Example:

Instead of one big UserService, you’d have:

  • CreateUserCommandHandler
  • GetUserByIdQueryHandler

Each does only one responsibility.



MediatR in .NET?


MediatR is a lightweight library for implementing CQRS and Mediator Pattern in .NET.

It helps you decouple your controllers from the business logic.

Instead of the controller calling services directly, it sends a Request (Command or Query) to a Handler.


CQRS + MediatR still perform CRUD operations,

but they do it in a cleaner, more structured way — not the traditional MVC way.

In traditional MVC:

  • Controller directly calls Service/Repository.
  • Service has all methods:
  • AddUser(), GetUser(), UpdateUser(), DeleteUser().

In CQRS:

  • Each operation (Create, Read, Update, Delete) becomes its own Handler.
  • Controller sends a Command (for write) or Query (for read) to MediatR.
  • MediatR finds the right handler to execute it.

🎯 The result:

  • Better separation of concerns.
  • Easier maintenance and testing.
  • Supports scaling (you can handle read and write separately).
  • Cleaner and more modular architecture.




Return Types of Controller in in ASP.NET Web API?


🧩 1. IActionResult (or ActionResult)

➡️ This is the most flexible and recommended return type.

It allows you to return different kinds of responses — like Ok(), NotFound(), BadRequest(), etc.

Example in words:

If everything goes fine → return Ok(data)

If there’s a problem → return BadRequest("Invalid input")

In short:

Use IActionResult when you want to return both data and HTTP status codes.




 2. ActionResult<T>

➡️ This is a generic version of ActionResult.

It combines the benefits of returning a specific data type and also HTTP status codes.

Example in words:

You can return ActionResult<User> → means it can return a User object or an error response.

In short:

Use ActionResult<T> when you want both type safety and flexible responses.

3. Specific Type (e.g., string, int, object, IEnumerable<T>)

➡️ You can directly return data types — like a string, list, or object.

ASP.NET automatically serializes them to JSON (by default).

In short:

Simple and quick, but limited — can’t return status codes easily.



4. HttpResponseMessage

➡️ This is the old style used more in classic Web API.

It gives you full control over the HTTP response — headers, status codes, content, etc.

In short:

Gives full manual control, but not commonly used in ASP.NET Core.

🧩 5. JsonResult

➡️ Returns JSON data directly to the client.

Usually used when you want to force JSON output, regardless of request headers.

In short:

Used when you specifically want to return JSON



 What is Serialization and Deserialization?

Serialization


Serialization is the process of converting an object into a format that can be stored or transferred (such as JSON, XML, or binary).

Goal: save the object's data or send it over a network.

Example use cases:

  • Sending objects in Web APIs (JSON)
  • Saving data to files
  • Caching objects
  • Messaging systems (RabbitMQ, Kafka)

Deserialization

English

Deserialization is the process of converting the stored/transferred data (JSON, XML, etc.) back into an object.



Simple Example (Concept Only)

Before:

{ "name": "Osama", "age": 25 }

After Deserialization:

Person obj = new Person("Osama", 25)




HTTP Verbs in ASP.NET Web API ?



1. GET

  • Used to retrieve data from the server.
  • It’s a read-only operation — it doesn’t change anything in the database.
  • Example: GET /api/users → fetches all users.
  • Response: Usually returns 200 OK with JSON data.

✉️ 2. POST

  • Used to create a new resource on the server.
  • The data is usually sent in the request body.
  • Example: POST /api/users with { "name": "Osama" } → creates a new user.
  • Response: Usually returns 201 Created and the new resource.

🛠️ 3. PUT

  • Used to replace an existing resource completely.
  • You send the full updated object — even fields that didn’t change.
  • Example:
  • If user has {name: "Osama", age: 25},
  • and you send {name: "Osama Ayesh"},
  • the old age might be replaced or lost unless you include it again.
  • Response: Usually 200 OK or 204 No Content.

🔧 4. PATCH

  • Used to update only part of a resource (partial update).
  • You send only the fields you want to change.
  • Example:
  • If you just want to update name, send { "name": "Osama Ayesh" } only —
  • the rest of the object stays the same.
  • Response: Usually 200 OK.

🗑️ 5. DELETE

  • Used to delete a resource from the server.
  • Example: DELETE /api/users/5 → deletes the user with ID = 5.
  • Response: Usually 204 No Content if deletion is successful.



what's SOLID Principles?


The SOLID principles are five design principles created by Robert C. Martin (Uncle Bob).

They help developers write cleaner, maintainable, and scalable code.


1. S – Single Responsibility Principle (SRP)


Each class should have only one reason to change.

➡️ A class should do one thing only, and do it well.

If a class handles too many responsibilities (like logging, saving, validation), it becomes hard to maintain and test.

In short:

One class = One job.



🧩 2. O – Open/Closed Principle (OCP)

Software entities should be open for extension, but closed for modification.

➡️ You shouldn’t modify existing code to add new functionality — instead, you extend it (e.g., using inheritance or interfaces).

In short:

Add new features by extending, not by changing.


🧩 3. L – Liskov Substitution Principle (LSP)

Subclasses should be substitutable for their base classes.

➡️ If class B inherits from class A, you should be able to use B wherever A is expected, without breaking the program.

In short:

Child classes must behave like their parent classes.

🧩 4. I – Interface Segregation Principle (ISP)

Clients should not be forced to depend on methods they do not use.

➡️ Instead of one large interface, create smaller, more specific interfaces.

In short:

Many small interfaces are better than one big one.

5. D – Dependency Inversion Principle (DIP)

Depend on abstractions, not on concrete implementations.

➡️ High-level modules shouldn’t depend on low-level modules — both should depend on abstractions (interfaces).

In short:

Code should depend on what something does, not how it does it.



what's Design Principles?


Design Principles are guidelines to write clean, maintainable, and scalable code. They help developers structure applications in a way that’s easier to understand, test, and extend.

Some key design principles:

  1. SOLID Principles: Five core principles for object-oriented design (Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion).
  2. DRY (Don’t Repeat Yourself): Avoid duplicating code; reuse logic instead.
  3. KISS (Keep It Simple, Stupid): Write simple, clear, and understandable code.
  4. YAGNI (You Aren’t Gonna Need It): Don’t implement features before they are necessary.
  5. Separation of Concerns: Each part of the code should handle one responsibility.

Goal: Reduce complexity, avoid bugs, and make future changes easier.




what's Agile Methodology?

Agile is a software development approach that focuses on:

  • Flexibility: Adapting to changes quickly.
  • Collaboration: Developers, testers, and stakeholders work closely together.
  • Iterative Progress: Projects are delivered in small, incremental pieces called sprints.

Key points:

  • Work is divided into short cycles (usually 1–4 weeks).
  • Each sprint produces a potentially shippable product increment.
  • Agile emphasizes continuous feedback, customer involvement, and team communication.

Popular Agile frameworks: Scrum, Kanban, Lean.




Okey what's Scrum ?



Scrum is a framework that helps teams organize their work when developing software. The idea is to break the work into short cycles called "Sprints," and each Sprint has clear goals. By the end of each Sprint, there should be a usable or reviewable piece of work.

The team holds a quick daily meeting called the "Daily Scrum" to discuss what they did, what they’ll do next, and any blockers they’re facing.

There are three main roles:

  • Product Owner: decides what’s most important to work on.
  • Scrum Master: ensures the team follows Scrum and helps remove obstacles.
  • Development Team: the people who actually build and deliver the work.

Scrum helps teams stay flexible, adapt to changes, and deliver working results regularly.





what's most services used for real connection in .net core ?

1. Chatbot Integration Services

  • It’s Microsoft’s official platform for building intelligent chatbots.
  • It works seamlessly with .NET through its dedicated SDK.
  • You can connect it with:
  • Azure Bot Service (for cloud hosting)
  • Microsoft Teams, Telegram, Slack, Facebook Messenger, etc.
  • It supports LUIS (Language Understanding Intelligent Service) for natural language processing (NLP).



💌 2. Email Notification Services

English:

.NET offers built-in support for sending emails using SMTP.

  • You can use System.Net.Mail.SmtpClient or the modern MailKit library.
  • Common use cases: sending account confirmations, password resets, and system alerts.
  • You can also integrate with services like SendGrid, Mailgun, or Amazon SES for better scalability.


🔔 3. In-App Notification Services (Real-Time Notifications)


For in-app notifications or live updates (like chat, dashboards, or alerts), .NET provides SignalR.

  • SignalR is a real-time communication library.
  • It uses WebSockets primarily but can fall back to Long Polling if needed.
  • Perfect for: chat apps, real-time dashboards, or live user updates.


📱 4. Push Notifications (Mobile / Web)


If you want to send notifications directly to users’ devices or browsers:

  • Use Firebase Cloud Messaging (FCM) — integrates easily with .NET APIs to send notifications to Android/iOS.
  • Or Azure Notification Hubs — Microsoft’s cloud service for managing push notifications across multiple platforms.


What is RabbitMQ?

RabbitMQ is one of the most popular message queueing systems (Message Brokers) used in .NET and ASP.NET Core applications.

It acts as a middle layer that receives messages (tasks or data) from one part of your system and delivers them to another part — usually in a queue-based, asynchronous manner.

Instead of making your app process every heavy task immediately (which could slow it down), RabbitMQ lets you send the task into a queue — then a background worker (called a Consumer) picks it up and executes it when resources are available.

🎯 Why use RabbitMQ in ASP.NET Core?

⚙️ 1. Decoupling Services

It allows you to separate components of your system.

For example, the User API doesn’t need to communicate directly with the Email Service — it just drops a “SendEmail” message into the queue, and the email service handles it later.

🚀 2. Performance

Your API stays fast and responsive, since it doesn’t wait for time-consuming tasks (like sending emails or processing files).

The request completes instantly after pushing the job to RabbitMQ.

🔄 3. Reliability / Retry Mechanism

If a consumer service goes down, the message stays in the queue until it’s back online — ensuring that no data or task is lost.

🔔 4. Notifications / Event Bus

RabbitMQ can act as an Event Bus — whenever something happens (like “user registered”), it broadcasts that event to other services (for example, to send notifications or update analytics).

💼 Common Use Cases in .NET

  1. Email / Notification Queue
  2. When a user registers, the system doesn’t send the email immediately — it places a SendEmail message in the queue, and a background service processes it.
  3. Chat Message Queue
  4. Used in chat applications or chatbot systems to guarantee message order, reliability, and delivery confirmation.
  5. Background Jobs
  6. Tasks like generating PDFs, image processing, report generation, or large-scale notifications are executed asynchronously through RabbitMQ.


In short:

🧠 RabbitMQ helps your system scale smoothly by decoupling tasks, improving performance, and ensuring reliability — all without blocking your main API thread.




WebSocket / SignalR

WebSocket (or SignalR in .NET) creates a direct and persistent connection between the server and the client. This means the server can push updates instantly to the user without waiting for the user to request them.

📱 Example: In a chat app You send a message → the server immediately delivers it to all connected users.

SignalR makes it easy for the server to send real-time notifications to clients — no need for refresh or polling.

🎯 Use Cases:

  • Real-time chat applications
  • Live dashboards
  • Instant in-app notifications
  • Collaborative tools (like whiteboards or multiplayer games)

🐇 RabbitMQ

RabbitMQ is a message broker — it works behind the scenes to queue and deliver messages between systems.

It’s great for background tasks like:

  • Sending emails
  • Processing orders
  • Logging activity
  • Integrating microservices

📌 Real-Life Analogy:

  • RabbitMQ is like a post office: You drop off a message, and it gets delivered later.
  • SignalR/WebSocket is like a phone call: You talk directly and instantly.

💡 Summary:

  • RabbitMQ → System-to-system communication, delayed or queued tasks
  • SignalR/WebSocket



Whats Continuous Integration (CI) & Continuous Deployment/Delivery (CD)

1️⃣ Continuous Integration (CI)

CI is the practice where developers frequently merge their code changes into a shared repository.

Each merge triggers automated builds and tests to ensure nothing breaks.

Goal: Catch issues early, reduce integration problems, and make the codebase more stable.

Example: Every time a developer pushes a change to GitHub, a CI pipeline runs tests automatically.

2️⃣ Continuous Deployment / Delivery (CD)

  • Continuous Delivery: The code is always in a deployable state, but deployment to production might still be manual.
  • Continuous Deployment: Every successful change automatically goes to production without manual steps.

Goal: Deliver new features and fixes quickly and reliably to users.

Example: After CI runs tests successfully, the system can automatically deploy the code to a staging or production environment.



Version Control & Git

Version Control is a system that tracks changes to your code over time, so you can recall specific versions later. It helps collaboration, backup, and tracking who changed what.

Git is the most popular version control system today. It allows developers to work on the same project simultaneously and merge changes safely.

Common Git Commands:

  • git init → initialize a new repository
  • git clone <repo> → copy a repository locally
  • git add <file> → stage changes
  • git commit -m "message" → save staged changes
  • git push → send changes to remote repository
  • git pull → fetch and merge changes from remote
  • git branch → list branches
  • git checkout <branch> → switch branch
  • git merge <branch> → merge another branch
  • git status → check current changes



What is Deployment / Hosting?

Deployment is the process of taking your application from your local development environment and making it available to users on a server or cloud.

Hosting is where your application lives online, meaning the server or environment that serves your app to users.

How to deploy/host an application:

  1. On a Windows Server / IIS:
  • Publish your .NET project (or any web project) from Visual Studio.
  • Copy files to the server.
  • Configure IIS to point to your app folder.
  1. On Linux Server:
  • Use Apache or Nginx as a web server.
  • Publish your app as a self-contained package.
  • Run it using systemd or Docker.
  1. Cloud Hosting (Azure, AWS, Google Cloud):
  • Push your code to the cloud service.
  • Configure services like App Service, EC2, or Elastic Beanstalk.
  • The cloud automatically hosts and scales your app.

Tips:

  • Make sure connection strings, secrets, and environment variables are configured for production.
  • Use CI/CD pipelines to automate deployment for smoother releases.


TLS/SSL Certificates & IIS

TLS/SSL Certificates are digital certificates used to encrypt data between a client (browser) and a server. They ensure:

  • Confidentiality: Data is protected from eavesdroppers.
  • Integrity: Data is not tampered with in transit.
  • Authentication: Users can verify they are connecting to the real server.

How it works on IIS:

  • IIS uses the certificate to enable HTTPS for your website.
  • When a user visits https://yourdomain.com, IIS presents the certificate.
  • The browser checks the certificate’s validity and encrypts communication with the server.

Types of certificates:

  • Self-signed: Generated by you for testing or internal use.
  • CA-signed: Issued by a Certificate Authority (like DigiCert, Let’s Encrypt) for production websites.




Popular .NET Services & Their Types?


🌐 Web Services / APIs

  • ASP.NET Core Web API → Used to build RESTful APIs for communication between clients and servers.
  • gRPC Services → High-performance, cross-platform communication between microservices or backend servers.

⚡ Real-time Communication

  • SignalR → Enables live chat, instant notifications, and real-time data updates inside applications.

🧩 Background Processing / Messaging

  • Hangfire / Quartz.NET → Handle scheduled or background jobs (e.g., sending emails, data cleanup).
  • RabbitMQ / Azure Service Bus → Manage asynchronous message delivery and communication between distributed systems or microservices.

🔐 Authentication & Identity

  • ASP.NET Identity → Manages user accounts, login, and roles in your application.
  • JWT Tokens / OAuth → Secure methods for authenticating users in APIs and mobile apps.

📬 Email & Notifications

  • Send emails directly from your application using SMTP, MailKit, or third-party services like SendGrid.
  • Use Push Notifications or SMS services (e.g., Firebase Cloud Messaging or Twilio) for user alerts and engagement.

⚙️ Caching & Performance

  • MemoryCache → Stores frequently used data in memory to improve speed.
  • DistributedCache → Works across multiple servers (e.g., Redis) to boost scalability and performance.




Popular .NET Services on Cloud & Types?Compute Services

  • Azure App Service / AWS Elastic Beanstalk Host web applications and APIs without managing servers directly.
  • Azure Functions / AWS Lambda Serverless functions that run on demand and charge per execution.
  • Azure Virtual Machines / AWS EC2 Full control over virtual servers for hosting apps or databases.

📦 Storage Services

  • Azure Blob Storage / AWS S3 Store files, images, and documents.
  • Azure File Storage / AWS EFS Shared file systems for applications.

🗃️ Database Services

  • Azure SQL Database / AWS RDS Managed relational databases.
  • Azure Cosmos DB / AWS DynamoDB NoSQL databases for flexible, scalable data.

🔄 Messaging & Event Services

  • Azure Service Bus / AWS SQS & SNS Messaging between services, background task coordination, and notifications.
  • Azure Event Hub / AWS Kinesis Real-time processing of large data streams.

🔐 Identity & Security

  • Azure Active Directory / AWS Cognito User identity management, secure login, and Single Sign-On.
  • Azure Key Vault / AWS Secrets Manager Secure storage for app secrets like passwords and API keys.

📊 Monitoring & Logging

  • Azure Application Insights / AWS CloudWatch Monitor app performance, log errors, and receive alerts.

🚀 DevOps & CI/CD

  • Azure DevOps / GitHub Actions / AWS Code Pipeline Automate deployment from code to production.










1️⃣ What is Angular?


Angular is a front-end framework developed by Google for building single-page applications (SPAs) using TypeScript.

It provides tools for building dynamic, modular, and reactive web apps easily.


2️⃣ What is the difference between AngularJS and Angular (2+)?



AngularJS (version 1.x) is based on JavaScript, while Angular (2+) is a complete rewrite that uses TypeScript.

Angular (2+) is faster, more modular, and follows component-based architecture.


3️⃣ What is a Component in Angular?



A component is the building block of an Angular application.

It controls a part of the UI using HTML, CSS, and TypeScript logic.


4️⃣ What is a Module?


A module is a container that groups related components, directives, pipes, and services.

It helps organize the application into smaller, manageable parts.



5️⃣ What is the purpose of app.module.ts?


app.module.ts is the root module of the Angular app.

It defines which components, modules, and services are part of the main application.



6️⃣ What is a Decorator in Angular?


A decorator is a special function (like @Component, @NgModule, @Injectable) that adds metadata to classes.

It tells Angular how to treat that class.




7️⃣ What is the difference between Interpolation, Property Binding, and Event Binding?


  • Interpolation ({{ }}): To show data from TypeScript in HTML.
  • Property Binding ([ ]): To bind data from component → to HTML property.
  • Event Binding (( )): To handle user actions like click or input.


8️⃣ What is Two-Way Data Binding?


It means synchronization between the UI and the component — if the user changes data in the UI, it updates in the code, and vice versa.

It uses [(ngModel)].


.

9️⃣ What is a Directive in Angular?

A directive is a class that changes the behavior or appearance of elements in the DOM.

Examples: *ngIf, *ngFor, [ngClass].


.

🔟 Difference between Structural and Attribute Directives

  • Structural directives (like *ngIf, *ngFor) change the DOM structure — they add or remove elements.
  • Attribute directives (like [ngClass], [ngStyle]) change the appearance or behavior of existing elements.






Keyboard