Part of my job is to interview developers for open position at my company. I’m surprised how many times people give wrong answers to questions related to Reference type vs. Value type. Bellow list of the questions some interviewers get incorrectly:
Question 1: Describe behavior of the code bellow:
1: static void Main(string[] args)
2: {
3: StringBuilder builder = null;
4: Foo(builder);
5: Console.WriteLine(builder.ToString());
6: }
7:
8: private static void Foo(StringBuilder builder)
9: {
10: builder = new StringBuilder("Interview");
11: }
Incorrect Answer 1: It will output “Interview”.
Correct Answer 1: NullReferenceException will be thrown on line 6. Because builder is null and cannot access ToString() method.
Question 2: What will the output of the code bellow?
1: static void Main(string[] args)
2: {
3: StringBuilder builder = null;
4: Console.WriteLine(Foo(builder));
5: }
6:
7: private static bool Foo(StringBuilder builder)
8: {
9: return builder is StringBuilder;
10: }
Incorrect Answer 2: True
Correct Answer 2: False
Often people are very eager to demonstrate their knowledge of the subject and they volunteer statements like this one:
Reference Types live on the heap and Value Types on the stack.
And this triggers a question like this one from me:
1: class A
2: {
3: B b = new B();
4:
5: class B
6: {
7: public int i;
8: }
9: }
Does it mean that in the code above b of type B will be stored on the heap but b‘s member i of type int is going to be stored on the stack?
This questions really confuses some people.
Correct statement is:
Reference Types and instance Value Types live on the heap and local Value Types live on the stack.
The purpose of this post is not to make fun but to educate.