Practice mode C#

Given struct P { public int X; }, what does this print: P a = new P { X = 1 }; P b = a; b.X = 5; Console.WriteLine(a.X);?

Correct answer D. 1

Explanation

Because P is a struct, the assignment b = a copies all its fields into a separate value. Changing b.X affects only the copy, so a.X stays 1. If P were a class, both variables would refer to the same object and the program would print 5. This copy behaviour is the main practical difference between value and reference types.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.