What is the output of this C# code?
struct Point {
public int X;
public int Y;
}
class Program {
static void Main() {
Point p1 = new Point { X = 5, Y = 10 };
Point p2 = p1;
p2.X = 20;
System.Console.WriteLine(p1.X);
}
}Remember that structs are value types and copying creates a new copy.
Structs are value types in C#. Assigning p1 to p2 copies the values. Changing p2.X does not affect p1.X. So p1.X remains 5.
What is the output of this C# program?
struct Counter {
public int Count;
public void Increment() {
Count++;
}
}
class Program {
static void Main() {
Counter c = new Counter();
c.Increment();
System.Console.WriteLine(c.Count);
}
}Instance methods on structs operate on a copy of the struct.
When calling c.Increment(), the method operates on the instance c directly, incrementing Count to 1. So c.Count is 1.
What is the output of this C# code?
struct Number {
public int Value;
public void DoubleValue() {
Value *= 2;
}
}
class Program {
static void Main() {
Number n = new Number { Value = 10 };
object o = n;
((Number)o).DoubleValue();
System.Console.WriteLine(n.Value);
}
}Think about what happens when a struct is boxed.
Boxing creates a copy of the struct on the heap. Calling DoubleValue on the boxed copy involves unboxing to a stack copy, modifying that, but does not change the original n or the boxed copy. So n.Value remains 10.
What is the output of this C# program?
struct Data {
public int Number;
public string Text;
}
class Program {
static void Main() {
Data d = new Data();
System.Console.WriteLine($"{d.Number}, {d.Text ?? "null"}");
}
}Struct fields get default values when using the default constructor.
Struct fields are automatically initialized to their default values. Number is 0 and Text is null.
Consider this struct and code snippet. Which statement is true about the output?
struct ImmutablePoint {
public int X { get; init; }
public int Y { get; init; }
public ImmutablePoint(int x, int y) {
X = x;
Y = y;
}
public ImmutablePoint Move(int dx, int dy) {
return new ImmutablePoint(X + dx, Y + dy);
}
}
class Program {
static void Main() {
ImmutablePoint p = new ImmutablePoint(1, 2);
p.Move(3, 4);
System.Console.WriteLine($"{p.X}, {p.Y}");
}
}Think about how immutable structs behave and what the Move method returns.
The Move method returns a new ImmutablePoint with updated coordinates but does not change the original p. Since p is not reassigned, its values remain (1, 2).