All jobs / Backend developer / Backend Languages
Backend developer interview question · 0–1 years
You pass a class instance and a struct to a method and both are modified inside. What does the caller see?
The strongest answer
The class change is visible because the reference points at the same object; the struct was copied, so the caller's copy is untouched unless it was passed with ref
Why it works
Exactly. Reference types share the object, value types are copied.
What a good answer covers
- class = reference type, struct = value type.
- The reference is copied; the object is not.
- ref / out change the parameter binding itself.
- Mutable structs are a known source of surprises.
Answers that fall short
- Close, but not the strongest: Both are visible; C# passes everything by reference
Reference types share; value types do not. - Weak: Neither is visible; C# copies every argument
The reference is copied, but it still points at the same object. - Red flag: It depends on whether the method is static
Static has nothing to do with it.
Who gets asked this
More Backend Languages questions
- When would you choose a tuple over a list?
- What is the most common cause of a NullReferenceException in a new codebase?
- What is the difference between == and is?
- When do you use an array rather than a List<T>?
- You want a value from a dict, or a default if the key is missing, without raising. What do you use?
- You remove items from a List<T> inside a foreach over it and get an exception. Why?
- if items: — what exactly is being tested?
- When is var a good idea?