C#.NET generics — What is the result of this code? public class Generic<T> { public T Field; } class Program { static void Main(string[] args) { Generic<string> g = new Generic<string>(); g.Field = "Hello"; Console.WriteLine(g.Field); } }

Difficulty: Easy

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 Generic.Assign g.Field = "Hello".Console.WriteLine(g.Field) prints Hello.


Verification / 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.

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion