There are a lot of good articles and posts about classes vs structs, and today I don’t have any intention to describe similarity and difference between them.
I just want to share with you some interesting (in my opinion) interview questions on this subject me or my friends met with.
Implementing Binary Tree or Recursive Create Problem
One friend of mine was asked to write a class to implement binary tree data structure. I’m pretty sure that it won’t be a problem for all of you to write this class. So we can implement it something like that:
public class Node
{
public Node Left { get; set; }
public Node Right { get; set; }
public int Value { get; set; }
}
And the next question was:
Can we just change “class” keyword to “struct” to get the same behaviour? Think a bit before further reading. Of cause the answer is NO. The code below won’t be even compiled:
namespace TestStructsAndClasses
{
public struct Node
{
public Node Left { get; set; }
public Node Right { get; set; }
public int Value { get; set; }
}
class Program
{
static void Main(string[] args)
{
}
}
}
After compiling this snippet you will get this error:
Struct member 'TestStructsAndClasses.Node.Left' of type 'TestStructsAndClasses.Node' causes a cycle in the struct layoutAnd the reason is that
struct is value type and class is reference type.
Structs have to be initialized when they are allocated with some default values. So to create instance of Node default constructors for left and right children (which are also of Node type) will be called first. And it will lead to recursive create problem, that cannot work (stack overflow problem).
However, reference types will contain only memory reference, not the actual data structure, and this will work fine for classes.
In my next post I will write about another interview question about structs and classes.