Question Bank › Technical › C# › MCQ
.NET Framework Components
Q1.Easy
Which part of the .NET Framework offers a reusable, extensible set of classes that any .NET-compliant language (such as C# or VB.NET) can consume?
- .NET class libraries
- Common Language Runtime
- Common Language Infrastructure
- Component Object Model
- Common Type System
Show answer & explanation
Answer: (A) .NET class librariesExplanation: 1. The .NET class libraries (FCL/BCL) are collections of reusable types like System.IO, System.Collections, etc.
2. Any .NET-compliant language can call these same classes.
3. The CLR executes code, CLI is a specification, COM is a legacy model, and CTS defines types.
4. Therefore the extensible set of usable classes is the .NET class libraries.
Q2.Easy
In the .NET runtime, which component is responsible for reclaiming memory occupied by objects on the managed heap that are no longer referenced?
- Common Language Infrastructure
- Common Language Runtime
- Garbage Collector
- Class Loader
- Common Type System
Show answer & explanation
Answer: (C) Garbage CollectorExplanation: 1. The managed heap holds objects created with 'new'.
2. The Garbage Collector (GC) periodically scans the heap for objects with no live references.
3. It frees the memory of those unreferenced objects and compacts the heap.
4. CLI, CLR, Class Loader and CTS are broader framework pieces, not the memory reclaimer.
5. Hence the correct component is the Garbage Collector.
Q3.Medium
Which of the following are core components of the .NET Framework?
1. ASP.NET
2. CLR
3. Framework Class Library
4. WinForms
5. Windows Services
- 1 and 2
- 2 and 3
- 3 and 4
- 2 and 5
Show answer & explanation
Answer: (B) 2 and 3Explanation: 1. The .NET Framework fundamentally consists of two parts: the Common Language Runtime (CLR) and the Framework Class Library (FCL).
2. ASP.NET, WinForms and Windows Services are technologies/applications built on top of the framework, not its core components.
3. Therefore the correct pair is CLR and Framework Class Library, i.e. 2 and 3.
Q4.Medium
Which of the following are parts of the .NET Framework? 1. The Common Language Runtime (CLR) 2. The Framework Class Libraries (FCL) 3. Microsoft Published Web Services 4. Applications deployed on IIS 5. Mobile Applications
- Only 1, 2
- Only 1, 2, 3
- Only 1, 2, 4
- Only 4, 5
- All of the above
Show answer & explanation
Answer: (A) Only 1, 2Explanation: The .NET Framework consists of the CLR (execution engine) and the FCL (base class libraries). Web services, IIS-deployed applications, and mobile applications are things built using the framework, not parts of the framework itself. Hence only 1 and 2 are correct.
Access Modifiers
Q5.Easy
Which of the following statements is correct about the C# code snippet given below?
class Sample
{
private int i;
public float j;
private void DisplayData()
{
Console.WriteLine(i + " " + j);
}
public void ShowData()
{
Console.WriteLine(i + " " + j);
}
}- j cannot be declared as public.
- DisplayData() cannot be declared as private.
- DisplayData() cannot access j.
- ShowData() cannot access i.
- There is no error in this class.
Show answer & explanation
Answer: (E) There is no error in this class.Explanation: 1) A field can be public, so j being public is fine. 2) A method can be private, so DisplayData() being private is fine. 3) Private members are accessible anywhere inside the same class, so DisplayData() can read j and ShowData() can read i. 4) Hence no access rule is violated and the class compiles without error.
Q6.Easy
An object of a derived class cannot access private members of its base class.
- True
- False
Show answer & explanation
Answer: (A) TrueExplanation: 1. Private members are accessible only within the class that declares them.
2. Even a derived class object cannot reach them directly.
3. So the statement is True.
Q7.Easy
Private members of a base class cannot be accessed by derived class member functions or by objects of the derived class.
- True
- False
Show answer & explanation
Answer: (A) TrueExplanation: Private members are accessible only within the body of the class that declares them.
A derived class, even though it inherits from the base, cannot directly access those private members.
Objects of the derived class also cannot reach them.
Therefore the statement is true.
Attributes
Q8.Easy
The [Serializable()] attribute is inspected at which stage?
- Compile-time
- Run-time
- Design-time
- Linking-time
- None of the above
Show answer & explanation
Answer: (B) Run-timeExplanation: 1) [Serializable] is written into the assembly metadata by the compiler.
2) The decision whether a type can be serialized is made by the serialization engine (e.g. BinaryFormatter) while the program executes.
3) That inspection of the attribute happens through reflection at run time.
4) Therefore it is inspected at run-time.
Q9.Easy
Is it possible to create a custom attribute that can be applied only to specific programming elements such as classes and methods?
- Classes
- Methods
- Classes and Methods
- Classes, Methods and Member-Variables
Show answer & explanation
Answer: (C) Classes and MethodsExplanation: 1) A custom attribute class derives from System.Attribute.
2) The AttributeUsage attribute on it has a ValidOn property (of type AttributeTargets).
3) AttributeTargets is a flags enum, so you can combine values, e.g. AttributeTargets.Class | AttributeTargets.Method.
4) This restricts the attribute to only the chosen elements, so classes and methods together is possible.
5) Hence the correct choice is 'Classes and Methods'.
Q10.Medium
Which of the following CANNOT be a target for a custom attribute in C#?
- Enum
- Event
- Delegate
- Interface
- Namespace
Show answer & explanation
Answer: (E) NamespaceExplanation: 1) AttributeUsage allows targets such as Assembly, Module, Class, Struct, Enum, Constructor, Method, Property, Field, Event, Interface, Parameter, ReturnValue, Delegate, GenericParameter.
2) Enum, Event, Delegate and Interface all appear in this list, so they can be attribute targets.
3) A Namespace is not a program element that carries metadata, so it cannot be an attribute target.
4) Therefore the answer is Namespace.
Q11.MediumAnswer under review
In .NET, once an attribute has been applied to a program element, which of the following CANNOT inspect that applied attribute?
- CLR
- Linker
- ASP.NET Runtime
- Visual Studio.NET
- Language compilers
Show answer & explanation
Answer: (B) LinkerExplanation: 1) Attributes are stored as metadata in the assembly by the language compiler.
2) At run time the CLR and the ASP.NET runtime read this metadata via reflection.
3) Visual Studio.NET (the IDE) also reads attribute metadata for design-time features.
4) The linker works on object code before metadata-based attribute inspection; it does not inspect applied attributes.
5) Hence the linker is the one that cannot inspect the applied attribute.
Bitwise Operators
Q12.EasyAnswer under review
Which of the following is NOT a bitwise operator in C#.NET?
- &
- |
- <<
- ^
- ~
Show answer & explanation
Answer: (C) <<Explanation: 1) & is bitwise AND, | is bitwise OR, ^ is bitwise XOR and ~ is bitwise NOT (complement) - all bitwise operators.
2) << is the left-shift operator; it is classified as a shift operator, not a bitwise operator.
3) Therefore << is the one that is NOT a bitwise operator.
Q13.Medium
Suppose m is a variable of type byte and we wish to check whether its fourth bit (counting from the right, where the rightmost bit is the first) is ON or OFF. Which of the following statements will do this correctly?
- if ((m & 16) == 16) Console.WriteLine("Fourth bit is ON");
- if ((m & 8) == 8) Console.WriteLine("Fourth bit is ON");
- if ((m ! 8) == 8) Console.WriteLine("Fourth bit is ON");
- if ((m ^ 8) == 8) Console.WriteLine("Fourth bit is ON");
- if ((m ~ 8) == 8) Console.WriteLine("Fourth bit is ON");
Show answer & explanation
Answer: (B) if ((m & 8) == 8) Console.WriteLine("Fourth bit is ON");Explanation: 1) Bits are counted from the right: 1st bit = 1, 2nd = 2, 3rd = 4, 4th = 8.
2) So the mask for the fourth bit is 8 (binary 00001000).
3) Bitwise AND with 8 keeps only that bit: e.g. m = 153 (10011001) & 00001000 = 00001000 = 8.
4) If the result equals 8, the fourth bit is ON.
5) Option with 16 checks the fifth bit; !, ^ and ~ are not the correct test.
Q14.Medium
Which of the following statements is correct about the bitwise | (OR) operator used in C#?
- The | operator can be used to put OFF a bit.
- The | operator can be used to invert a bit.
- The | operator can be used to check whether a bit is ON.
- The | operator can be used to check whether a bit is OFF.
- The | operator can be used to put ON a bit.
Show answer & explanation
Answer: (E) The | operator can be used to put ON a bit.Explanation: OR-ing a bit with 1 always yields 1, so | with a mask sets (puts ON) the chosen bits while leaving others unchanged (x | 0 = x). Putting OFF a bit needs AND with 0; inverting needs NOT (~); checking a bit needs AND with a mask.
Q15.Medium
What will be the output of the C#.NET code snippet given below?
byte b1 = 0xF7;
byte b2 = 0xAB;
byte temp;
temp = (byte)(b1 & b2);
Console.Write(temp + " ");
temp = (byte)(b1 ^ b2);
Console.WriteLine(temp);
- 163 92
- 92 163
- 192 63
- 0 1
Show answer & explanation
Answer: (A) 163 92Explanation: Step 1: 0xF7 = 1111 0111 and 0xAB = 1010 1011.
Step 2: AND: 1111 0111 & 1010 1011 = 1010 0011 = 0xA3 = 163.
Step 3: XOR: 1111 0111 ^ 1010 1011 = 0101 1100 = 0x5C = 92.
Step 4: Output is '163 92', which is option 1.
Q16.Medium
Which of the following statements are correct about the bitwise & operator in C#.NET? (1) It can be used to invert a bit. (2) It can be used to put a bit ON. (3) It can be used to put a bit OFF. (4) It can be used to check whether a bit is ON. (5) It can be used to check whether a bit is OFF.
- 1, 2, 4
- 2, 3, 5
- 3, 4
- 3, 4, 5
- None of these
Show answer & explanation
Answer: (D) 3, 4, 5Explanation: 1) ANDing a bit with 0 forces it to 0, so & can put a bit OFF (statement 3 correct).
2) ANDing with a mask and testing the result tells whether a bit is ON (statement 4 correct).
3) Testing the AND result for zero tells whether a bit is OFF (statement 5 correct).
4) Inverting a bit needs ~ (not &), and putting a bit ON needs | (not &), so 1 and 2 are wrong.
5) Hence the correct statements are 3, 4, 5.
Q17.Hard
What will be the output of the following C# code?
byte b1 = 0xAB;
byte b2 = 0x99;
byte temp;
temp = (byte)~b2;
Console.Write(temp + " ");
temp = (byte)(b1 << b2);
Console.Write(temp + " ");
temp = (byte)(b2 >> 2);
Console.WriteLine(temp);
- 102 1 38
- 108 0 32
- 102 0 38
- 1 0 1
Show answer & explanation
Answer: (C) 102 0 38Explanation: b2=0x99=153. ~b2 = -154; as byte: 256-154=102. b1<<b2: shift count is masked to 5 bits (153 & 31 = 25), 0xAB<<25 keeps only low byte = 0. b2>>2 = 153>>2 = 38. Output: 102 0 38.
Constructors
Q18.Easy
How many times can a constructor be called during the lifetime of an object?
- As many times as we call it.
- Only once.
- Depends upon a Project Setting made in Visual Studio.NET.
- Any number of times before the object gets garbage collected.
- Any number of times before the object is deleted.
Show answer & explanation
Answer: (B) Only once.Explanation: A constructor is called exactly once when an object is created. After the object is constructed, the constructor cannot be called again on the same object. Therefore, the correct answer is 'Only once'.
Q19.EasyAnswer under review
In C#, can you prevent an object from being created by using a zero-argument constructor?
- Yes
- No
Show answer & explanation
Answer: (B) NoExplanation: A zero-argument constructor is just a parameterless constructor. It does not prevent object creation; it is used to initialize an object when no arguments are provided. To prevent object creation, you would need to make the constructor private or throw an exception, but that is not the same as using a zero-argument constructor.
Q20.Easy
Which of the following statements is correct about constructors in C#.NET?
- A constructor cannot be declared as private.
- A constructor cannot be overloaded.
- A constructor can be a static constructor.
- A constructor cannot access static data.
Show answer & explanation
Answer: (C) A constructor can be a static constructor.Explanation: 1. Constructors can be private (used in singleton patterns), so option 1 is false.
2. Constructors can be overloaded with different parameter lists, so option 2 is false.
3. C# allows static constructors, which run once to initialize static data, so option 3 is true.
4. Constructors can access static data, so option 4 is false.
Q21.Easy
Given the class below, which of the following object-creation statements will compile correctly?
class Circle
{
int radius;
Single angle;
double area;
public Circle(int r, Single a, double ar)
{
radius = r;
angle = a;
area = ar;
}
}- Circle c1 = new Circle();
- Circle c1 = new Circle(5);
- Circle c2 = new Circle(5, 1.5f);
- Circle c3 = new Circle(5, 1.5f, 2.4);
- Circle c1 = new Circle(, , 2.5);
Show answer & explanation
Answer: (D) Circle c3 = new Circle(5, 1.5f, 2.4);Explanation: Step 1: The class defines only one constructor taking three arguments: int, Single, double.
Step 2: Since a constructor is defined, no default zero-argument constructor exists, so option 1 fails.
Step 3: Options 2 and 3 pass fewer arguments than required, so they fail.
Step 4: Option 5 has empty argument slots, which is invalid syntax.
Step 5: Option 4 passes 5 (int), 1.5f (Single) and 2.4 (double) — matching the constructor exactly.
Q22.Easy
Which of the following statements is correct about constructors in C#?
- If we provide a one-argument constructor then the compiler still provides a zero-argument constructor.
- Static constructors can use optional arguments.
- Overloaded constructors cannot use optional arguments.
- If we do not provide a constructor, then the compiler provides a zero-argument constructor.
Show answer & explanation
Answer: (D) If we do not provide a constructor, then the compiler provides a zero-argument constructor.Explanation: Step 1: In C#, the compiler supplies a default parameterless constructor only when no constructor is written.
Step 2: Once any constructor is defined, the compiler stops providing the default one, so option 1 is false.
Step 3: Static constructors take no parameters, so optional arguments are not allowed (option 2 false).
Step 4: Overloaded constructors may use optional arguments, so option 3 is false.
Step 5: Therefore option 4 is the correct statement.
Q23.Medium
A C# class named Student must allow objects to be created in both of these ways:
Student a = new Student();
Student b = new Student(12, 78.5f);
Which of the following correctly defines the constructor(s) of the Student class?
- public Student() { roll = 0; marks = 0.0f; }
public Student(int r, Single m) { roll = r; marks = m; }
- public Student(Optional int r = 0, Optional Single m = 0.0f) { roll = r; marks = m; }
- public Student(int r, Single m) { roll = r; marks = m; }
- Student s;
s = new Student();
Show answer & explanation
Answer: (A) public Student() { roll = 0; marks = 0.0f; }
public Student(int r, Single m) { roll = r; marks = m; }Explanation: Step 1: The first call new Student() needs a zero-argument constructor.
Step 2: The second call new Student(12, 78.5f) needs a two-argument constructor (int, Single).
Step 3: Option 1 provides both constructors, so both calls compile.
Step 4: Option 2 uses invalid 'Optional' keyword syntax in C#.
Step 5: Option 3 has only the two-argument constructor, so new Student() fails.
Step 6: Option 4 is not a constructor definition at all.
Q24.Medium
Which of the following statements about constructors in C# are correct?
1. Constructors cannot be overloaded.
2. Constructors always have the same name as the class.
3. Constructors are never called explicitly.
4. Constructors never return any value.
5. Constructors allocate space for the object in memory.
- 1, 3, 5
- 2, 3, 4
- 3, 5
- 4, 5
- None of these
Show answer & explanation
Answer: (B) 2, 3, 4Explanation: Constructors can be overloaded, so statement 1 is false. A constructor has the same name as its class (statement 2 true). Constructors are invoked automatically when an object is created, not called explicitly like methods (statement 3 true). They have no return type and return no value (statement 4 true). Memory allocation is done by the runtime, not by the constructor itself (statement 5 false). Hence 2, 3, 4 are correct.
Control Statements
Q25.MediumAnswer under review
Which of the following statements are correct?
1. A switch statement can act on numerical as well as Boolean types.
2. A switch statement can act on characters, strings and enumeration types.
3. We cannot declare variables within a case statement if it is not enclosed by { }.
4. The foreach statement is used to iterate through a collection to get the desired information and should be used to change the contents of the collection to avoid unpredictable side effects.
5. All of the expressions of the for statement are not optional.- 1, 2
- 2, 3
- 3, 5
- 4, 5
- None of these
Show answer & explanation
Answer: (B) 2, 3Explanation: Statement 1 is wrong: switch cannot act on bool in C#.
Statement 2 is correct: char, string and enum are valid switch types.
Statement 3 is correct: a variable declared in a case must be inside a block { } to limit its scope.
Statement 4 is wrong: foreach is read-only; you must not modify the collection while iterating.
Statement 5 is wrong: all three expressions of a for loop are optional.
So the correct statements are 2 and 3.
Q26.Medium
Which of the following statements about C# control statements are correct?
1. The switch statement is a selection statement that handles multiple choices by transferring control to one of its case labels.
2. The goto statement transfers control to the next iteration of the enclosing loop in which it appears.
3. Branching is done using jump statements, which cause an immediate transfer of program control.
4. A common use of continue is to transfer control to a specific switch-case label or to the default label of a switch statement.
5. The do statement executes a statement or a block of statements enclosed in { } repeatedly until a specified expression evaluates to false.- 1, 2, 4
- 1, 3, 5
- 2, 3, 4
- 3, 4, 5
- None of these
Show answer & explanation
Answer: (B) 1, 3, 5Explanation: Statement 1 is correct: switch is a multi-way selection statement.
Statement 2 is wrong: goto jumps to a label, not to the next loop iteration (that is continue).
Statement 3 is correct: jump statements (break, continue, goto, return) transfer control immediately.
Statement 4 is wrong: continue skips to the next iteration of a loop; it cannot target a case label.
Statement 5 is correct: do-while repeats until the condition becomes false.
So the correct set is 1, 3, 5.
Q27.MediumAnswer under review
Which of the following statements about C# control statements is correct?
- It is not possible to extend the if statement to handle multiple conditions using the else-if arrangement.
- The switch statement can include any number of case instances, but two case statements cannot have the same value.
- A jump statement such as break is required after each case block, including the last block even if it is a default statement.
- The if statement selects a statement for execution based on the value of a Boolean expression.
- C# always supports an implicit fall through from one case label to another.
Show answer & explanation
Answer: (D) The if statement selects a statement for execution based on the value of a Boolean expression.Explanation: 1) else-if chains are allowed, so option 1 is false.
2) Duplicate case values cause a compile error, so option 2 is false.
3) break is not required after the last/default block, so option 3 is false.
4) C# does not allow implicit fall through (except empty cases), so option 5 is false.
5) The if statement evaluates a Boolean expression and runs the statement accordingly — option 4 is correct.
Data Types
Q28.Easy
Which of the following is an 8-byte integer in C#?
- char
- long
- short
- byte
- int
Show answer & explanation
Answer: (B) longExplanation: In C#, long is a 64-bit (8-byte) signed integer. char is 2 bytes, short is 2 bytes, byte is 1 byte, and int is 4 bytes.
Q29.Easy
Which of the following is NOT an integer type in C#?
- char
- byte
- int
- short
- long
Show answer & explanation
Answer: (A) charExplanation: In C#, char is a character type (16-bit Unicode), not an integer type. byte, int, short, and long are all integer types.
Q30.Easy
In C#, which of the following data types does NOT store a sign?
- sbyte
- int
- long
- byte
- float
Show answer & explanation
Answer: (D) byteExplanation: In C#, sbyte, int, long, and float are signed types (they can hold negative values). byte is an unsigned 8-bit integer, so it cannot store a sign.
Delegates
Q31.Easy
In a C# application, when a button is clicked an object must be notified, but which object should be notified is decided only at runtime. Which programming construct best implements this?
- Attribute
- Delegate
- Namespace
- Interface
Show answer & explanation
Answer: (B) DelegateExplanation: 1. The requirement is to decide the target method/object at runtime.
2. A delegate is a type-safe function pointer that can be assigned a method at runtime and invoked later.
3. Attributes are metadata, namespaces organize code, interfaces define contracts but don't bind a runtime method.
4. Hence a delegate is the right construct.
Q32.Easy
Which of the following statements about delegates in C# is incorrect?
- Delegates are reference types.
- Delegates are object oriented.
- Delegates are type-safe.
- A single delegate instance can invoke only one method; it cannot hold multiple methods.
Show answer & explanation
Answer: (D) A single delegate instance can invoke only one method; it cannot hold multiple methods.Explanation: 1. Delegates are reference types - true.
2. Delegates are object oriented (they are objects of a class) - true.
3. Delegates are type-safe - true.
4. A delegate can be a multicast delegate holding multiple methods via +=, so the claim that only one method can be called is false.
5. Hence the incorrect statement is the last one.
Q33.Easy
Which of the following statements about a delegate in C# is INCORRECT?
- A single delegate can invoke more than one method.
- Delegates can be shared.
- A delegate is a value type.
- Delegates are type-safe wrappers for function pointers.
- The signature of a delegate must match the signature of the method it calls.
Show answer & explanation
Answer: (C) A delegate is a value type.Explanation: 1. Delegates support multicasting, so one delegate can invoke several methods — statement 1 is true.
2. Delegates are objects and can be shared — statement 2 is true.
3. A delegate is actually a reference type (derived from System.MulticastDelegate), so statement 3 is false.
4. Statements 4 and 5 are true properties of delegates.
5. Hence the incorrect statement is that a delegate is a value type.
Q34.Medium
Which of the following is the correct way to declare a delegate that can refer to the method compute defined in the class Calculator given below?
class Calculator { public double compute(int a, float b) { /* body */ } }- delegate d(int a, float b);
- delegate void d(int, float);
- delegate double d(int a, float b);
- delegate void (int a, float b);
Show answer & explanation
Answer: (C) delegate double d(int a, float b);Explanation: 1. A delegate declaration must specify the return type and parameter list matching the target method.
2. compute returns double and takes (int, float).
3. So the delegate must be declared as returning double with parameters (int, float).
4. Option with 'void' return is wrong; option without return type is invalid; option with no delegate name is invalid.
5. Hence 'delegate double d(int a, float b);' is correct.
Q35.Medium
In C#, which of the following is a necessary condition before you can create a delegate instance that points to a method?
- The method's signature must match the delegate's signature
- The method must be declared inside an abstract class
- The method must throw no exceptions
- The method must be static
Show answer & explanation
Answer: (A) The method's signature must match the delegate's signatureExplanation: 1. A delegate is a type-safe function pointer: it declares a fixed parameter list and return type.
2. Any method assigned to the delegate must have exactly the same parameter types and return type.
3. Therefore matching the signature is the necessary condition.
4. Static/instance, abstract class, or exceptions are not required.
Q36.Medium
Which of the following statements are correct about the delegate declaration: delegate void del(int i); 1. On declaring the delegate, a class called del will get created. 2. The signature of del need not be the same as the signature of the method that we intend to call using it. 3. The del class will be derived from the MulticastDelegate class. 4. The method that can be called using del should not be a static method. 5. The del class will contain a one-argument constructor and an Invoke() method.
- 1, 2 and 3 only
- 1, 3 and 5 only
- 2 and 4 only
- 4 only
- All of the above
Show answer & explanation
Answer: (B) 1, 3 and 5 onlyExplanation: Statement 1 is true: the compiler generates a class named del deriving from MulticastDelegate.
Statement 2 is false: the delegate signature must match the target method's signature.
Statement 3 is true: delegate classes derive from MulticastDelegate.
Statement 4 is false: static methods can also be called through delegates.
Statement 5 is true: the generated class has a constructor taking the target and an Invoke() method.
Hence the correct statements are 1, 3 and 5.
Q37.Medium
Consider the class: class Sample { public int MyFun(int i) { Console.WriteLine("Hello from Jaipur!"); return 0; } } Which of the following is the correct way to call MyFun using a delegate?- delegate void del(int i); Sample s = new Sample(); del d = new del(ref s.MyFun); d(10);
- delegate int del(int i); Sample s = new Sample(); del = new delegate(ref MyFun); del(10);
- Sample s = new Sample(); delegate void del = new delegate(ref MyFun); del(10);
- delegate int del(int i); del d; Sample s = new Sample(); d = new del(s.MyFun); d(10);
Show answer & explanation
Answer: (D) delegate int del(int i); del d; Sample s = new Sample(); d = new del(s.MyFun); d(10);Explanation: MyFun returns int and takes one int parameter, so the delegate must be 'delegate int del(int i)'.
Option 1 uses void return type, which does not match.
Option 2 uses invalid syntax 'new delegate(ref MyFun)' and no instance.
Option 3 declares a delegate variable incorrectly and uses void.
Option 4 correctly declares del(int) returning int, creates Sample, binds s.MyFun and invokes d(10).
Q38.Medium
Consider the class: class Sample { public void MyFun(int i, Single j) { Console.WriteLine("Hello from Pune!"); } } Which of the following is the correct way to call MyFun using a delegate?- delegate void del(int i); Sample s = new Sample(); del d = new del(ref s.MyFun); d(10, 1.1f);
- delegate void del(int i, Single j); del d; Sample s = new Sample(); d = new del(s.MyFun); d(10, 1.1f);
- Sample s = new Sample(); delegate void d = new del(ref MyFun); d(10, 1.1f);
- delegate void del(int i, Single j); Sample s = new Sample(); del = new delegate(ref MyFun); del(10, 1.1f);
Show answer & explanation
Answer: (B) delegate void del(int i, Single j); del d; Sample s = new Sample(); d = new del(s.MyFun); d(10, 1.1f);Explanation: The delegate signature must match MyFun: two parameters (int, Single) and void return.
Option 1 declares del with only one parameter, so it cannot match.
Option 3 declares the delegate incorrectly (delegate void d = ... is invalid syntax).
Option 4 uses invalid syntax 'new delegate(ref MyFun)' and no instance.
Option 2 correctly declares del(int, Single), creates a Sample instance, binds s.MyFun (no ref needed) and invokes with (10, 1.1f).
Q39.Medium
Which of the following statements are correct about a delegate in C#? 1. Inheritance is a prerequisite for using delegates. 2. Delegates are type-safe. 3. Delegates provide wrappers for function pointers. 4. The declaration of a delegate must match the signature of the method that we intend to call using it. 5. Functions called using delegates are always late-bound.
- 1 and 2 only
- 1, 2 and 3 only
- 2, 3 and 4 only
- All of the above
- None of the above
Show answer & explanation
Answer: (C) 2, 3 and 4 onlyExplanation: Statement 1 is false: you do not need inheritance to use delegates.
Statement 2 is true: delegates are type-safe, only matching signatures are accepted.
Statement 3 is true: delegates internally act as wrappers around function pointers.
Statement 4 is true: the delegate signature must match the target method's signature.
Statement 5 is false: delegates are not always late-bound; they can be bound at compile time.
So the correct statements are 2, 3 and 4.
Q40.Medium
Which of the following statements are correct about delegates in C#? 1. Delegates are not type-safe. 2. A delegate is a user-defined type. 3. Only one method can be bound to a single delegate object. 4. Delegates can be used to implement callback notification. 5. Delegates permit execution of a method on a secondary thread in an asynchronous manner.
- 1 and 2 only
- 1, 2 and 3 only
- 2, 4 and 5 only
- 4 and 5 only
- All of the above
Show answer & explanation
Answer: (C) 2, 4 and 5 onlyExplanation: Statement 1 is false: delegates are type-safe, they only accept methods matching their signature.
Statement 2 is true: a delegate is a reference type defined by the user via the delegate keyword.
Statement 3 is false: a multicast delegate can hold references to multiple methods.
Statement 4 is true: delegates are commonly used for callbacks.
Statement 5 is true: delegates support asynchronous invocation (BeginInvoke) on a secondary thread.
Hence the correct statements are 2, 4 and 5.
Q41.MediumAnswer under review
Which of the following statements is correct about delegates in C#.NET?
- Delegates cannot be used to call a static method of a class.
- Delegates cannot be used to call procedures that receive a variable number of arguments.
- If the signatures of two methods are the same they can be called through the same delegate object.
- Delegates cannot be used to call an instance function.
Show answer & explanation
Answer: (B) Delegates cannot be used to call procedures that receive a variable number of arguments.Explanation: Step 1: A delegate can point to both static and instance methods, so options 1 and 4 are wrong.
Step 2: A delegate's signature is fixed at declaration time; it cannot match a method with a variable number of arguments (params), so option 2 is correct.
Step 3: Two methods with the same signature can indeed be invoked through the same delegate object, so option 3 is wrong.
Step 4: Hence the correct statement is option 2.
Enums
Q42.Easy
An enum can be declared inside a class, struct, namespace or interface.
- True
- False
Show answer & explanation
Answer: (A) TrueExplanation: Step 1: In C#, an enum is a type declaration and can be nested inside a class, struct or interface.
Step 2: It can also be declared directly inside a namespace.
Step 3: Hence the statement is True.
Q43.Easy
Which of the following CANNOT be used as an underlying datatype for an enum in C#.NET?
- byte
- short
- float
- int
Show answer & explanation
Answer: (C) floatExplanation: Step 1: C# allows only integral types (byte, sbyte, short, ushort, int, uint, long, ulong) and char as the underlying type of an enum.
Step 2: byte, short and int are all integral types, so they are allowed.
Step 3: float is a floating-point type and is not permitted as an enum's underlying type.
Step 4: Therefore float cannot be used.
Q44.Easy
Which of the following is the correct output for the C#.NET code snippet given below?
enum shade { red, green, blue }
shade c = shade.red;
Type t;
t = c.GetType();
string[] str;
str = Enum.GetNames(t);
Console.WriteLine(str[0]);- red
- 0
- 1
- -1
- shade.red
Show answer & explanation
Answer: (A) redExplanation: c is shade.red, so c.GetType() returns the Type of the enum shade.
Enum.GetNames(t) returns the array of member names in declaration order: {"red","green","blue"}.
str[0] is the first name, which is "red".
Console.WriteLine prints red.
Q45.Easy
Which of the following statements is correct about an enum used in C#.NET?
- enum is a reference type.
- enum is a value type.
- Whether it is a value type or a reference type depends upon its size.
- Whether it is a value type or a reference type depends upon a Project Setting made in Visual Studio.NET.
- We can programmatically control whether it is a value type or a reference type.
Show answer & explanation
Answer: (B) enum is a value type.Explanation: An enum in C# is derived from System.Enum which is a value type (its underlying storage is an integral type).
It is stored on the stack / inline, not on the heap as a reference.
Its size does not change its type category, and no project setting or code can change this.
Hence the correct statement is: enum is a value type.
Q46.Easy
What is the output of the following C#.NET code?
enum shade { crimson, teal, indigo }
shade s;
s = shade.crimson;
Console.WriteLine(s);- 1
- -1
- crimson
- 0
- shade.crimson
Show answer & explanation
Answer: (C) crimsonExplanation: 1) The enum shade has members crimson (0), teal (1), indigo (2).
2) s is assigned shade.crimson.
3) Console.WriteLine on an enum prints the member name, not its numeric value.
4) So the output is crimson.
Q47.Easy
Which of the following statements is correct about the following C#.NET code?
enum status { single, engaged, divorced, widowed }
status.single = 10;
Console.WriteLine(status.engaged);- The program will output a value 11.
- The program will output a value 1.
- The program will output a value 2.
- The program will report an error since an enum element cannot be assigned a value outside the enum declaration.
- The enum elements must be declared private.
Show answer & explanation
Answer: (D) The program will report an error since an enum element cannot be assigned a value outside the enum declaration.Explanation: Enum members are constants; their values can only be set in the enum declaration.
The line 'status.single = 10;' tries to assign a value to an enum member outside the declaration.
This is a compile-time error.
Therefore the program reports an error and never prints anything.
Q48.Easy
What is the output of the following C#.NET code?
enum shade : int { pink, grey, teal = 4, olive, maroon = 9, gold }
Console.Write((int)shade.grey + ", ");
Console.Write((int)shade.gold);- 1, 10
- 2, 10
- 1, 4
- 2, 5
- None of the above
Show answer & explanation
Answer: (A) 1, 10Explanation: pink = 0 (first element).
grey = 1 (next after pink).
teal = 4 (explicitly set).
olive = 5 (teal + 1).
maroon = 9 (explicitly set).
gold = 10 (maroon + 1).
So (int)shade.grey = 1 and (int)shade.gold = 10, giving output '1, 10'.
Q49.Medium
Which of the following statements are correct about an enum used in C#.NET? 1. By default the first enumerator has the value equal to the number of elements present in the list. 2. The value of each successive enumerator is decreased by 1. 3. An enumerator contains white space in its name. 4. A variable cannot be assigned to an enum element. 5. Values of enum elements cannot be populated from a database.
- 1, 2
- 3, 4
- 4, 5
- 1, 4
Show answer & explanation
Answer: (C) 4, 5Explanation: Step 1: By default the first enumerator has value 0 (not the count of elements), so statement 1 is wrong.
Step 2: Each successive enumerator increases by 1, not decreases, so statement 2 is wrong.
Step 3: Enumerator names cannot contain white spaces, so statement 3 is wrong.
Step 4: An enum element is a constant; a variable cannot be assigned to it, so statement 4 is correct.
Step 5: Enum values are fixed at compile time and cannot be populated from a database at runtime, so statement 5 is correct.
Step 6: Hence correct statements are 4 and 5.
Q50.Medium
Which of the following statements are correct about an enum used in C#.NET? 1. Every enum is derived from the Object class. 2. Every enum is a value type. 3. There is no way to print an element of an enum as a string. 4. Every enum is a reference type. 5. The default underlying datatype of an enum is int.
- 1, 2, 5
- 1, 4
- 3, 5
- 2, 3, 4
Show answer & explanation
Answer: (A) 1, 2, 5Explanation: Step 1: Enums in C# implicitly derive from System.Enum which derives from System.Object, so statement 1 is correct.
Step 2: Enums are value types (stored on stack / inline), so statement 2 is correct and statement 4 is wrong.
Step 3: Enum elements can be printed as strings using ToString() or Enum.GetName(), so statement 3 is wrong.
Step 4: The default underlying type of an enum is int, so statement 5 is correct.
Step 5: Hence correct statements are 1, 2 and 5.
Q51.Medium
Which of the following statements is correct about the C#.NET code snippet given below?
enum shade : byte { red = 500, green = 1000, blue = 1500 }- byte values cannot be assigned to enum elements.
- enum elements should always take successive values.
- Since 500, 1000, 1500 exceed the valid range of byte compiler will report an error.
- enum must always be of int type.
- enum elements should be declared as private.
Show answer & explanation
Answer: (C) Since 500, 1000, 1500 exceed the valid range of byte compiler will report an error.Explanation: The enum's underlying type is byte, whose range is 0 to 255.
The assigned values 500, 1000 and 1500 are all greater than 255.
The compiler checks that each constant fits the underlying type, so it reports an error (constant value cannot be converted to byte).
Hence the correct statement is that the compiler will report an error.
Q52.MediumAnswer under review
Which of the following statements are correct about the C#.NET code snippet given below?
namespace BharatConsoleApplication
{
class Sample
{
private enum shade : int { red, green, blue }
public void fun() { Console.WriteLine(shade.red); }
}
class Program
{
static void Main(string[] args)
{
// Use enum shade here
}
}
}
1) To define a variable of type enum shade in Main(), we should use the statement, shade c;
2) enum shade being private it cannot be used in Main().
3) We must declare enum shade as public to be able to use it outside the class Sample.
4) To define a variable of type enum shade in Main(), we should use the statement, Sample.shade c;
5) We must declare private enum shade outside the class to be able to use it in Main().- 1, 2, 3
- 2, 3, 4
- 3, 4
- 4, 5
Show answer & explanation
Answer: (B) 2, 3, 4Explanation: The enum shade is nested inside class Sample and marked private, so it is accessible only within Sample.
1) False - 'shade c;' in Main() fails because shade is not in scope there.
2) True - being private, it cannot be used in Main().
3) True - making it public allows access outside Sample.
4) True - with public access, the nested type is referenced as Sample.shade, so 'Sample.shade c;' works.
5) False - moving it outside the class is not the only fix; making it public (or internal) suffices.
So statements 2, 3 and 4 are correct.
Q53.Medium
Which of the following statements are correct about an enum used in C#.NET? 1) An enum can be declared inside a class. 2) An enum can take Single, Double or Decimal values. 3) An enum can be declared outside a class. 4) An enum can be declared inside/outside a namespace. 5) An object can be assigned to an enum variable.
- 1, 3, 4
- 2, 5
- 3, 4
- 2, 4, 5
Show answer & explanation
Answer: (A) 1, 3, 4Explanation: 1) True - an enum can be nested inside a class.
2) False - enum underlying types must be integral (byte, sbyte, short, int, long, etc.), not float/double/decimal.
3) True - an enum can be declared at namespace level (outside a class).
4) True - enums can be declared inside or outside a namespace.
5) False - you cannot assign an object to an enum variable without an explicit cast.
So the correct statements are 1, 3 and 4.
Q54.Medium
Which of the following statements is correct about the C#.NET code snippet given below?
int a = 10;
int b = 20;
int c = 30;
enum shade : byte { crimson = a, teal = b, indigo = c }- Variables cannot be assigned to enum elements.
- Variables can be assigned to any one of the enum elements.
- Variables can be assigned only to the first enum element.
- Values assigned to enum elements must always be successive values.
- Values assigned to enum elements must always begin with 0.
Show answer & explanation
Answer: (A) Variables cannot be assigned to enum elements.Explanation: 1) Enum member values must be compile-time constants.
2) Local variables a, b, c are not constants, so they cannot be used as enum member values.
3) This causes a compile-time error; hence variables cannot be assigned to enum elements.
4) Options about successive values or starting at 0 are not required rules.
Q55.Medium
Which of the following statements is true about an enum used in C#.NET?
- An implicit cast is needed to convert from enum type to an integral type.
- An enum variable cannot have a public access modifier.
- An enum variable cannot have a private access modifier.
- An enum variable can be defined inside a class or a namespace.
- An enum variable cannot have a protected access modifier.
Show answer & explanation
Answer: (D) An enum variable can be defined inside a class or a namespace.Explanation: 1) Converting an enum to an integral type requires an explicit cast, not implicit, so option 1 is false.
2) Enum variables can carry public, private or protected modifiers, so options 2, 3 and 5 are false.
3) An enum declaration may be nested inside a class or placed directly in a namespace, so option 4 is true.
Q56.Medium
Which of the following statements about the enum keyword in C#.NET are correct?
1. To use the keyword enum, we should either use [enum] or System.Enum.
2. enum is a keyword.
3. Enum is a class declared in the System.Type namespace.
4. Enum is a class declared in the current project's root namespace.
5. Enum is a class declared in the System namespace.
- 1, 3
- 2, 4
- 2, 5
- 3, 4
Show answer & explanation
Answer: (C) 2, 5Explanation: 1) 'enum' is a reserved C# keyword, so statement 2 is true.
2) The base class System.Enum lives in the System namespace, so statement 5 is true.
3) System.Type is a different class (reflection), so statement 3 is false.
4) Enum is not declared in the project's root namespace, so statement 4 is false.
5) Statement 1 is incorrect wording; hence correct pair is 2 and 5.
Q57.Medium
What is the output of the following C#.NET code?
enum shade : int
{
crimson = -5,
teal,
indigo
}
Console.Write((int) shade.crimson + ", ");
Console.Write((int) shade.teal + ", ");
Console.Write((int) shade.indigo);- -5, -4, -3
- -5, 0, 1
- 0, 1, 2
- crimson, teal, indigo
- shade.crimson, shade.teal, shade.indigo
Show answer & explanation
Answer: (A) -5, -4, -3Explanation: 1) In an enum, the first member without an explicit value starts at 0, but here crimson is explicitly set to -5.
2) Each subsequent member without a value is previous + 1, so teal = -5 + 1 = -4.
3) indigo = -4 + 1 = -3.
4) Casting each to int and printing gives -5, -4, -3.
Q58.Medium
An enum declared inside a class, struct, namespace or interface is treated as public by default.
- True
- False
Show answer & explanation
Answer: (B) FalseExplanation: In C#, a nested type such as an enum declared inside a class or struct has private accessibility by default.
An enum declared directly in a namespace has internal accessibility by default.
It is not public by default in either case.
Hence the statement is False.
Exception Handling
Q59.Easy
Which of the following statements is correct about an Exception in C#?
- It occurs during compilation.
- It occurs during linking.
- It occurs at run-time.
- It occurs during Just-In-Time compilation.
- It occurs during loading of the program.
Show answer & explanation
Answer: (C) It occurs at run-time.Explanation: 1) Compilation errors are detected by the compiler before the program runs. 2) Linking and loading happen before execution begins. 3) An exception is an abnormal condition that arises while the program is executing. 4) Hence exceptions occur at run-time.
Q60.Easy
In C#.NET, if an exception is thrown at runtime and is not caught by any catch block in the program, which of the following handles it?
- Compiler
- CLR
- Linker
- Loader
- Operating system
Show answer & explanation
Answer: (B) CLRExplanation: 1) The compiler only checks syntax and types, not runtime exceptions. 2) The linker and loader deal with combining and loading assemblies. 3) At runtime, the Common Language Runtime (CLR) tracks unhandled exceptions. 4) If no catch handles the exception, the CLR terminates the program and reports the unhandled exception.
Q61.Medium
Which of the following statements are correct about exception handling in C#.NET? 1. try blocks cannot be nested. 2. In one method, there can be only one try block. 3. An exception must be caught in the same method in which it is thrown. 4. All values set up in the exception object are available in the catch block. 5. While throwing a user-defined exception, multiple values can be set in the exception object.
- 1 only
- 1 and 2 only
- 3 only
- 4 and 5 only
- All of the above
Show answer & explanation
Answer: (D) 4 and 5 onlyExplanation: 1 is false: try blocks can be nested inside one another.
2 is false: a method can contain several try blocks.
3 is false: an exception can be caught in a calling method, not necessarily where it was thrown.
4 is true: the catch block receives the exception object with all its set values.
5 is true: a user-defined exception class can carry multiple fields/values.
Hence only 4 and 5 are correct.
Q62.Medium
What is the output of the following C# program if the user enters the text "ABCD" when prompted? using System; namespace SampleApp { class Demo { static void Main(string[] args) { int pos; int num = 60; int[] arr = new int[5]; try { Console.Write("Enter a number: "); pos = Convert.ToInt32(Console.ReadLine()); arr[pos] = num; } catch (Exception e) { Console.Write("Exception occurred"); } Console.Write("Remaining program"); } } }- It will output: Exception occurred
- It will output: Remaining program
- It will output: Remaining program Exception occurred
- It will output: Exception occurred Remaining program
- The value 60 will get assigned to arr[0].
Show answer & explanation
Answer: (D) It will output: Exception occurred Remaining programExplanation: 1) The prompt 'Enter a number: ' is printed. 2) Convert.ToInt32("ABCD") cannot parse the text and throws a FormatException. 3) The catch block catches it and prints 'Exception occurred'. 4) Execution continues after try-catch and prints 'Remaining program'. 5) Combined output: 'Exception occurred Remaining program'.
Q63.Medium
In C#, is it compulsory for every class whose objects can be thrown with the throw statement to be derived from the System.Exception class?
- True
- False
Show answer & explanation
Answer: (A) TrueExplanation: 1) In C#, the throw statement requires an object of a type derived from System.Exception. 2) You cannot throw arbitrary objects (unlike some other languages). 3) Therefore any throwable class must derive from System.Exception. 4) So the statement is True.
Q64.Medium
What is the output of the following C# program? using System; namespace SampleApp { class Demo { static void Main(string[] args) { int pos = 7; int num = 25; int[] arr = new int[4]; try { arr[pos] = num; } catch (IndexOutOfRangeException e) { Console.Write("Index out of bounds "); } Console.Write("Remaining program"); } } }- Value 25 will get assigned to arr[7].
- It will output: Index out of bounds
- It will output: Remaining program
- It will not produce any output.
- It will output: Index out of bounds Remaining program
Show answer & explanation
Answer: (E) It will output: Index out of bounds Remaining programExplanation: 1) arr has size 4, so valid indices are 0..3. 2) pos = 7 is out of range, so arr[7] = 25 throws IndexOutOfRangeException. 3) The catch block prints 'Index out of bounds '. 4) Execution continues after the try-catch and prints 'Remaining program'. 5) Combined output: 'Index out of bounds Remaining program'.
Exception Handling Output
Q65.Medium
What is the output of the following C# program if the user enters the value 6? using System; namespace DemoApp { class Program { static void Main(string[] args) { int index; int val = 66; int[] a = new int[5]; try { Console.Write("Enter a number: "); index = Convert.ToInt32(Console.ReadLine()); a[index] = val; } catch (Exception e) { Console.Write("Exception occurred "); } Console.Write("Remaining program"); } } }- Exception occurred
- Remaining program
- Exception occurred Remaining program
- Remaining program Exception occurred
- The value 66 will get assigned to a[6].
Show answer & explanation
Answer: (C) Exception occurred Remaining programExplanation: 1. The array a has 5 elements, valid indices 0 to 4.
2. The user enters 6, so a[6] = 66 attempts an out-of-range access.
3. This throws an IndexOutOfRangeException, which is caught by catch(Exception e).
4. The catch block prints "Exception occurred ".
5. Execution continues and prints "Remaining program".
6. Combined output: "Exception occurred Remaining program".
Q66.Medium
What is the output of the following C# program if the user enters the text "ABCD"? using System; namespace DemoApp { class Program { static void Main(string[] args) { int index; int val = 42; int[] a = new int[5]; try { Console.Write("Enter a number: "); index = Convert.ToInt32(Console.ReadLine()); a[index] = val; } catch (FormatException e) { Console.Write("Bad Format "); } catch (IndexOutOfRangeException e) { Console.Write("Index out of bounds "); } Console.Write("Remaining program"); } } }- Bad Format
- Remaining program
- Index out of bounds
- Bad Format Remaining program
- Index out of bounds Remaining program
Show answer & explanation
Answer: (D) Bad Format Remaining programExplanation: 1. The input "ABCD" is passed to Convert.ToInt32, which cannot parse it.
2. This throws a FormatException.
3. The first catch block catches FormatException and prints "Bad Format ".
4. The IndexOutOfRangeException catch is skipped.
5. Execution continues after the try-catch, printing "Remaining program".
6. Combined output: "Bad Format Remaining program".
Q67.Medium
What will the following C# program output if the user enters the value "7" when prompted? using System; namespace DelhiConsoleApp { class DemoProgram { static void Main(string[] args) { int pos; int num = 25; int[] arr = new int[4]; try { Console.Write("Enter a number:"); pos = Convert.ToInt32(Console.ReadLine()); arr[pos] = num; } catch (FormatException e) { Console.Write("Bad Format"); } catch (IndexOutOfRangeException e) { Console.Write("Index out of bounds"); } Console.Write("Remaining program"); } } }- It will output: Index out of bounds Remaining program
- It will output: Bad Format Remaining program
- It will output: Bad Format
- It will output: Remaining program
- It will output: Index out of bounds
Show answer & explanation
Answer: (A) It will output: Index out of bounds Remaining programExplanation: 1) The array arr has size 4, so valid indices are 0 to 3.
2) The user enters 7, which converts fine to int (no FormatException).
3) arr[7] = num throws IndexOutOfRangeException.
4) That catch prints 'Index out of bounds'.
5) Execution continues after the try-catch and prints 'Remaining program'.
6) Combined output: 'Index out of bounds Remaining program'.
Garbage Collection
Q68.Easy
In C#, is it possible to invoke the Garbage Collector explicitly?
- Yes
- No
Show answer & explanation
Answer: (A) YesExplanation: In C#, you can explicitly invoke the garbage collector by calling GC.Collect(). This forces a garbage collection. However, it is generally not recommended because the garbage collector is optimized to run automatically.
Q69.Medium
Which of the following tasks are NOT performed by the .NET Garbage Collector? (1) Freeing memory allocated on the stack. (2) Preventing memory leaks. (3) Freeing memory of unreferenced objects. (4) Closing unclosed database connections. (5) Closing unclosed files.
- 1, 2, 3
- 3, 5
- 1, 4, 5
- 3, 4
Show answer & explanation
Answer: (C) 1, 4, 5Explanation: 1. The GC manages only the managed heap, so it does NOT free stack memory (task 1 is not done).
2. It does help avoid memory leaks by reclaiming unreachable objects (task 2 is done).
3. It frees memory of unreferenced objects (task 3 is done).
4. Database connections are unmanaged resources; the GC does not close them (task 4 is not done).
5. Files are also unmanaged handles; the GC does not close them (task 5 is not done).
6. So the tasks NOT performed are 1, 4 and 5.
Q70.Medium
Which of the following statements about garbage collection in .NET is correct?
- There is one garbage collector per program running in memory.
- There is one common garbage collector for all programs.
- An object is destroyed by the garbage collector when only one reference refers to it.
- We have to specifically run the garbage collector after executing Visual Studio.NET.
Show answer & explanation
Answer: (A) There is one garbage collector per program running in memory.Explanation: In .NET, each application domain (or process) has its own garbage collector. The garbage collector runs per process, not shared across all programs. An object is collected when there are no references to it, not when only one reference exists. You do not need to manually run the garbage collector after using Visual Studio.NET.
Generics
Q71.Medium
For the code snippet below, which statement is valid?
public class Holder<T>
{
public T Value;
public void Increment()
{
T x = Value + 1;
}
}
class Demo
{
static void Main(string[] args)
{
Holder<int> h = new Holder<int>();
h.Increment();
}
}- The addition produces the result 1.
- The result of the addition depends on the system.
- The program throws a run-time exception.
- The compiler reports an error: Operator '+' cannot be applied to operands of type 'T' and 'int'.
- None of the above.
Show answer & explanation
Answer: (D) The compiler reports an error: Operator '+' cannot be applied to operands of type 'T' and 'int'.Explanation: 1) Inside the generic class, T is an unconstrained type parameter.
2) The compiler does not know whether T supports the '+' operator.
3) Therefore Value + 1 is invalid at compile time, regardless of the fact that Main uses Holder<int>.
4) The error is a compile-time error, not a run-time exception.
Q72.Medium
Which of the following statements about generics in the .NET Framework are valid? 1. Generics is a language feature. 2. We can create a generic class but not a generic interface in C#.NET. 3. Generic delegates are not allowed in C#.NET. 4. Generics are useful in collection classes in the .NET Framework.
- 1 and 2 only
- 1, 2 and 3 only
- 1 and 4 only
- All of the above
- None of the above
Show answer & explanation
Answer: (C) 1 and 4 onlyExplanation: 1) Statement 1 is true: generics is a language feature supported by C#.
2) Statement 2 is false: C# allows generic interfaces such as IComparable<T>.
3) Statement 3 is false: generic delegates such as Action<T> and Func<T> are allowed.
4) Statement 4 is true: generic collection classes like List<T> and Dictionary<K,V> are widely used.
5) So only statements 1 and 4 are valid.
Q73.MediumAnswer under review
In C#.NET, which statement about generic methods is correct?
- Every method inside a generic class is automatically generic.
- Only methods explicitly declared with their own type parameters are generic.
- A generic method can have at most one type parameter.
- A generic method must have at least one type parameter.
- None of the above.
Show answer & explanation
Answer: (B) Only methods explicitly declared with their own type parameters are generic.Explanation: 1) A generic class such as Box<T> may contain ordinary non-generic methods.
2) A method is generic only when it declares its own type parameters, e.g. void Show<U>(U item).
3) A generic method may have zero, one or many type parameters, so the 'at most one' and 'at least one' claims are wrong.
4) Hence only the second statement is valid.
Q74.Medium
Which of the following statements is a valid advantage of generics in C#?
- Generics shift the burden of type safety to the programmer rather than the compiler.
- Generics require the use of explicit type casting.
- Generics provide type safety without the overhead of multiple implementations.
- Generics eliminate the possibility of run-time errors.
Show answer & explanation
Answer: (C) Generics provide type safety without the overhead of multiple implementations.Explanation: Generics allow you to write type-safe code without duplicating implementations for each type. The compiler enforces type safety, so you don't need explicit casts, and you avoid the overhead of multiple type-specific versions. They reduce but do not eliminate all run-time errors.
Indexers
Q75.Medium
An indexer allows which of the following to be indexed in the same way as an array? 1. A class 2. A property 3. A struct 4. A function 5. An interface
- 1, 3, 5
- 2, 4
- 3, 5
- 3, 4, 5
Show answer & explanation
Answer: (A) 1, 3, 5Explanation: 1) An indexer is a member that lets an object be indexed like an array using this[...]. 2) It can be declared in a class (1), a struct (3) and an interface (5). 3) A property (2) and a function (4) cannot themselves be indexed this way. 4) So the correct set is 1, 3, 5.
Q76.Medium
A class named Matrix has an indexer. Which of the following declarations correctly defines the indexer so that the code below compiles and runs? Matrix m = new Matrix(); m[1, 2] = 35;
- class Matrix { int[,] a = new int[5, 5]; public property WriteOnly int this[int i, int j] { set { a[i, j] = value; } } }
- class Matrix { int[,] a = new int[5, 5]; public int property WriteOnly { set { a[i, j] = value; } } }
- class Matrix { int[,] a = new int[5, 5]; public int this[int i, int j] { set { a[i, j] = value; } } }
- class Matrix { int[,] a = new int[5, 5]; int i, j; public int this { set { a[i, j] = value; } } }
Show answer & explanation
Answer: (C) class Matrix { int[,] a = new int[5, 5]; public int this[int i, int j] { set { a[i, j] = value; } } }Explanation: 1. An indexer is declared with the keyword this followed by a parameter list in square brackets, and it has no name of its own.
2. The usage m[1, 2] = 35 requires two int parameters, so the declaration must be public int this[int i, int j].
3. Option 1 wrongly uses the keyword 'property' and 'WriteOnly'.
4. Option 2 has no parameter list and uses invalid syntax.
5. Option 4 has no parameter list on this, so it cannot accept indices.
6. Only option 3 declares a two-parameter indexer with a set accessor that assigns a[i, j] = value.
Q77.Medium
Which of the following statements about indexers in C# are correct? (1) The signature of an indexer consists of the number and types of its formal parameters. (2) Indexers are similar to properties except that their accessors take parameters. (3) Accessors of interface indexers may use access modifiers. (4) The type of an indexer and the type of its parameters must be at least as accessible as the indexer itself. (5) An interface accessor contains a body.
- 1, 3, 5
- 1, 2, 4
- 3, 5
- 2, 4
Show answer & explanation
Answer: (B) 1, 2, 4Explanation: 1. Statement 1 is true: an indexer's signature is defined by the number and types of its parameters.
2. Statement 2 is true: indexers resemble properties but their accessors take parameters (the index).
3. Statement 3 is false: accessors of interface indexers cannot use access modifiers.
4. Statement 4 is true: the indexer type and its parameter types must be at least as accessible as the indexer.
5. Statement 5 is false: interface accessors have no body.
6. So the correct statements are 1, 2 and 4.
Q78.Medium
A Student class has an indexer that stores or retrieves values in an array of 5 integers. Which of the following are correct ways to use this indexer? (1) Student[3] = 34; (2) Student s = new Student(); s[3] = 34; (3) Student s = new Student(); Console.WriteLine(s[3]); (4) Console.WriteLine(Student[3]); (5) Student.this s = new Student.this(); s[3] = 34;
- 1, 2
- 2, 3
- 3, 4
- 3, 5
Show answer & explanation
Answer: (B) 2, 3Explanation: 1. An indexer is an instance member, so Student[3] on the type name is invalid.
2. Creating an instance s and writing s[3] = 34 uses the indexer correctly.
3. Reading Console.WriteLine(s[3]) on an instance is also valid.
4. Student[3] on the class name is invalid (no static indexer).
5. 'Student.this' is not valid syntax.
So the correct usages are 2 and 3.
Inheritance
Q79.Easy
In C#, which mechanism is used to model an 'is-a' (or 'kind of') relationship between two classes?
- Polymorphism
- Containership
- Generics
- Encapsulation
- Inheritance
Show answer & explanation
Answer: (E) InheritanceExplanation: 1. An 'is-a' relationship means one class is a specialized kind of another (e.g., a Car is a Vehicle).
2. Inheritance (class Derived : Base) expresses exactly this 'kind of' relationship.
3. Containership ('has-a') means one class holds an object of another as a field.
4. Polymorphism and encapsulation are OOP principles, not relationship-modelling mechanisms.
5. Hence Inheritance is the correct choice.
Q80.Easy
There is no multiple inheritance in C#.NET. That is, a class cannot be derived from multiple base classes.
- True
- False
Show answer & explanation
Answer: (A) TrueExplanation: 1) In C#, a class can inherit from only one base class (single inheritance).
2) Multiple inheritance of classes is not allowed; however, a class can implement multiple interfaces.
3) Hence the statement is True.
Q81.Easy
How can you prevent inheritance from a class in C#.NET?
- Declare the class as shadows.
- Declare the class as overloads.
- Declare the class as sealed.
- Declare the class as suppress.
- Declare the class as override.
Show answer & explanation
Answer: (C) Declare the class as sealed.Explanation: 1) C# provides the 'sealed' modifier for classes.
2) A sealed class cannot be used as a base class for other classes.
3) This is the standard way to prevent a class from being inherited (and thus prevent its behavior from being changed via derivation).
4) 'shadows', 'overloads', 'suppress' and 'override' are not class-level modifiers for this purpose.
Q82.Easy
Creating a derived class from a base class requires fundamental changes to the base class.
- True
- False
Show answer & explanation
Answer: (B) FalseExplanation: 1) In C#, a class can be derived from an existing base class without modifying the base class at all.
2) The base class only needs to be non-sealed and accessible; no source changes are required.
3) Therefore the statement is False.
Q83.Medium
Which of the following statements are correct about inheritance in C#.NET?
1. A derived class object contains all the base class data.
2. Inheritance cannot suppress the base class functionality.
3. A derived class may not be able to access all the base class data.
4. Inheritance cannot extend the base class functionality.
5. In an inheritance chain, construction of the object happens from base towards derived.
- 1, 2, 4
- 2, 4, 5
- 1, 3, 5
- 2, 4
Show answer & explanation
Answer: (C) 1, 3, 5Explanation: 1) Statement 1 is correct: a derived object includes the base class portion (all base fields exist in the object).
2) Statement 2 is wrong: a derived class can hide/suppress base members (e.g., with 'new'), so functionality can be suppressed.
3) Statement 3 is correct: private members of the base class are not accessible in the derived class.
4) Statement 4 is wrong: inheritance is precisely a mechanism to extend base functionality.
5) Statement 5 is correct: base class constructor runs before derived class constructor, so construction goes base -> derived.
6) Correct set is 1, 3, 5.
Interfaces
Q84.Easy
Which of the following statements about interfaces in C# is correct?
- When a class inherits an interface it inherits member definitions as well as their implementations.
- An interface cannot contain the signature of an indexer.
- Interface members are automatically public.
- To implement an interface member, the corresponding member in the class must be public as well as static.
Show answer & explanation
Answer: (C) Interface members are automatically public.Explanation: Option 1 is wrong: an interface carries no implementations, only signatures.
Option 2 is wrong: an interface can declare an indexer signature.
Option 3 is correct: members declared in an interface are implicitly public.
Option 4 is wrong: implementing members must be public but need not be static.
Hence the correct statement is option 3.
Q85.Medium
Which of the following statements are correct about an interface in C#.NET?
1. An interface can contain properties, methods and events.
2. The keyword 'implements' forces implementation of an interface.
3. Interfaces can be overloaded.
4. Interfaces can be implemented by a class or a struct.
5. Enhanced implementations of an interface can be developed without breaking existing code.
- 1, 2
- 1, 4, 5
- 3, 4
- 3 only
Show answer & explanation
Answer: (B) 1, 4, 5Explanation: Statement 1 is true: interfaces may declare properties, methods and events.
Statement 2 is false: C# uses ':' for implementation, there is no 'implements' keyword.
Statement 3 is false: interfaces themselves are not overloaded; methods inside them can be overloaded but the statement as worded is wrong.
Statement 4 is true: both classes and structs can implement interfaces.
Statement 5 is true: new members can be added via new interfaces or default implementations without breaking existing code.
So the correct set is 1, 4, 5.
Q86.Medium
Which of the following statements about an interface used in C#.NET is correct?
- One class can implement only one interface.
- If one class in a program implements an interface, no other class in that program can implement the same interface.
- A new interface cannot be inherited from two base interfaces.
- Properties can be declared inside an interface.
- Interfaces cannot be inherited.
Show answer & explanation
Answer: (D) Properties can be declared inside an interface.Explanation: 1) An interface may declare properties (e.g., int Area { get; }), events and indexers besides methods. 2) A class can implement many interfaces. 3) Many classes can implement the same interface. 4) An interface can extend multiple base interfaces. 5) Interfaces can be inherited. Hence option D is correct.
Q87.Medium
Which of the following statements about interfaces in C#.NET is correct?
- All interfaces are derived from the Object class.
- Interfaces can be inherited (one interface can extend another).
- All interfaces are derived from an Object interface.
- Interfaces can contain only method declarations and nothing else.
- Interfaces can contain static data fields and static methods.
Show answer & explanation
Answer: (B) Interfaces can be inherited (one interface can extend another).Explanation: 1) An interface can extend one or more other interfaces, e.g., interface IC : IA, IB { }. 2) Interfaces are not derived from the Object class (only classes are). 3) There is no 'Object interface'. 4) Interfaces can also contain properties, events and indexers, not only methods. 5) Classic interfaces cannot hold static data fields. So option B is correct.
Q88.Medium
In C#.NET, which statement about interfaces is correct?
- A class that implements an interface only partially must be declared abstract.
- A class can never implement an interface partially.
- An interface can contain static methods.
- An interface can contain static data fields.
- Multiple interface inheritance is not allowed.
Show answer & explanation
Answer: (A) A class that implements an interface only partially must be declared abstract.Explanation: 1) If a class does not provide implementations for all interface members, it leaves them unimplemented. 2) A non-abstract class cannot have unimplemented members, so it must be marked abstract. 3) A class can indeed implement partially if it is abstract, so option B is wrong. 4) Classic interfaces cannot hold static data fields; multiple interface inheritance is allowed. Hence option A is correct.
Q89.Medium
In C#, which of the following statements about interfaces is correct?
- A single interface can be implemented by more than one class within the same program.
- A class that implements an interface must explicitly re-declare every member of that interface.
- The methods declared inside an interface always contain a method body.
- One interface can be implemented inside another interface using the implements keyword.
Show answer & explanation
Answer: (A) A single interface can be implemented by more than one class within the same program.Explanation: 1) An interface is a contract; any number of classes (e.g., Circle, Square) can implement the same interface IShape. 2) Members of an interface are implemented implicitly by the class, no explicit re-declaration is required. 3) Interface methods have no body (only signatures). 4) Interfaces are inherited/extended, not 'implemented inside' another interface. Hence only option A is correct.
Q90.Medium
Which of the following statements are correct about an interface in C#.NET? 1. A class can implement multiple interfaces. 2. Structures cannot inherit a class but can implement an interface. 3. In C#.NET, : is used to signify that a class member implements a specific interface. 4. An interface can implement multiple classes. 5. The static attribute can be used with a method that implements an interface declaration.
- 1, 2, 3
- 2, 4
- 3, 5
- None of the above.
Show answer & explanation
Answer: (A) 1, 2, 3Explanation: Statement 1 is correct: a class can implement multiple interfaces. Statement 2 is correct: structs cannot inherit from a class but can implement interfaces. Statement 3 is correct: the colon ':' is used to indicate that a class implements an interface. Statement 4 is wrong because an interface cannot implement classes; classes implement interfaces. Statement 5 is wrong because interface methods cannot be declared static in the traditional sense. Hence 1, 2 and 3 are correct.
Jagged Arrays
Q91.Medium
Which of the following statements is correct about the array declaration given below? int[][][] scores = new int[3][][];
- scores refers to a 2-D jagged array containing 3 rows.
- scores refers to a 2-D jagged array containing 2 rows.
- scores refers to a 3-D jagged array containing 3 2-D jagged arrays.
- scores refers to a 3-D jagged array containing two 2-D jagged arrays.
- scores refers to a 3-D jagged array containing 3 2-D rectangular arrays.
Show answer & explanation
Answer: (C) scores refers to a 3-D jagged array containing 3 2-D jagged arrays.Explanation: int[][][] is a jagged array of three levels, i.e. a 3-D jagged array.
new int[3][][] allocates the outermost level with 3 elements.
Each of those 3 elements is itself a 2-D jagged array (int[][]), initially null.
So scores refers to a 3-D jagged array containing 3 2-D jagged arrays.
Q92.Medium
Which of the following is the correct output of the C# code snippet given below?
int[][] data = new int[2][];
data[0] = new int[4] { 8, 3, 6, 5 };
data[1] = new int[3] { 11, 4, 9 };
Console.WriteLine(data[1].GetUpperBound(0));- 3
- 4
- 9
- 11
- 2
Show answer & explanation
Answer: (E) 2Explanation: 1) data[1] is an int array of size 3: { 11, 4, 9 }. 2) Its valid indices are 0, 1, 2. 3) GetUpperBound(0) returns the highest index of the first dimension, which is 2. 4) Hence the output is 2.
Q93.Medium
Which of the following statements are correct about the C#.NET code snippet given below?
int [][] marks = new int [ 2 ][];
marks [ 0 ] = new int [ 4 ]{ 6 , 1 , 4 , 3 };
marks [ 1 ] = new int [ 3 ]{ 9 , 2 , 7 };- marks is a reference to a 2-D jagged array.
- The two rows of the jagged array marks are stored in adjacent memory locations.
- marks [ 0 ] refers to the zeroth 1-D array and marks [ 1 ] refers to the first 1-D array.
- marks refers to marks [ 0 ] and marks [ 1 ].
- marks refers to marks [ 1 ] and marks [ 2 ].
Show answer & explanation
Answer: (C) marks [ 0 ] refers to the zeroth 1-D array and marks [ 1 ] refers to the first 1-D array.Explanation: 1. int[][] marks declares a jagged array: an array whose elements are themselves 1-D arrays.
2. marks[0] is assigned new int[4]{6,1,4,3}, so marks[0] refers to the zeroth 1-D array.
3. marks[1] is assigned new int[3]{9,2,7}, so marks[1] refers to the first 1-D array.
4. The rows of a jagged array are separate objects on the heap, so they need not be adjacent (option 2 is wrong).
5. marks is the outer array reference, not a reference to the inner arrays themselves (options 4 and 5 are wrong).
6. Hence the correct statement is option 3.
Logical Operators
Q94.Easy
Which of the following statements are correct about the C#.NET code snippet given below?
if (age > 21 && marks < 15 )
a = 30 ;
1. The condition marks < 15 will be evaluated only if age > 21 evaluates to True.
2. The statement a = 30 will get executed if any one condition is True.
3. The condition marks < 15 will be evaluated only if age > 21 evaluates to False.
4. The statement a = 30 will get executed if both the conditions are True.
5. && is known as a short-circuiting logical operator.- 1, 3
- 2, 5
- 1, 4, 5
- 3, 4, 5
- None of these
Show answer & explanation
Answer: (C) 1, 4, 5Explanation: && evaluates left to right and stops early: the right operand marks < 15 is checked only when age > 21 is true, so statement 1 is correct and 3 is wrong.
The body a = 30 runs only when both conditions are true, so 4 is correct and 2 is wrong.
&& is indeed a short-circuiting operator, so 5 is correct.
Hence the correct set is 1, 4, 5.
Q95.Easy
Which of the following statements are correct about the following code snippet?
int a = 10;
int b = 20;
bool c;
c = !(a > b);
1. There is no error in the code snippet.
2. An error will be reported since ! can work only with an int.
3. A value 1 will be assigned to c.
4. A value True will be assigned to c.
5. A value False will be assigned to c.
- 1, 3
- 2, 4
- 4, 5
- 1, 4
- None of these
Show answer & explanation
Answer: (D) 1, 4Explanation: Step 1: a > b means 10 > 20, which is False.
Step 2: !(False) = True, so c gets the Boolean value True.
Step 3: The ! operator works on Boolean values, so there is no error.
Step 4: c is bool, so it stores True (not 1).
Step 5: Correct statements are 1 and 4, which is option 4.
Q96.Easy
In C#.NET, which of the following are logical operators? (1) && (2) || (3) ! (4) Xor (5) %
- 1, 2, 3
- 1, 3, 4
- 2, 4, 5
- 3, 4, 5
- None of these
Show answer & explanation
Answer: (A) 1, 2, 3Explanation: 1) && is the conditional AND operator.
2) || is the conditional OR operator.
3) ! is the logical NOT operator.
4) Xor is not a C# operator (the bitwise XOR symbol is ^), and % is the modulus operator, not logical.
5) So the logical operators are 1, 2, 3.
Q97.MediumAnswer under review
Consider the C# statement:
if (marks > 60 || age < 12)
result = 1;
Which of the following statements are correct?
1. The condition age < 12 is evaluated only if marks > 60 is false.
2. The condition age < 12 is evaluated if marks > 60 is true.
3. The statement result = 1 executes if at least one of the two conditions is true.
4. || is a short-circuiting logical operator.
5. The statement result = 1 executes only if both conditions are true.- 1, 4, 5
- 2, 4
- 1, 3, 4
- 2, 3, 5
- None of these
Show answer & explanation
Answer: (C) 1, 3, 4Explanation: 1. || is the short-circuiting OR operator (statement 4 correct).
2. With short-circuiting, the right operand age < 12 is evaluated only if the left operand marks > 60 is false (statement 1 correct, statement 2 wrong).
3. OR is true if at least one condition is true, so result = 1 executes when either is true (statement 3 correct, statement 5 wrong).
4. Hence correct set is 1, 3, 4.
Namespaces
Q98.Easy
Which of the following statements is correct about a namespace in C#.NET?
- Namespaces help us to organise classes and avoid name clashes between them.
- A namespace can contain a class but not another namespace.
- If not mentioned, then the name 'root' gets assigned to the namespace.
- It is necessary to use the using statement to be able to use an element of a namespace.
- A namespace can contain only methods, not classes.
Show answer & explanation
Answer: (A) Namespaces help us to organise classes and avoid name clashes between them.Explanation: Step 1: The main purpose of a namespace is to group related types and prevent naming conflicts, so option 1 is correct.
Step 2: Namespaces can be nested inside other namespaces, so option 2 is false.
Step 3: There is no default 'root' namespace name, so option 3 is false.
Step 4: A using statement is convenient but not mandatory; fully qualified names work without it, so option 4 is false.
Step 5: Namespaces can contain classes, so option 5 is false.
Q99.Easy
Which of the following statements is correct about namespaces in C#.NET?
- Namespaces can be nested only up to level 5.
- A namespace cannot be nested.
- There is no limit on the number of levels while nesting namespaces.
- If namespaces are nested, then it is necessary to use using statement while using the elements of the inner namespace.
- Nesting of namespaces is permitted, provided all the inner namespaces are declared in the same file.
Show answer & explanation
Answer: (C) There is no limit on the number of levels while nesting namespaces.Explanation: 1. In C#, a namespace can contain other namespaces, giving nested namespaces.
2. The language does not impose any maximum depth on this nesting.
3. Using directives are convenient but not mandatory (you can use fully qualified names).
4. Inner namespaces may be declared in different files.
5. Hence the only correct statement is that there is no limit on nesting levels.
Q100.MediumAnswer under review
Which of the following statements are correct about namespaces in C#.NET? 1. Classes must belong to a namespace, whereas structures need not. 2. Every class, struct, enum, delegate and interface has to belong to some namespace or the other. 3. All elements of a namespace have to belong to one file. 4. If not mentioned, a namespace takes the name of the current project. 5. The namespace should be imported to be able to use the elements in it.
- 1, 3
- 2, 4, 5
- 3, 5
- 4 only
Show answer & explanation
Answer: (A) 1, 3Explanation: Statement 1 is correct: a class must be inside a namespace (or the global namespace is implied), while a struct need not be explicitly placed in one. Statement 3 is correct: all elements of a namespace must reside in a single file. Statement 2 is wrong because types can exist in the global namespace. Statement 4 is wrong because an unnamed namespace does not automatically take the project name. Statement 5 is wrong because elements can be used with a fully qualified name without importing. Hence only 1 and 3 are correct.