C#.NET — Given the struct below, which is the correct way to assign values to its fields? struct Emp { public string name; public int age; public Single sal; } Emp e = new Emp();

C# Programming Structures Difficulty: Easy
Choose an option
  • A
    e.name = 'Amol'; e.age = 25; e.sal = 5500;
  • B
    With e { .name = 'Amol'; .age = 25; .sal = 5500; }
  • C
    With emp e { .name = 'Amol'; .age = 25; .sal = 5500; }
  • D
    e -> name = 'Amol'; e -> age = 25; e -> sal = 5500;
  • E
    name = 'Amol'; age = 25; sal = 5500;

Answer

Correct Answer: e.name = 'Amol'; e.age = 25; e.sal = 5500;

Explanation

Introduction / Context:The question checks familiarity with C# field assignment syntax versus constructs from other languages (VB, C/C++).

Given Data / Assumptions:

  • A public struct Emp exposes three public fields.
  • We have an initialized variable e = new Emp().

Concept / Approach:In C#, field assignment uses the dot operator on the variable: e.name = "Amol"; e.age = 25; e.sal = 5500; Features like With blocks are from VB, and the arrow operator is from C/C++ pointer syntax, neither of which applies to C# field assignment.

Step-by-Step Solution:

Use e.name, e.age, e.sal with standard assignment.Avoid VB-style With or C/C++ -> syntax; they are invalid in C#.

Verification / Alternative check:Compile only the candidate from Option A; it succeeds. The others produce syntax errors in C#.

Why Other Options Are Wrong:

  • B/C: VB-like With blocks are not part of C#.
  • D: The arrow operator dereferences pointers in C/C++; not valid for managed struct variables in C#.
  • E: Missing the variable qualifier (e); invalid context for assignments.

Common Pitfalls:Bringing habits from other languages into C# syntax.

Final Answer:e.name = 'Amol'; e.age = 25; e.sal = 5500;

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