Getting Started with Adobe After Effects - Part 6: Motion Blur


Upload Image Close it
Select File

Browse by Tags · View All
C# 6
structs ans classes 2
Performance Wizard 2
Visual Studio 2010 2
case-insensitive 1
parse 1
enum 1
string 1
decoding 1
encoding 1

Archive · View All
January 2013 2
August 2012 2
July 2012 2
June 2012 2
April 2012 2
February 2013 1

Olga's SQL Server and .NET Blog

C#: Having fun with classes and structs

Aug 13 2012 12:00AM by Olga Medvedeva   

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 layout

And 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.

Tags: C#, structs ans classes


Olga Medvedeva
66 · 3% · 843
3
 
0
Lifesaver
 
 
0
Learned
 
0
Incorrect



Submit

Your Comment


Sign Up or Login to post a comment.

"C#: Having fun with classes and structs" rated 5 out of 5 by 3 readers
C#: Having fun with classes and structs , 5.0 out of 5 based on 3 ratings
    Copyright © Rivera Informatic Private Ltd Contact us      Privacy Policy      Terms of use      Report Abuse      Advertising      [ZULU1097]