Vadim's Weblog

Never stop learning.

Reference Type interview questions.

Posted by Vadim on June 30, 2008

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.

kick it on DotNetKicks.com

About these ads

3 Responses to “Reference Type interview questions.”

  1. Excellent post… thanks for the knowledge.

  2. DratesevabGeamb said

    rbyjzzkvbquoqmriwell, hi admin adn people nice forum indeed. how’s life? hope it’s introduce branch ;)

  3. Ramachandran said

    Where does this lives in?

    struct Foo
    {
    public int val;
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: