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();
-
Ae.name = 'Amol'; e.age = 25; e.sal = 5500;
-
BWith e { .name = 'Amol'; .age = 25; .sal = 5500; }
-
CWith emp e { .name = 'Amol'; .age = 25; .sal = 5500; }
-
De -> name = 'Amol'; e -> age = 25; e -> sal = 5500;
-
Ename = '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:
Usee.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;