C#.NET generics — What is the result of this code?
public class Generic
{
public T Field;
}
class Program
{
static void Main(string[] args)
{
Generic g = new Generic();
g.Field = "Hello";
Console.WriteLine(g.Field);
}
}
-
AIt will print string 'Hello' on the console.
-
BName Generic cannot be used as a class name because it's a keyword.
-
CCompiler will give an error.
-
DMember Field of class Generic is not accessible directly.
-
ENone of the above.
Answer
Correct Answer: It will print string 'Hello' on the console.
Explanation
Introduction / Context:This checks basic usage of a generic class with a type parameter T, instantiation with a concrete type, field assignment, and console output.
Given Data / Assumptions:
- Generic
has a public field Field of type T. - Main creates Generic
, assigns "Hello", and writes it out.
Concept / Approach:When closing a generic type with T = string, the field becomes of type string. Because Field is public, it is directly accessible from outside the class. The identifier Generic is not a C# keyword; it is a perfectly legal class name (though not recommended for clarity).
Step-by-Step Solution:
Instantiate g as GenericVerification / Alternative check:Change T to int and assign 42; Console.WriteLine prints 42. Compile and run to confirm no errors.
Why Other Options Are Wrong:
- B: generic is not a reserved C# keyword; Generic is allowed as an identifier.
- C: There is no compile-time error.
- D: Field is public, hence directly accessible.
- E: A is correct.
Common Pitfalls:Naming classes with overly generic names can reduce readability, but it is syntactically valid.
Final Answer:It will print string 'Hello' on the console.