MPSeDC GET Program 3.0 2026 – Exam-Oriented .NET MCQ Questions

MPSeDC GET Program 3.0 2026 – Exam-Oriented .NET MCQ Questions

BEGINNER LEVEL

Q1: What is the full form of CLR in .NET?
A. Common Library Runtime
B. Common Language Runtime
C. Compiled Language Runtime
D. Core Language Runtime

Correct Answer: B
Explanation: CLR (Common Language Runtime) is the virtual machine of .NET that manages execution — garbage collection, type safety, exception handling, JIT compilation, and thread management. All .NET languages compile to MSIL which CLR’s JIT converts to native code at runtime.
Exam Trick: CLR = Common Language Runtime. It is the ENGINE of .NET. No CLR = no .NET execution.


Q2: What is MSIL in the .NET Framework?
A. Microsoft Standard Interface Library
B. Microsoft Intermediate Language — CPU-independent bytecode all .NET languages compile to
C. Memory Segment Integration Layer
D. Managed System Interface Layer

Correct Answer: B
Explanation: MSIL (Microsoft Intermediate Language), also called CIL (Common Intermediate Language), is the CPU-independent instruction set that all .NET languages (C#, VB.NET, F#) compile to. The CLR’s JIT compiler then converts MSIL to native machine code at runtime. This enables cross-language interoperability.
Exam Trick: MSIL = CIL = IL. C# source -> MSIL -> JIT -> Native machine code. Think: MSIL is .NET’s bytecode like Java’s bytecode.


Q3: Which is the ROOT namespace of the .NET Framework Class Library?
A. System.IO
B. System.Collections
C. System
D. Microsoft.NET

Correct Answer: C
Explanation: The ‘System’ namespace is the root and most fundamental namespace in the .NET FCL. It contains: Object (base of all types), String, Int32, Console, Math, Exception. All sub-namespaces like System.IO, System.Collections, System.Data are children of System.
Exam Trick: Root namespace = System. System.Object is the base of EVERYTHING in .NET. ‘It all starts with System.’


Q4: What is the size of ‘int’ (System.Int32) in C#?
A. 2 bytes
B. 8 bytes
C. 4 bytes
D. Platform-dependent

Correct Answer: C
Explanation: In C#, ‘int’ maps to System.Int32 and is ALWAYS 4 bytes (32 bits) regardless of platform (32-bit or 64-bit). Range: -2,147,483,648 to 2,147,483,647. C# has fixed-size types unlike C/C++. short=2 bytes, int=4 bytes, long=8 bytes.
Exam Trick: Memory: byte=1, short=2, int=4, long=8 bytes. int is ALWAYS 4 bytes in C#. Not platform-dependent!


Q5: Which keyword declares a compile-time constant in C#?
A. readonly
B. static
C. final
D. const

Correct Answer: D
Explanation: ‘const’ declares a compile-time constant — value set at declaration and cannot change ever. ‘readonly’ is a runtime constant — set in constructor. ‘final’ is Java’s keyword (not C#). ‘static’ makes members belong to the type. const is implicitly static.
Exam Trick: const = compile-time (must set NOW). readonly = runtime (set in constructor). No ‘final’ in C# — that’s Java!


Q6: What is the output of: Console.WriteLine(10 / 3);
A. 3.33
B. 3.0
C. Error
D. 3

Correct Answer: D
Explanation: Both 10 and 3 are int literals, so C# performs INTEGER division — divides and discards remainder. 10/3 = 3 (not 3.33). For decimal result: (double)10/3 or 10.0/3. This integer division trap is a very common exam question.
Exam Trick: int / int = int result (truncated). 10/3 = 3. For 3.33: use 10.0/3 or (double)10/3. Classic exam trap!


Q7: What is the default value of a bool variable in C# (class field)?
A. null
B. true
C. 0
D. false

Correct Answer: D
Explanation: Default values in C#: bool=false, int/long/short=0, double/float=0.0, char=’\0′, string=null, reference types=null. This applies to class-level fields. Local variables in methods MUST be explicitly initialized before use.
Exam Trick: Defaults: bool=false, int=0, string=null. ‘false, 0, null’ — the three default zeros of C#.


Q8: Which of the following is a VALUE type in C#?
A. string
B. array
C. class
D. struct

Correct Answer: D
Explanation: struct is a value type stored on the stack. Value types: struct, enum, int, double, bool, char, decimal, float, long, short, byte. Reference types (heap): class, interface, delegate, array, string. Key: value types are copied on assignment; reference types share the same object.
Exam Trick: Value types = struct, enum, primitives (stack). Reference types = class, array, string, interface (heap). Struct = value type!


Q9: What are the TWO roles of the ‘using’ keyword in C#?
A. Only imports namespaces
B. Only manages resources
C. Imports namespaces AND manages IDisposable resources (ensures Dispose() is called)
D. Declares a class alias and creates threads

Correct Answer: C
Explanation: ‘using’ has 2 roles: (1) Directive: ‘using System;’ — imports namespace, avoids fully qualifying type names. (2) Statement: ‘using (var r = new StreamReader(..)) { }’ — ensures IDisposable.Dispose() is called even if exception occurs (equivalent to try-finally with Dispose in finally).
Exam Trick: using = 2 roles: (1) namespace import, (2) IDisposable resource management. using stmt = try-finally with Dispose().


Q10: How do you declare a single-dimensional array of 5 integers in C#?
A. int arr[5];
B. int arr = new int(5);
C. array<int> arr(5);
D. int[] arr = new int[5];

Correct Answer: D
Explanation: C# array syntax: int[] arr = new int[5]; The [] goes AFTER the type (not after the variable name). Arrays are reference types (objects) in C#, created with ‘new’. Default initialization: numeric arrays to 0, bool to false, reference arrays to null.
Exam Trick: C# array: type[] name = new type[size]; NOT type name[size] (that’s C/C++). [] after type. Arrays are objects in C#.


Q11: Which property returns the number of characters in a string in C#?
A. .Count()
B. .Size()
C. .Length
D. .GetLength()

Correct Answer: C
Explanation: String.Length is a PROPERTY (not a method — no parentheses) returning the number of chars. ‘Hello’.Length = 5. It is O(1) since string stores its length internally. Note: for List<T> use .Count property; for arrays use .Length property. String.Count() (LINQ) also works but is slower.
Exam Trick: .Length is a PROPERTY (no parentheses). string.Length vs List.Count vs Array.Length — know the difference!


Q12: Which OOP concept allows a class to inherit members from another class?
A. Encapsulation
B. Abstraction
C. Polymorphism
D. Inheritance

Correct Answer: D
Explanation: Inheritance allows a derived (child) class to inherit members (fields, methods, properties) from a base (parent) class. In C#: class Dog : Animal { }. C# supports single inheritance for classes but multiple interface implementation. The derived class gets all non-private members of the base class.
Exam Trick: Inheritance = IS-A relationship. Dog IS-A Animal. C# uses : for inheritance. Single class, multiple interfaces.


Q13: What is encapsulation in OOP?
A. Creating multiple instances of a class
B. Inheriting from multiple classes
C. Converting one type to another
D. Hiding implementation and exposing only necessary functionality via access modifiers

Correct Answer: D
Explanation: Encapsulation bundles data (fields) and methods in a class, restricting access to internals using access modifiers (private, protected, internal, public). Implemented via properties in C#. Protects data integrity and hides complexity.
Exam Trick: Encapsulation = Data hiding + bundling. Private fields + public properties. Like a capsule hiding its contents.


Q14: Which access modifier makes a member accessible ONLY within the same class?
A. public
B. protected
C. internal
D. private

Correct Answer: D
Explanation: Access modifiers (most to least restrictive): private (same class only) < protected (class + derived) < internal (same assembly) < protected internal (assembly OR derived) < public (everywhere). private is the DEFAULT for class members if no modifier is specified.
Exam Trick: private = most restrictive. Default for class members. public = anywhere. Remember: private < protected < internal < public.


Q15: What keyword creates an object of a class in C#?
A. create
B. object
C. instance
D. new

Correct Answer: D
Explanation: ‘new’ allocates memory on the heap, calls the constructor, and returns a reference. Dog d = new Dog(); In C# 9+: Dog d = new(); (target-typed new). ‘new’ also hides inherited members when used as a method modifier. Without new, no heap allocation occurs.
Exam Trick: new = create object = heap allocation + constructor call. Dog d = new Dog(); ‘new’ is the creation keyword.


Q16: What is a constructor in C#?
A. A method to destroy objects
B. A method that returns the class type
C. A special method with same name as class, no return type, called automatically on object creation
D. A method to copy objects

Correct Answer: C
Explanation: Constructor: same name as class, NO return type (not even void), called automatically with ‘new’. Types: Default (parameterless), Parameterized, Static (class-level init). If you don’t define one, C# provides a free default constructor. Constructors can be chained with : this() or : base().
Exam Trick: Constructor: same name as class, no return type. Called with ‘new’. No return type = key distinguisher from methods.


Q17: For string comparison in C#, which is correct about ‘==’ and ‘.Equals()’?
A. == compares references; Equals() compares content for strings
B. They are completely different for strings
C. == is for value types only
D. == compares content for strings (overloaded); Equals() also compares content but supports StringComparison options

Correct Answer: D
Explanation: For strings in C#, ‘==’ is OVERLOADED to compare VALUE (content), not reference. So ‘Hello’==’Hello’ is true even for different string objects. .Equals() also compares content by default and accepts StringComparison enum for case-insensitive comparisons. For object type: == compares references.
Exam Trick: String ‘==’ compares content (overloaded). .Equals() also content + StringComparison options. For objects: == compares reference.


Q18: What will this code print? string s = “Hello”; Console.WriteLine(s.ToUpper());
A. hello
B. Hello
C. Error
D. HELLO

Correct Answer: D
Explanation: ToUpper() returns a NEW string with all characters in uppercase. CRITICAL: strings are IMMUTABLE in C# — s is unchanged. ToUpper() does NOT modify ‘s’, it returns a new string ‘HELLO’. Similarly ToLower(), Trim(), Replace() all return new strings. Output: HELLO.
Exam Trick: ToUpper() returns NEW string in uppercase. Strings are IMMUTABLE in C#. Original string ‘s’ is unchanged. Output: HELLO.


Q19: What is the index of the FIRST element in a C# array?
A. 1
B. -1
C. Depends on declaration
D. 0

Correct Answer: D
Explanation: C# arrays are 0-indexed — first element is at index 0. For int[] arr = new int[5], valid indices: 0,1,2,3,4. arr[5] throws IndexOutOfRangeException. Last valid index = arr.Length – 1. This is consistent across all .NET collections.
Exam Trick: C# arrays: 0-indexed. First = arr[0], Last = arr[arr.Length-1]. arr[Length] = IndexOutOfRangeException!


Q20: What is GAC in .NET?
A. Garbage Automatic Collector
B. Generic Array Collection
C. Global Application Configuration
D. Global Assembly Cache — machine-wide repository for shared assemblies

Correct Answer: D
Explanation: GAC (Global Assembly Cache) stores shared .NET assemblies accessible by multiple applications. Assemblies must be strongly named (public key token). Solves DLL Hell (versioning conflicts). Location: C:\Windows\assembly. Use GAC for shared libraries that multiple apps need.
Exam Trick: GAC = Global Assembly Cache. Shared assemblies. Requires strong naming. Solves DLL Hell. Like a global library shelf.


Q21: Which C# data type stores a single Unicode character?
A. string
B. byte
C. varchar
D. char

Correct Answer: D
Explanation: char (System.Char) stores ONE Unicode character (2 bytes, UTF-16). Use single quotes: char c = ‘A’; string uses double quotes and stores multiple chars. ‘varchar’ is SQL, not C#. char in C# is always 2 bytes (Unicode).
Exam Trick: char = single character with SINGLE quotes ‘A’. string = multiple chars with DOUBLE quotes “Hello”. char = 2 bytes.


Q22: What does ‘static’ mean in C#?
A. Makes a class immutable
B. Prevents inheritance
C. Creates abstract members
D. Makes members belong to the TYPE itself, not any instance — accessed via ClassName.Member

Correct Answer: D
Explanation: static makes a member (field, method, property, constructor) belong to the CLASS, not instances. Called as ClassName.Method(). Shared across all objects. Main() must be static because it’s called before any object exists. Static constructor runs once when the class is first used.
Exam Trick: static = belongs to CLASS (not instance). Access: ClassName.Method(). Shared by ALL objects. Main() must be static.


Q23: How many classes can a C# class directly inherit from?
A. Unlimited
B. Two classes
C. Multiple classes
D. Only ONE class

Correct Answer: D
Explanation: C# supports SINGLE inheritance for classes — one base class only. To get multiple inheritance behavior, implement MULTIPLE INTERFACES (interfaces support multiple implementation). This avoids the Diamond Problem. Abstract classes also follow single inheritance.
Exam Trick: C# = 1 base class + many interfaces. NOT multiple class inheritance. Interface = multiple implementation OK.


Q24: Which string method splits a string into an array of substrings?
A. .Break()
B. .Divide()
C. .Substring()
D. .Split()

Correct Answer: D
Explanation: String.Split() divides a string by a delimiter into a string array. Example: ‘a,b,c’.Split(‘,’) returns {‘a’,’b’,’c’}. Substring(start, length) extracts part of a string. Split() can take char[], string[], and StringSplitOptions (to remove empty entries). Very common in data processing.
Exam Trick: .Split() = string to array. .Substring(start,len) = extract part. .Join() = array to string. These three are often tested together.


Q25: What is the relationship between ‘string’ and ‘String’ in C#?
A. string is for single chars; String is for multiple
B. String is deprecated in .NET 6+
C. string is C# keyword; String is a different class
D. string is an alias for System.String — they are 100% identical

Correct Answer: D
Explanation: ‘string’ (lowercase) = C# keyword alias for System.String. Completely identical — compiler treats them as the same type. Similarly: int=System.Int32, bool=System.Boolean, double=System.Double. Convention: lowercase for variable declarations, System.String for static method calls like String.Format.
Exam Trick: string = System.String. int = System.Int32. bool = System.Boolean. Aliases are 100% identical. Convention: lowercase for vars.


Q26: What is the output? int[] arr = {3, 1, 4, 1, 5}; Console.WriteLine(arr.Length);
A. 4
B. 0
C. Error
D. 5

Correct Answer: D
Explanation: arr.Length returns the TOTAL number of elements in the array. The array {3,1,4,1,5} has 5 elements, so arr.Length = 5. Note: Length is a PROPERTY not a method. For multi-dimensional arrays use GetLength(dimension). For List<T> use .Count.
Exam Trick: arr.Length = number of elements. Array has 5 elements = Length is 5. Last index = Length-1 = 4. Output: 5.


Q27: What is a delegate in C#?
A. A method that runs automatically on a schedule
B. An interface with one method
C. A keyword for inheritance
D. A type-safe function pointer that holds references to methods with a matching signature

Correct Answer: D
Explanation: A delegate is a type-safe function pointer. It holds references to methods with a matching signature (return type + parameter types). Enables passing methods as parameters, callbacks, and events. Syntax: delegate returnType Name(params); Foundation for events, LINQ (lambda expressions), and async programming.
Exam Trick: Delegate = type-safe method reference. Foundation for events, LINQ, callbacks. ‘A pointer to a method’ in C#.


Q28: What does ADO.NET stand for?
A. Active Data Object .NET
B. Application Data Object .NET
C. Advanced Data Operations .NET
D. ActiveX Data Objects .NET

Correct Answer: D
Explanation: ADO.NET stands for ActiveX Data Objects for .NET. It is the data access technology in .NET Framework for connecting to databases (SQL Server, Oracle, MySQL). Key objects: SqlConnection, SqlCommand, SqlDataReader, SqlDataAdapter, DataSet, DataTable, DataRow.
Exam Trick: ADO.NET = ActiveX Data Objects .NET. Key objects: Connection, Command, Reader, Adapter, DataSet. ‘CCRA-DS’.


Q29: Which namespace contains SQL Server data provider classes in ADO.NET?
A. System.Sql
B. System.Data.OleDb
C. System.Data
D. System.Data.SqlClient

Correct Answer: D
Explanation: System.Data.SqlClient contains SQL Server-specific classes: SqlConnection, SqlCommand, SqlDataReader, SqlDataAdapter, SqlParameter. System.Data = base classes + DataSet/DataTable. System.Data.OleDb = OLE DB sources. In .NET 5+: Microsoft.Data.SqlClient (NuGet package).
Exam Trick: SqlClient namespace = SQL Server provider. OleDb = OLE DB. Odbc = ODBC. Each database has its own namespace/provider.

INTERMEDIATE LEVEL


Q30: In Windows Forms, which control displays data in rows and columns (tabular format)?
A. GridControl
B. ListView
C. TableView
D. DataGridView

Correct Answer: D
Explanation: DataGridView is the primary Windows Forms control for tabular data display and editing. It supports data binding via DataSource property, sorting, filtering, custom column types, and inline editing. The older DataGrid control is deprecated. Set dgv.DataSource = dataTable to bind.
Exam Trick: DataGridView = tabular grid in WinForms. DataSource property for binding. DataGrid = old/deprecated. Use DataGridView always.


Q31: What does the JIT compiler do in .NET?
A. Converts C# source to MSIL
B. Manages garbage collection
C. Compiles code ahead of time (AOT)
D. Converts MSIL to native machine code at RUNTIME (just before method execution)

Correct Answer: D
Explanation: JIT (Just-In-Time) compiler converts MSIL/CIL to NATIVE machine code at RUNTIME when a method is first called. The compiled native code is cached so subsequent calls use the cached version. Types: Normal JIT (default per-method), NGen/Pre-JIT (entire assembly ahead of time), Econo-JIT (low-memory devices).
Exam Trick: JIT = MSIL -> Native at RUNTIME (just before first execution). NGen = ahead-of-time (faster startup). Flow: C# -> MSIL -> JIT -> Native.


Q32: What is method overloading in C#?
A. A method calling itself recursively
B. Making a method static
C. Overriding a base class method
D. Multiple methods with SAME NAME but DIFFERENT parameters (number/type/order) in the same class

Correct Answer: D
Explanation: Method Overloading (compile-time/static polymorphism): multiple methods with same name but different parameter signatures. Return type alone CANNOT differentiate overloads. The compiler selects the correct overload at compile time based on argument types. Common example: Console.WriteLine() has 18 overloads.
Exam Trick: Overloading = same name, different parameters. Return type ALONE cannot overload. Compile-time resolution. Static polymorphism.


Q33: What keyword does a derived class use to override a virtual method from the base class?
A. new
B. abstract
C. virtual
D. override

Correct Answer: D
Explanation: ‘override’ provides a new implementation of a base class ‘virtual’ or ‘abstract’ method. This enables RUNTIME polymorphism (dynamic dispatch). The base method MUST be marked ‘virtual’. ‘new’ hides the base method but does NOT participate in polymorphism. ‘sealed override’ prevents further overriding.
Exam Trick: override = runtime polymorphism. Base needs ‘virtual’. Derived uses ‘override’. new = hiding (not polymorphism). virtual->override chain.


Q34: What is the output? class Animal { public virtual string Sound() => “…”; } class Dog : Animal { public override string Sound() => “Woof”; } Animal a = new Dog(); Console.WriteLine(a.Sound());
A. …
B. Error
C. Animal
D. Woof

Correct Answer: D
Explanation: Runtime polymorphism: ‘a’ is declared as Animal but references a Dog object. Since Sound() is virtual in Animal and overridden in Dog, CLR calls Dog’s Sound() at runtime based on ACTUAL object type. Declared type (Animal) is irrelevant for virtual/override. Output: Woof.
Exam Trick: virtual + override = actual object type wins. Animal a = new Dog() -> a.Sound() calls Dog’s override. Output: Woof. Declared type irrelevant for virtual.


Q35: What is an abstract class in C#?
A. A class with only static members
B. A class that prevents inheritance
C. A class with no methods
D. A class that CANNOT be instantiated, may contain abstract methods (no body), and MUST be inherited

Correct Answer: D
Explanation: Abstract class (keyword ‘abstract’): (1) Cannot be instantiated directly — only via derived classes. (2) Can contain abstract methods (no body — derived non-abstract class MUST implement them). (3) Can also have concrete (implemented) methods, fields, constructors. (4) A class with ANY abstract method must be abstract.
Exam Trick: abstract class = cannot instantiate directly. Abstract method = no body. Derived non-abstract class MUST implement ALL abstract methods.


Q36: Key difference between interface and abstract class in C#?
A. No difference
B. Interface is faster
C. Abstract class can be used only by value types
D. Interface = pure contract (no fields/constructor, multiple implementation). Abstract class = partial implementation (single inheritance, can have constructor/fields/access modifiers)

Correct Answer: D
Explanation: Interface: no implementation (pre-C#8), no fields/constructors, all public by default, a class can implement MULTIPLE interfaces. Abstract class: can have implementation, constructors, fields, access modifiers, only ONE can be inherited. C# 8+ allows default interface implementations. Rule: interface for ‘can-do’, abstract class for ‘is-a with shared code’.
Exam Trick: Interface = contract (multiple OK). Abstract = partial impl (single only). Multiple interfaces allowed. Constructors only in abstract class.


Q37: What does ‘sealed’ keyword do in C#?
A. Makes all members private
B. Creates immutable objects
C. Makes a class abstract
D. sealed class = prevents inheritance; sealed override = prevents further method overriding in derived classes

Correct Answer: D
Explanation: ‘sealed’ on a CLASS: no other class can inherit from it. ‘sealed’ on an override METHOD: derived classes cannot further override it. The string class in .NET is sealed. sealed classes can have JIT performance benefits (devirtualization). Use sealed when a class is not designed for extension.
Exam Trick: sealed class = no inheritance. sealed override = no further override. string is a sealed class. Performance benefit from JIT.


Q38: What is the key difference between a delegate and an event in C#?
A. Events support async; delegates do not
B. Events can hold more methods than delegates
C. They are identical
D. Event = delegate with restrictions: external code can only += or -= (subscribe/unsubscribe), only the declaring class can invoke (raise) it

Correct Answer: D
Explanation: Event wraps a delegate with access restrictions: external code can ONLY subscribe (+=) or unsubscribe (-=). Only the class that declares the event can raise/invoke it. Delegate alone allows external code to invoke it or replace it with = assignment. Events enforce the publisher-subscriber pattern and encapsulation.
Exam Trick: Event = restricted delegate. External: += or -= ONLY. Only declaring class invokes. Delegate: anyone can invoke or assign. Event = safe delegate.


Q39: What is a multicast delegate in C#?
A. A delegate that connects to multiple databases
B. A delegate for async operations
C. A delegate that spans multiple assemblies
D. A delegate that holds references to MULTIPLE methods in an invocation list, calling ALL when invoked

Correct Answer: D
Explanation: Multicast delegate holds multiple method references in its invocation list. += adds a method, -= removes it. When invoked, ALL methods are called in order. Return value = LAST method’s return (previous return values are discarded). Events use multicast delegates. This enables multiple event handlers.
Exam Trick: Multicast = multiple methods in one delegate. += adds, -= removes. ALL called in order. Return = last method’s return value.


Q40: What does ‘delegate int MathOp(int a, int b);’ declare?
A. A method named MathOp
B. An abstract method
C. An interface
D. A delegate TYPE — any method taking two ints and returning int can be assigned to a MathOp variable

Correct Answer: D
Explanation: This declares a DELEGATE TYPE called MathOp. Variables of type MathOp can hold references to any method with signature: int MethodName(int, int). Usage: MathOp add = (a,b) => a+b; MathOp mul = (a,b) => a*b; Console.WriteLine(add(3,4)); // 7. The delegate type = the ‘template’ for method references.
Exam Trick: delegate returnType Name(params) = declares delegate TYPE (not a method). Then: Name var = method; to store reference.


Q41: What is SqlConnection used for in ADO.NET?
A. To store data in memory
B. To execute SQL queries directly
C. To read data from database
D. To represent and manage a connection to SQL Server — must be Opened before use and Closed after

Correct Answer: D
Explanation: SqlConnection represents a physical connection to SQL Server. Key: ConnectionString (server, database, auth), State (Open/Closed), Open(), Close(). ALWAYS use ‘using’ block: connection auto-closes even on exception. Connection pooling: Close() returns connection to pool (doesn’t physically close). Open() gets one from pool.
Exam Trick: SqlConnection = DB connection. Must Open() before use. ALWAYS ‘using’ block. Close() = return to pool (not physical close).


Q42: What is a connection string in ADO.NET?
A. A SQL query string
B. The path to the database file
C. The name of the stored procedure
D. A string with parameters to connect to a database: server name, database name, and authentication details

Correct Answer: D
Explanation: Connection string contains: Data Source/Server (server name/IP), Initial Catalog/Database (DB name), Authentication (Integrated Security=True for Windows auth, or User ID + Password for SQL auth). Example: “Server=.;Database=MyDB;Integrated Security=True;”. Store in app.config/appsettings.json, not hardcoded.
Exam Trick: Connection String = server address + database name + credentials. Key parts: Server, Database, Auth. Store in config file!


Q43: What is the difference between ExecuteNonQuery() and ExecuteScalar()?
A. ExecuteScalar is for stored procedures only
B. ExecuteNonQuery() is faster
C. No difference
D. ExecuteNonQuery() = rows affected (for INSERT/UPDATE/DELETE); ExecuteScalar() = single value (first column of first row)

Correct Answer: D
Explanation: ExecuteNonQuery(): Runs INSERT/UPDATE/DELETE/DDL. Returns int = NUMBER OF ROWS AFFECTED. ExecuteScalar(): Returns SINGLE VALUE (first column, first row) — used for COUNT(*), MAX(), SUM(), etc. Returns object. ExecuteReader(): Returns SqlDataReader for reading multiple rows. Know all three!
Exam Trick: ExecuteNonQuery() = rows affected (DML). ExecuteScalar() = single value. ExecuteReader() = multiple rows. Three methods, three purposes.


Q44: What is SqlParameter and why use it?
A. A connection configuration setting
B. A method to return data from DB
C. A parameter for SQL Server configuration
D. A typed parameter for SQL queries that PREVENTS SQL INJECTION — use @ParamName syntax instead of string concatenation

Correct Answer: D
Explanation: SqlParameter passes parameters safely: cmd.CommandText = “SELECT * FROM Users WHERE Name = @Name”; cmd.Parameters.AddWithValue(“@Name”, userInput); This prevents SQL injection because the parameter is treated as DATA, not executable SQL. Also handles data type conversion. NEVER concatenate user input into SQL strings.
Exam Trick: SqlParameter = SQL injection prevention. NEVER: ‘SELECT * WHERE Name=’ + name. ALWAYS: @Name parameter. Security essential!


Q45: Key difference between SqlDataReader and SqlDataAdapter?
A. They are the same
B. DataReader can update data; DataAdapter cannot
C. DataAdapter is always faster
D. DataReader = connected/forward-only/read-only/fast (keeps connection open). DataAdapter = disconnected (fills DataSet, closes connection, data in memory for offline use)

Correct Answer: D
Explanation: SqlDataReader: CONNECTED mode — keeps connection open while reading, forward-only, read-only, streams row by row, very fast and memory-efficient. Use for large result sets where you read once. SqlDataAdapter: DISCONNECTED mode — fills DataSet/DataTable, then closes connection. Data lives in memory for offline manipulation.
Exam Trick: DataReader = connected, forward-only, FAST (streaming). DataAdapter = disconnected, fills DataSet (offline). DR=speed, DA=flexibility.


Q46: What does SqlDataReader.Read() return?
A. The current row data
B. The number of rows in the result
C. The column names
D. true if a row was successfully read (advances to next row); false if no more rows — reader starts BEFORE row 1

Correct Answer: D
Explanation: Read() advances the reader to the NEXT row. Returns TRUE if row exists, FALSE if no more rows. The reader starts BEFORE the first row, so Read() must be called before accessing any data. Pattern: while (reader.Read()) { string name = reader[“Name”].ToString(); } Without Read() = InvalidOperationException.
Exam Trick: reader.Read() = advance + returns true/false. Starts BEFORE row 1. Pattern: while(reader.Read()) { access columns }. Read() FIRST!


Q47: How do you bind a DataTable to a DataGridView?
A. dgv.Load(dataTable)
B. dgv.Fill(dataTable)
C. dgv.Bind(dataTable)
D. Set dgv.DataSource = dataTable; DGV auto-creates columns for each DataTable column

Correct Answer: D
Explanation: DataGridView.DataSource = dataTable; automatically creates columns matching DataTable columns and rows for each row. For DataSet: dgv.DataSource = ds; dgv.DataMember = “TableName”; For List<T>: dgv.DataSource = list; For BindingSource (recommended): bs.DataSource = dt; dgv.DataSource = bs;
Exam Trick: DGV binding: dgv.DataSource = dataTable; For DataSet: also dgv.DataMember = “TableName”. BindingSource recommended for updates.


Q48: What is wrong? SqlConnection conn = new SqlConnection(cs); conn.Open(); /* ops */ conn.Close();
A. conn.Close() is invalid
B. SqlConnection cannot be used this way
C. No problem
D. If an exception occurs between Open() and Close(), connection is NEVER closed — causes connection leak. Use ‘using’ block instead.

Correct Answer: D
Explanation: Without try-finally or ‘using’, an exception between Open() and Close() skips Close(), leaking the connection (not returned to pool). Fix: using (SqlConnection conn = new SqlConnection(cs)) { conn.Open(); /* operations */ } — Dispose()/Close() is called even on exception. ‘using’ = try-finally with Dispose().
Exam Trick: ALWAYS: using (var conn = new SqlConnection(cs)) { conn.Open(); … }. Without ‘using’ = connection leak on exception!


Q49: What is the output? string s = “Hello World”; Console.WriteLine(s.Substring(6));
A. Hello
B. Error
C. Hello World
D. World

Correct Answer: D
Explanation: Substring(startIndex) returns from startIndex to end. ‘Hello World’ (0-indexed): H=0,e=1,l=2,l=3,o=4,’ ‘=5,W=6,o=7,r=8,l=9,d=10. Index 6 = ‘W’. Substring(6) = ‘World’. Substring(startIndex, length) takes explicit length. Strings are 0-indexed like arrays.
Exam Trick: Substring(6) on ‘Hello World’ = ‘World’ (index 6 = ‘W’). Remember 0-indexing. Substring(start, length) for fixed length.


Q50: Find the compile error: abstract class Shape { abstract void Draw(); } class Circle : Shape { void Paint() { } }
A. Abstract class cannot have methods
B. Circle needs ‘abstract’ keyword
C. No error
D. Circle does NOT implement abstract method Draw() — compile error. Non-abstract derived class MUST implement ALL abstract methods.

Correct Answer: D
Explanation: Circle inherits Shape but doesn’t implement Draw(). Compiler error: ‘Circle does not implement inherited abstract member Shape.Draw()’. Fix: add ‘public override void Draw() { }’ to Circle. All abstract methods MUST be implemented by the first non-abstract derived class.
Exam Trick: Error: non-abstract derived class MUST implement ALL abstract methods. Fix: add ‘public override void Draw() { }’ to Circle.


Q51: Difference between ‘is’ and ‘as’ operators?
A. ‘is’ is for value types only; ‘as’ for reference types
B. ‘as’ throws exception on failure
C. They are the same
D. ‘is’ checks type (returns bool, no exception); ‘as’ attempts conversion (returns null if fails, no exception — reference types only)

Correct Answer: D
Explanation: ‘is’: bool result = obj is Dog; Safe check, no exception. C#7+: if (obj is Dog d) { } (pattern matching with declaration). ‘as’: Dog d = obj as Dog; Returns converted object or NULL if conversion fails — no exception thrown. ‘as’ only works with reference types and nullable. Direct cast: (Dog)obj throws InvalidCastException on failure.
Exam Trick: ‘is’ = bool check (no exception). ‘as’ = try-convert, null if fails (no exception). (Dog)obj = exception on fail. is/as are safe casts.


Q52: What is boxing and unboxing in C#?
A. Putting a class in a namespace and removing it
B. Copying objects between arrays
C. Encrypting and decrypting data
D. Boxing = value type to object (heap allocation, implicit); Unboxing = object back to value type (explicit cast) — both have performance cost

Correct Answer: D
Explanation: Boxing: int i=42; object o=i; // wraps int in heap object. Implicit. Unboxing: int j=(int)o; // extracts value from heap object. Explicit, requires cast. Performance cost: heap allocation + GC pressure. Solution: use generics (List<int> instead of ArrayList) to avoid boxing.
Exam Trick: Boxing = value -> object (implicit, heap). Unboxing = object -> value (explicit cast). Both = performance cost. Use generics to avoid!


Q53: What is the ‘var’ keyword in C#?
A. A variable that can hold any type at runtime
B. A keyword for global variables
C. A dynamically-typed variable like Python
D. Implicitly-typed local variable — compiler INFERS the type at COMPILE TIME from right-hand side. Type is fixed after inference.

Correct Answer: D
Explanation: ‘var i = 42;’ — compiler infers int at compile time. ‘var s = “Hello”;’ — compiler infers string. The type is FIXED and KNOWN at compile time (NOT dynamic). ‘var’ cannot be used for class fields or method parameters. NOT the same as ‘dynamic’ which is runtime-typed. Improves readability for complex types.
Exam Trick: var = compile-time type inference (still STRONGLY typed!). NOT dynamic. Type is fixed. var x = 42 means x IS an int always.


Q54: What is the output? int x = 5; Console.WriteLine(x++); Console.WriteLine(x);
A. 6, 6
B. 5, 5
C. 6, 5
D. 5, 6

Correct Answer: D
Explanation: x++ is POST-increment: USE the value first (5 printed), THEN increment x to 6. Line 1: prints 5. After: x=6. Line 2: prints 6. Pre-increment (++x): increment FIRST, then use. ++x would print 6 for both lines. Output: 5 then 6.
Exam Trick: x++ = post-increment: use THEN increment. ++x = pre-increment: increment THEN use. Console.WriteLine(x++) prints 5, then x becomes 6. Output: 5, 6.


Q55: What is the output? int[] arr = {5,3,1,4,2}; Array.Sort(arr); Console.WriteLine(string.Join(“,”, arr));
A. 5,3,1,4,2
B. 5,4,3,2,1
C. Error
D. 1,2,3,4,5

Correct Answer: D
Explanation: Array.Sort() sorts IN PLACE in ASCENDING order. {5,3,1,4,2} becomes {1,2,3,4,5}. string.Join(“,”, arr) concatenates elements with comma delimiter. For descending: Array.Sort(arr); Array.Reverse(arr); or LINQ: arr.OrderByDescending(x=>x). Output: 1,2,3,4,5.
Exam Trick: Array.Sort() = ascending, in-place. Array.Reverse() = reverses in-place. string.Join(sep, arr) = join with separator. Output: 1,2,3,4,5.


Q56: What is a property in C#?
A. A public field
B. An attribute applied to a class
C. A method starting with get or set
D. A class member providing controlled access to a backing field via get/set accessors — implementing encapsulation while looking like a field

Correct Answer: D
Explanation: Property: private int _age; public int Age { get => _age; set => _age = value >= 0 ? value : throw new Exception(); } Auto-property: public int Age { get; set; } The ‘value’ keyword in the setter holds the incoming value. Properties are the preferred way to expose data in C# (vs public fields).
Exam Trick: Property = controlled field access. Auto: { get; set; }. Full: get { return _f; } set { _f = value; }. ‘value’ = incoming value in setter.


Q57: What are Action and Func in C#?
A. Database operation delegates
B. Custom delegates defined by user
C. Async programming keywords
D. Built-in generic delegates: Action = void-returning method reference; Func<TResult> = method returning a value (last type param = return type)

Correct Answer: D
Explanation: Action<T1,T2,…>: Built-in delegate for VOID methods. Action<int,string> print = (i,s) => Console.Write(i+s); Func<T1,T2,…,TResult>: Built-in for methods that RETURN a value. Last type param = return type. Func<int,int,int> add = (a,b) => a+b; Predicate<T>: bool-returning (= Func<T,bool>). No need to define custom delegates for these patterns.
Exam Trick: Action = void delegate. Func = returns value (last type = return type). Predicate = bool return. No need for custom delegates!


Q58: What is a lambda expression in C#?
A. A Greek letter in math
B. A type of loop
C. A kind of inheritance
D. An anonymous function using => (goes to) operator: (params) => expression or statement block

Correct Answer: D
Explanation: Lambda syntax: (params) => expression. Examples: x => x*2 (single param), (a,b) => a+b (multi params), x => { int r = x*2; return r; } (statement body). Used with delegates, LINQ, events. x => x > 5 is equivalent to Predicate<int>. Lambda = anonymous method shorthand. The => reads as ‘goes to’.
Exam Trick: Lambda: params => expression. => reads ‘goes to’. x => x*2 means ‘x goes to x*2’. Anonymous = no method name needed.


Q59: What is a DataSet in ADO.NET?
A. A connection to the database
B. A type of SQL query
C. A method to update data
D. An in-memory representation of data containing multiple DataTables, DataRelations, and constraints — disconnected from database

Correct Answer: D
Explanation: DataSet = in-memory database. Contains: Multiple DataTables, DataRelations (relationships between tables), DataColumns, DataRows, Constraints. Disconnected from DB after fill. DataAdapter.Fill(ds) populates it; DataAdapter.Update(ds) pushes changes back. Supports XML serialization. AcceptChanges() commits pending changes in memory.
Exam Trick: DataSet = in-memory database (multiple tables + relations). Disconnected. DataAdapter fills it. Like a local snapshot of DB tables.


Q60: Difference between DataGridView.DataSource and DataGridView.DataMember?
A. DataMember is deprecated
B. DataSource is for columns; DataMember is for rows
C. No difference
D. DataSource = the data container (DataSet, List, DataTable); DataMember = which specific table to display when DataSource is a DataSet

Correct Answer: D
Explanation: DataSource: the bound data container — can be DataSet, DataTable, List<T>, BindingSource, etc. DataMember: used ONLY when DataSource is a DataSet — specifies which DataTable to show. Example: dgv.DataSource=myDS; dgv.DataMember=”Employees”; If DataSource is already a DataTable, no DataMember needed.
Exam Trick: DataSource = WHAT to bind (DataSet/List/DataTable). DataMember = WHICH TABLE (only needed with DataSet). DataMember empty if binding to DataTable.


Q61: What is the output? class Counter { static int count = 0; public Counter() { count++; } public static int GetCount() => count; } new Counter(); new Counter(); new Counter(); Console.WriteLine(Counter.GetCount());
A. 1
B. 2
C. 0
D. 3

Correct Answer: D
Explanation: count is STATIC — shared across ALL instances. Each new Counter() increments the shared count. Three objects created = count incremented 3 times = count=3. GetCount() returns static count. Static members retain values for the application’s lifetime. Output: 3.
Exam Trick: Static field = shared by ALL instances. 3 new Counter() calls = count incremented 3 times = 3. Output: 3.


Q62: Find the error: string s = null; Console.WriteLine(s.Length);
A. Compile-time error
B. s.Length returns 0 for null
C. No error
D. NullReferenceException at RUNTIME — accessing any member on a null reference throws NullReferenceException

Correct Answer: D
Explanation: s is null. Accessing s.Length throws NullReferenceException at RUNTIME (not compile time — compiler doesn’t track null values in general). Fix: null-conditional operator: s?.Length (returns null int? if s is null) or null check: if(s != null). C# 8+ nullable reference types help catch this at compile time.
Exam Trick: null.Anything = NullReferenceException at runtime. Fix: s?.Length or null check. NullReferenceException = most common .NET exception!


Q63: Difference between ‘ref’ and ‘out’ parameters?
A. No difference
B. ref is for value types; out for reference types
C. out is faster than ref
D. ref = must be initialized BEFORE calling (method may or may not modify); out = no init needed, method MUST assign before returning

Correct Answer: D
Explanation: ref: caller must initialize variable before passing. Method can read and modify. out: variable doesn’t need to be initialized. Method MUST assign before returning. Both pass by reference (changes reflect in caller). Common: int.TryParse(str, out int result) — result is set inside TryParse.
Exam Trick: ref = init first, method may change. out = no init needed, method MUST assign. int.TryParse uses ‘out’. Both pass by reference.


Q64: Difference between String and StringBuilder?
A. StringBuilder is for numbers only
B. String is for single chars
C. No difference
D. String = IMMUTABLE (each operation creates new object, memory pressure). StringBuilder = MUTABLE (modifies buffer in place, efficient for many concatenations)

Correct Answer: D
Explanation: String is immutable: s = s + ‘x’ creates a NEW string each time. In a loop with 1000 iterations = 1000 string objects. StringBuilder: sb.Append(‘x’) modifies the internal buffer — no new objects. Use string for few concatenations; StringBuilder for loops or many operations. StringBuilder.ToString() to get the final string.
Exam Trick: String = immutable (new object each change). StringBuilder = mutable (modifies buffer). Loop concatenation = ALWAYS use StringBuilder!


Q65: What are generics in C#?
A. A way to write non-specific code
B. A type of inheritance
C. A method to generate random values
D. Type-parametrized code allowing type-safe reuse without boxing — List<T>, Dictionary<K,V> are generic classes

Correct Answer: D
Explanation: Generics allow writing classes/methods/interfaces with TYPE PARAMETERS: class Stack<T> { }. Benefits: compile-time type safety, no boxing for value types, code reuse without duplication. List<int> is fully type-safe (no boxing unlike ArrayList). Constraints: where T : class, new(), IComparable<T>. Foundation of LINQ and collections.
Exam Trick: Generics = type-safe templates. List<int> vs ArrayList (no boxing). <T> = type parameter. Constraints: where T : …


Q66: Developer needs to quickly read a large result set (read-only, one pass). Best ADO.NET object?
A. DataTable
B. DataSet
C. SqlDataAdapter
D. SqlDataReader

Correct Answer: D
Explanation: SqlDataReader is best for large result sets read-only in one pass: streams data row by row from server (doesn’t load all into memory), forward-only, very fast. DataSet/DataTable load everything into memory at once — slow and memory-intensive for large data. Use DataReader for reports, data exports, ETL.
Exam Trick: Large data + read-only + one pass = SqlDataReader (fast streaming). DataSet = offline/random access/multiple tables. DataReader = speed.


Q67: How do you declare an event in C#?
A. A property with get/set
B. A method on a timer
C. A type of exception
D. Use ‘event’ keyword with a delegate type: public event EventHandler MyEvent; Raise with MyEvent?.Invoke(this, EventArgs.Empty);

Correct Answer: D
Explanation: Standard event pattern: public event EventHandler ButtonClicked; (EventHandler = delegate void(object sender, EventArgs e)). Raise: ButtonClicked?.Invoke(this, EventArgs.Empty); The ?. prevents NullReferenceException if no subscribers. Subscribe: obj.ButtonClicked += MyHandler; Unsubscribe: -= MyHandler;
Exam Trick: Event: public event EventHandler Name; Raise: Name?.Invoke(this,e); Subscribe: obj.Event += Handler; ?. prevents null exception.


Q68: How do you refresh DataGridView after data changes?
A. dgv.Reload()
B. dgv.Update()
C. dgv.Refresh()
D. Reassign DataSource: dgv.DataSource=null; dgv.DataSource=dt; or use BindingSource.ResetBindings(false)

Correct Answer: D
Explanation: dgv.Refresh() only repaints the control (visual refresh), doesn’t reload data. To reflect data changes: Option 1: Reassign DataSource (dgv.DataSource=null; dgv.DataSource=dt). Option 2: Use BindingSource (bs.DataSource=dt; dgv.DataSource=bs) then bs.ResetBindings(false) — preserves scroll/selection position.
Exam Trick: DGV refresh: reassign DataSource OR use BindingSource.ResetBindings(false). dgv.Refresh() only repaints, doesn’t reload data!


Q69: Difference between shallow copy and deep copy?
A. Shallow is for value types; deep for reference types
B. Deep copy is automatic; shallow is manual
C. No difference
D. Shallow copy = copies field values (reference fields still share the same objects). Deep copy = creates completely independent copies of all nested objects too

Correct Answer: D
Explanation: Shallow copy (MemberwiseClone()): copies all fields. For reference type fields, copies the REFERENCE — original and copy share the same nested objects. Deep copy: creates new copies of all nested objects too — completely independent. Must implement manually (serialization, ICloneable, copy constructors). Important to avoid unintended side effects.
Exam Trick: Shallow = copy references (shared nested objects). Deep = copy everything (fully independent). MemberwiseClone() = shallow. Serialization = deep.

ADVANCED LEVEL


Q70: Correct order when using SqlDataAdapter to fill a DataTable?
A. Open connection -> Fill -> Close connection
B. Create DataTable -> Fill -> Open connection
C. Open connection -> Create adapter -> Close connection
D. Create connection + adapter -> Fill DataTable (adapter AUTO-manages the connection)

Correct Answer: D
Explanation: SqlDataAdapter.Fill() automatically OPENS the connection (if closed), executes the query, fills the DataTable, and CLOSES the connection (if it opened it). No manual Open()/Close() needed. Example: SqlDataAdapter da = new(“SELECT…”, conn); DataTable dt = new(); da.Fill(dt); // auto open/close.
Exam Trick: DataAdapter.Fill() auto-opens AND auto-closes the connection. No manual Open()/Close() needed with DataAdapter! Automatic management.


Q71: What is the output? class Base { public void Show() => Console.Write(“Base “); public virtual void Display() => Console.Write(“BaseD “); } class Derived : Base { public new void Show() => Console.Write(“Derived “); public override void Display() => Console.Write(“DerivedD “); } Base b = new Derived(); b.Show(); b.Display();
A. Derived BaseD
B. Derived DerivedD
C. Base BaseD
D. Base DerivedD

Correct Answer: D
Explanation: b is declared as Base but references a Derived object. Show() uses ‘new’ (hiding, not virtual) — DECLARED TYPE (Base) determines which Show() runs -> prints ‘Base ‘. Display() uses virtual/override — ACTUAL TYPE (Derived) determines -> prints ‘DerivedD ‘. Output: ‘Base DerivedD’. This is the key new vs override distinction.
Exam Trick: new = hides (declared type wins = Base). override = polymorphism (actual type wins = Derived). Base b = new Derived(): Show=’Base’, Display=’DerivedD’.


Q72: Difference between IEnumerable<T>, ICollection<T>, and IList<T>?
A. IList is base of all
B. IEnumerable is for LINQ only
C. They are the same
D. Hierarchy: IEnumerable = foreach/iteration only; ICollection = +Count/Add/Remove; IList = +indexer [i]/Insert/IndexOf

Correct Answer: D
Explanation: Inheritance chain: IEnumerable<T> -> ICollection<T> -> IList<T>. IEnumerable<T>: GetEnumerator() for forward iteration (foreach). ICollection<T>: adds Count, Add(), Remove(), Contains(), Clear(). IList<T>: adds indexer list[i], Insert(index,item), IndexOf(), RemoveAt(). Rule: use the WIDEST (least specific) interface that satisfies your needs.
Exam Trick: IEnumerable = foreach. ICollection = +Count/Add/Remove. IList = +index[i]. Hierarchy: EN < COL < LIST. Use widest needed.


Q73: What is LINQ in C#?
A. Linux Integration for .NET
B. A testing framework
C. A type of loop
D. Language Integrated Query — SQL-like queries in C# for any IEnumerable<T> source (collections, XML, databases)

Correct Answer: D
Explanation: LINQ (Language Integrated Query) enables querying any IEnumerable<T> using SQL-like syntax in C#. Two syntaxes: Query: var r = from x in list where x>5 select x; Method: var r = list.Where(x=>x>5).Select(x=>x); Providers: LINQ to Objects (collections), LINQ to SQL, LINQ to XML, Entity Framework. Key: deferred execution.
Exam Trick: LINQ = SQL in C# for any collection. Query syntax (from/where/select) vs Method syntax (.Where().Select()). Works on IEnumerable.


Q74: What is the output? Func<int,int,int> calc = (a,b) => a > b ? a : b; Console.WriteLine(calc(10, 20));
A. 10
B. 30
C. Error
D. 20

Correct Answer: D
Explanation: calc is Func<int,int,int> — takes two ints, returns int. Lambda (a,b) => a>b?a:b returns the MAXIMUM (ternary operator). calc(10,20): 10>20 is FALSE, so returns b=20. Output: 20. Func<T1,T2,TResult>: last type param is the RETURN TYPE. This demonstrates Func with a ternary conditional expression.
Exam Trick: Func<int,int,int>: 2 int params, returns int. (a,b)=>a>b?a:b = max(a,b). calc(10,20)=max=20. Last type param = return type.


Q75: What is an interface and when should you use it?
A. To create static classes
B. To create abstract classes
C. To prevent instantiation
D. A contract defining method/property signatures that implementing classes MUST fulfill — used for multiple inheritance behavior, loose coupling, dependency injection, and testability (mocking)

Correct Answer: D
Explanation: Interface = pure contract (signatures only, no implementation pre-C#8). All members public by default. A class can implement MULTIPLE interfaces. Use interfaces for: (1) Multiple inheritance behavior, (2) Dependency Injection (program to interface, not implementation), (3) Unit testing (mock the interface), (4) SOLID Dependency Inversion Principle.
Exam Trick: Interface = contract. Multiple per class OK. Use for DI, mocking, loose coupling. ‘can-do’ relationship. SOLID DIP: depend on interfaces.


Q76: Find the bug: SqlConnection conn = new SqlConnection(cs); SqlCommand cmd = new SqlCommand(“SELECT * FROM Users”, conn); SqlDataReader dr = cmd.ExecuteReader(); while(dr.Read()) { Console.WriteLine(dr[“Name”]); }
A. Wrong SQL syntax
B. DataReader cannot use SELECT
C. ExecuteReader needs parameters
D. Connection is never opened — will throw InvalidOperationException: ‘ExecuteReader requires an open and available Connection’

Correct Answer: D
Explanation: conn.Open() is NEVER called! SqlCommand.ExecuteReader() requires an open connection. Without Open(), throws InvalidOperationException. Fix: add conn.Open(); after creating cmd (or before). Also: wrap everything in ‘using’ blocks for proper resource management. Forgetting conn.Open() is the #1 ADO.NET mistake.
Exam Trick: BUG: Missing conn.Open()! Must open connection before ExecuteReader()/ExecuteNonQuery()/ExecuteScalar(). Most common ADO.NET exam bug!


Q77: What are the SOLID principles?
A. A security framework for .NET
B. A testing methodology
C. A performance optimization technique
D. 5 OOP design principles: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion

Correct Answer: D
Explanation: SOLID: S=Single Responsibility (one reason to change). O=Open/Closed (extend without modifying). L=Liskov Substitution (derived replaces base seamlessly). I=Interface Segregation (specific interfaces > one fat interface). D=Dependency Inversion (depend on abstractions, not concretions — use interfaces + DI). Foundation of clean, maintainable .NET architecture.
Exam Trick: SOLID = S-O-L-I-D: Single, Open/Closed, Liskov, Interface Segregation, Dependency Inversion. Foundation of clean C# architecture.


Q78: How do you call a stored procedure using SqlCommand?
A. A C# stored method
B. A method to store query results
C. A precompiled SQL program stored in DB; call by setting cmd.CommandType = CommandType.StoredProcedure + procedure name
D. A property of SqlConnection

Correct Answer: C
Explanation: Stored procedure call: SqlCommand cmd = new SqlCommand(“sp_GetUsers”, conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue(“@Dept”, “IT”); SqlDataReader dr = cmd.ExecuteReader(); Default CommandType = Text (SQL string). MUST set CommandType.StoredProcedure before execution or it sends procedure name as SQL string.
Exam Trick: SP call: CommandType = StoredProcedure + procedure name. MUST set CommandType FIRST. Default = CommandType.Text. Add @params.


Q79: What is the output? List<int> list = new List<int> {1,2,3}; var query = list.Where(x => x > 1); list.Add(4); Console.WriteLine(string.Join(“,”, query));
A. 2,3
B. Error
C. 1,2,3,4
D. 2,3,4

Correct Answer: D
Explanation: LINQ queries are DEFERRED (lazy) — they execute when ENUMERATED, not when defined. ‘query’ is defined but NOT executed. list.Add(4) adds 4 to the list. When string.Join() enumerates ‘query’, it executes THEN against current list {1,2,3,4}. Where(x>1) on {1,2,3,4} = {2,3,4}. Output: 2,3,4. This is DEFERRED EXECUTION — critical LINQ concept.
Exam Trick: LINQ deferred execution: query runs WHEN ENUMERATED (not when defined). list.Add(4) BEFORE Join() affects result. Output: 2,3,4.


Q80: What is the standard EventHandler<TEventArgs> pattern?
A. A class for handling database events
B. A way to handle exceptions
C. A UI-specific event only
D. Standard .NET event pattern: delegate void EventHandler<T>(object sender, T e) where T:EventArgs. Sender=raiser, e=custom event data containing event-specific information

Correct Answer: D
Explanation: Standard pattern: public event EventHandler<OrderEventArgs> OrderPlaced; Custom args: class OrderEventArgs : EventArgs { public int OrderId { get; set; } } Raise: OrderPlaced?.Invoke(this, new OrderEventArgs { OrderId = 1 }); This pattern is used throughout .NET — all UI control events, HTTP events, etc. follow this convention.
Exam Trick: EventHandler<T> where T:EventArgs. Sender=raiser, e=event data. All .NET events follow this pattern. Custom: class XEventArgs : EventArgs.


Q81: Team needs multiple related tables (Customers + Orders) in memory, displayed in DataGridView. Best approach?
A. Use multiple SqlConnections
B. Use SqlDataReader
C. Use string variables
D. Use DataSet with two DataTables and DataRelation — fill with DataAdapter, add DataRelation, bind to DataGridView

Correct Answer: D
Explanation: DataSet approach: DataSet ds = new(); SqlDataAdapter da1 = new(“SELECT * FROM Customers”,conn); da1.Fill(ds,”Customers”); SqlDataAdapter da2 = new(“SELECT * FROM Orders”,conn); da2.Fill(ds,”Orders”); ds.Relations.Add(“CO”,ds.Tables[“Customers”].Columns[“CustID”],ds.Tables[“Orders”].Columns[“CustID”]); dgv.DataSource = ds.Tables[“Customers”];
Exam Trick: Multiple related tables = DataSet + DataRelation + DataAdapter.Fill each. Perfect use case for DataSet’s relational in-memory DB capability.


Q82: What is the output? interface IShape { double Area(); } class Circle : IShape { double r; public Circle(double r) { this.r = r; } public double Area() => Math.PI * r * r; } IShape s = new Circle(5); Console.WriteLine((int)s.Area());
A. 79
B. 75
C. Error
D. 78

Correct Answer: D
Explanation: Circle.Area() = Math.PI * 5 * 5 = 3.14159… * 25 = 78.5398… Casting to int TRUNCATES (not rounds): (int)78.5398 = 78. IShape s = new Circle(5): interface reference — runtime polymorphism calls Circle’s Area(). (int) cast truncates toward zero (floor for positives). Output: 78.
Exam Trick: Math.PI * 25 = 78.54. (int) truncates = 78 (not rounds to 79). IShape reference -> Circle’s Area() via polymorphism. Output: 78.


Q83: What is the output? string a = “hello”; string b = “hello”; Console.WriteLine(object.ReferenceEquals(a, b));
A. Depends on runtime
B. False
C. Error
D. True

Correct Answer: D
Explanation: Output: True. STRING INTERNING: .NET maintains a string intern pool. String LITERALS with same content share the same memory location (same object). Both ‘a’ and ‘b’ are literals = same interned object = same reference. ReferenceEquals checks memory address -> True. Non-literal strings created with ‘new string()’ bypass interning and return False.
Exam Trick: String literals are INTERNED in .NET. Same content = same object in pool. ReferenceEquals on literals = True! new string() bypasses interning.


Q84: Find the bug: SqlDataReader dr = cmd.ExecuteReader(); string name = (string)dr[“Name”]; dr.Read();
A. ExecuteReader needs parameters
B. The cast is wrong
C. No bug
D. dr.Read() called AFTER accessing columns — DataReader starts BEFORE row 1. Must call Read() FIRST before accessing any column data.

Correct Answer: D
Explanation: SqlDataReader starts positioned BEFORE the first row. You MUST call Read() before accessing dr[“Name”]. Here, dr[“Name”] is accessed BEFORE dr.Read() — InvalidOperationException. Correct: if (dr.Read()) { string name = (string)dr[“Name”]; } or while (dr.Read()) { /* access columns */ }
Exam Trick: BUG: Read() called AFTER accessing data. Must call Read() FIRST. DataReader starts before row 1. Read() returns true = row available.


Q85: Difference between IDisposable and finalizer (~destructor) in C#?
A. Finalizer is called first, then Dispose
B. Dispose is for managed resources; finalizer for static fields
C. No difference
D. IDisposable.Dispose() = DETERMINISTIC cleanup (you call it, via ‘using’). Finalizer = NON-DETERMINISTIC (GC calls it, unknown timing). Use Dispose Pattern for unmanaged resources.

Correct Answer: D
Explanation: Dispose() (IDisposable): called explicitly or by ‘using’ block — DETERMINISTIC. Finalizer (~ClassName()): called by GC when collecting — NON-DETERMINISTIC timing. Best practice — Dispose Pattern: implement both, call GC.SuppressFinalize(this) inside Dispose() so GC doesn’t run finalizer if Dispose was already called. For unmanaged resources (file handles, DB connections).
Exam Trick: Dispose() = deterministic (you control WHEN via ‘using’). Finalizer = GC controls WHEN. Dispose Pattern: implement both + GC.SuppressFinalize.


Q86: How do you get clicked row data in DataGridView.CellClick event?
A. dgv.SelectedRow.Value
B. dgv.GetRow(e.RowIndex)
C. dgv.CurrentCell.RowIndex only
D. Use e.RowIndex and e.ColumnIndex from DataGridViewCellEventArgs: dgv.Rows[e.RowIndex].Cells[“ColumnName”].Value

Correct Answer: D
Explanation: CellClick provides DataGridViewCellEventArgs e with e.RowIndex (clicked row) and e.ColumnIndex (clicked column). Access data: string name = dgv.Rows[e.RowIndex].Cells[“Name”].Value?.ToString(); Always check e.RowIndex >= 0 (header click returns -1). For current selected row: dgv.CurrentRow.Cells[“Name”].Value.
Exam Trick: CellClick: e.RowIndex = row, e.ColumnIndex = col. Access: dgv.Rows[e.RowIndex].Cells[“Col”].Value. Check e.RowIndex >= 0 (not header).


Q87: How do you implement a database transaction in ADO.NET?
A. Transactions are automatic in ADO.NET
B. Use two SqlConnections
C. Use DataSet
D. SqlTransaction: conn.BeginTransaction() -> assign to all commands -> Commit() on success, Rollback() in catch for ACID guarantee

Correct Answer: D
Explanation: Pattern: SqlTransaction trans = conn.BeginTransaction(); try { cmd1.Transaction = trans; cmd1.ExecuteNonQuery(); cmd2.Transaction = trans; cmd2.ExecuteNonQuery(); trans.Commit(); } catch { trans.Rollback(); throw; } All commands must use SAME transaction + SAME connection. Ensures all-or-nothing (ACID Atomicity).
Exam Trick: Transaction: BeginTransaction() -> assign to ALL cmds -> Commit() or Rollback(). Same connection for all cmds. ACID = All or Nothing.


Q88: What is the output? var nums = new int[]{1,2,3,4,5}; var r = nums.Select(x=>x*2).Where(x=>x>4).Sum(); Console.WriteLine(r);
A. 20
B. 30
C. 14
D. 24

Correct Answer: D
Explanation: Step 1: Select(x=>x*2) maps {1,2,3,4,5} to {2,4,6,8,10}. Step 2: Where(x=>x>4) filters: {6,8,10} (removes 2 and 4). Step 3: Sum() = 6+8+10 = 24. Output: 24. LINQ method chaining — each method is applied to output of previous. Deferred execution: all three methods run together when Sum() forces enumeration.
Exam Trick: Select(*2): {2,4,6,8,10}. Where(>4): {6,8,10}. Sum()=24. LINQ chain: each method’s output feeds next. Output: 24.


Q89: What is the Observer design pattern and how is it implemented in C#?
A. A database pattern for table changes
B. A performance monitoring pattern
C. A UI pattern for watching input
D. A behavioral pattern where a publisher notifies multiple subscribers on state change — C# events ARE the Observer pattern built into the language

Correct Answer: D
Explanation: Observer Pattern: Publisher (Subject) raises events when state changes. Subscribers register handlers. C# implementation: class Store { public event EventHandler<PriceEventArgs> PriceChanged; void SetPrice(decimal p) { _p=p; PriceChanged?.Invoke(this, new PriceEventArgs(p)); } } Subscribers: store.PriceChanged += SendEmailNotification; store.PriceChanged += UpdateUI; C# events = built-in Observer.
Exam Trick: Observer = Publisher/Subscriber. C# events ARE the Observer pattern. Raise event -> all += handlers called. Built into the language.


Q90: What is the Singleton design pattern in C#?
A. A class with one method
B. A pattern for creating multiple objects
C. A pattern for database connections
D. A pattern ensuring ONLY ONE instance of a class exists — private constructor + static instance + thread-safe lazy initialization

Correct Answer: D
Explanation: Thread-safe Singleton with Lazy<T>: public sealed class Singleton { private static readonly Lazy<Singleton> _i = new(() => new Singleton()); private Singleton() { } public static Singleton Instance => _i.Value; } Lazy<T> ensures thread-safe lazy initialization. Use cases: Logger, Config manager. Consider DI containers instead for testability.
Exam Trick: Singleton: private constructor + static Lazy<T> instance. sealed = no subclassing. Lazy<T> = thread-safe lazy init. Use DI in modern .NET.


Q91: Difference between CommandType.Text and CommandType.StoredProcedure?
A. StoredProcedure does not need parameters
B. No difference
C. Text is always faster
D. CommandType.Text = CommandText is a SQL string (compiled each call). CommandType.StoredProcedure = CommandText is stored procedure name (precompiled, reuses execution plan)

Correct Answer: D
Explanation: CommandType.Text (DEFAULT): CommandText is SQL string sent to server and compiled each execution. CommandType.StoredProcedure: CommandText is the SP name — server uses precompiled execution plan (faster, cached). CommandType.TableDirect: table name (rarely used). Always set CommandType BEFORE assigning CommandText.
Exam Trick: CommandType.Text = SQL string (compiled each time). StoredProcedure = precompiled SP name. Default = Text. Set CommandType FIRST.


Q92: What is covariance and contravariance in C# generics/delegates?
A. A type of inheritance
B. Generic constraints
C. Mathematical operations on generics
D. Covariance (out T): IEnumerable<Derived> usable as IEnumerable<Base> (producer). Contravariance (in T): Action<Base> usable as Action<Derived> (consumer)

Correct Answer: D
Explanation: Covariance (out T): allows derived type where base expected. IEnumerable<string> assignable to IEnumerable<object> because string is covariant in IEnumerable (marked out T). Contravariance (in T): allows base type where derived expected. Action<object> assignable to Action<string>. Covariant = produces T (returns). Contravariant = consumes T (parameter).
Exam Trick: Covariance: out T = derived->base (producer, returns T). Contravariance: in T = base->derived (consumer, takes T). IEnumerable<string>->IEnumerable<object>.


Q93: How do you export DataGridView data to a DataTable?
A. dgv.ToDataTable()
B. DataTable dt = (DataTable)dgv.DataSource only
C. Loop through dgv.Rows only
D. Both: (DataTable)dgv.DataSource if bound to DataTable, OR loop through dgv.Rows adding each row to a new DataTable

Correct Answer: D
Explanation: Method 1 (if DGV bound to DataTable): DataTable dt = (DataTable)dgv.DataSource; Direct cast. Method 2 (generic): DataTable dt = new DataTable(); add columns; foreach (DataGridViewRow row in dgv.Rows) { if (!row.IsNewRow) { dt.Rows.Add(row.Cells[0].Value, …); } } Both approaches are valid depending on binding situation.
Exam Trick: Export DGV to DataTable: if bound to DataTable, cast: (DataTable)dgv.DataSource. Otherwise loop dgv.Rows. Check row.IsNewRow to skip new row.


Q94: What is async/await in C#?
A. A way to speed up CPU-bound operations
B. A type of event handling
C. A database connection type
D. async/await = non-blocking asynchronous programming. async marks method async; await pauses method without blocking thread while waiting for I/O. Returns Task/Task<T>.

Correct Answer: D
Explanation: async marks a method asynchronous. await suspends the method, returns control to caller WITHOUT blocking thread, then resumes after the awaited task completes. Returns Task (void) or Task<T> (value). Use for I/O-bound operations (DB queries, HTTP calls, file operations). NOT for CPU-bound work (use Task.Run() for that).
Exam Trick: async/await = non-blocking I/O. await = pause without blocking thread. Returns Task. Use for DB/HTTP/file. NOT for CPU-heavy work.


Q95: What is connection pooling in ADO.NET?
A. Storing SQL queries for reuse
B. Caching query results
C. Storing multiple DataSets
D. ADO.NET automatically maintains a pool of pre-opened connections — Open() gets one from pool; Close() returns to pool. Avoids expensive connection overhead.

Correct Answer: D
Explanation: Connection Pooling (enabled by default): When SqlConnection.Open() is called, ADO.NET checks the pool for available connections matching the connection string. If found, reuses it (no new TCP/auth handshake). Close() returns connection to pool (not physically closed). Pool size: Min Pool Size / Max Pool Size in connection string. Significantly improves performance.
Exam Trick: Pooling: Open() = get from pool, Close() = return to pool. No physical close! Enabled by default. Set: Max Pool Size=100 in conn string.


Q96: What is the output? class A { public A() { Console.Write(“A “); } } class B : A { public B() { Console.Write(“B “); } } class C : B { public C() { Console.Write(“C “); } } new C();
A. C B A
B. C A B
C. B A C
D. A B C

Correct Answer: D
Explanation: C# calls constructors BASE-FIRST. Creating new C(): C extends B, B extends A. Each constructor implicitly calls base() before its own body. So: A() runs first -> ‘A ‘, then B() -> ‘B ‘, then C() -> ‘C ‘. Output: ‘A B C’. Students often write ‘C B A’ (thinking derived-first) — but C# is always BASE-FIRST.
Exam Trick: Constructor order: BASE-FIRST. new C() -> A() -> B() -> C(). Output: A B C. NOT C B A! Base class always initializes first. Classic exam trap.


Q97: Difference between DataTable.AcceptChanges() and DataAdapter.Update()?
A. No difference
B. Both send data to server
C. AcceptChanges() is faster
D. AcceptChanges() = commits changes IN MEMORY ONLY (marks rows as Unchanged, no DB). DataAdapter.Update() = pushes changes FROM DataTable TO the DATABASE, then calls AcceptChanges()

Correct Answer: D
Explanation: AcceptChanges(): Commits all pending changes (Added/Modified/Deleted rows) IN MEMORY — sets RowState to Unchanged. No database interaction. DataAdapter.Update(dt): Executes INSERT/UPDATE/DELETE SQL for each changed row via InsertCommand/UpdateCommand/DeleteCommand, then calls AcceptChanges(). If you call AcceptChanges() before Update(), DataAdapter sees no changes and sends nothing to DB.
Exam Trick: AcceptChanges() = in-memory commit only (no DB). DataAdapter.Update() = DB sync then calls AcceptChanges(). Don’t call AcceptChanges() BEFORE Update()!


Q98: How do you add a row to a DataGridView bound to a DataTable?
A. dgv.Insert(row)
B. dgv.DataSource.Add(values)
C. dgv.Rows.Add(values)
D. Add DataRow to the bound DataTable: DataRow row = dt.NewRow(); row[“Name”]=”John”; dt.Rows.Add(row); DGV auto-reflects the change

Correct Answer: D
Explanation: When DataGridView is bound to a DataTable, NEVER add rows directly to DGV (dgv.Rows.Add() throws exception when DataSource is set). Instead: DataRow row = dt.NewRow(); row[“Name”] = “John”; row[“Age”] = 25; dt.Rows.Add(row); The DataGridView automatically reflects the new row. Modify the DataSource, not the DGV directly.
Exam Trick: Bound DGV: modify the DataSource (DataTable), not the DGV. DGV auto-updates. DataRow = dt.NewRow(); then dt.Rows.Add(row).


Q99: What is the output? string s1 = new string(‘A’,3); string s2 = new string(‘A’,3); Console.WriteLine(s1 == s2); Console.WriteLine(object.ReferenceEquals(s1, s2));
A. False, False
B. True, True
C. False, True
D. True, False

Correct Answer: D
Explanation: new string(‘A’,3) creates ‘AAA’ using constructor. Both s1 and s2 are ‘AAA’ but DIFFERENT objects (new keyword bypasses string interning). == for strings compares CONTENT: ‘AAA’==’AAA’ -> True. ReferenceEquals checks if same OBJECT in memory: two different ‘new’ objects -> False. Output: True, False. String literals would give True, True.
Exam Trick: new string() BYPASSES interning. == compares content (True). ReferenceEquals compares reference (False). Literals: both True. new string: True, False.


Q100: How do you filter/search DataGridView data bound to a DataTable?
A. dgv.Search(“condition”)
B. Loop through all rows and hide non-matching
C. dgv.Filter = “condition”
D. Use DataTable.DefaultView.RowFilter: dt.DefaultView.RowFilter = “Name LIKE ‘%John%'”; then bind DGV to DefaultView

Correct Answer: D
Explanation: Filter using DataView.RowFilter: dt.DefaultView.RowFilter = “Name LIKE ‘%John%’ AND Age > 25”; dgv.DataSource = dt.DefaultView; (or DGV auto-updates if already bound to DefaultView via BindingSource). Uses SQL WHERE-like syntax. Sort: dt.DefaultView.Sort = “Name ASC”; Clear: dt.DefaultView.RowFilter = “”;
Exam Trick: Filter DGV: dt.DefaultView.RowFilter = “condition”; dgv.DataSource = dt.DefaultView; SQL-like syntax. Sort: DefaultView.Sort. Clear: RowFilter = “”.


MPSeDC GET Program 3.0 2026 – Exam-Oriented .NET MCQ Questions
Scroll to top