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. Part 2

Aug 13 2012 12:00AM by Olga Medvedeva   

In my previous post I wrote about C# interview question about implementing binary tree data structure using structs. Today I’m going to share with you another interview question about classes and structs.
Lets imagine this code snippet is given to you:

namespace TestStructsAndClasses
{
  public class Structure
  {
    public int Number;
  }
  class Program
  {
    static void Main(string[] args)
    {
      IList list = new List{new Structure()};
      Console.WriteLine(list[0].Number);
      list[0].Number++;
      Console.WriteLine(list[0].Number);
    }
  }
}
And the first question is: What output will you get after running this code? And of cause most of interviewees give correct answer to this question. It returns:
0
1

The next question is: What output will you get after changing “class” keyword to “struct” and why?
And correct answer is: this code won’t be compiled and you will get this compilation error (line 13):

Cannot modify the return value of 'System.Collections.Generic.IList<TestStructsAndClasses.Structure>.this[int]' because it is not a variable


And the reason is still the same: struct is value type and class is reference type
So when you apply [] operator (indexer) to the list of structs, it will give you value of element of struct type. And in our code snippet the value returned by indexer is not assigned to any variable, it’s just area in memory without any reference to it. That’s why it is pointless to increment value in that memory because nobody can use that value anyway.
When you apply [] operator to a list of objects (reference type), you can increment value of Number field without any problem because the list still have reference to its elements.

Tags: C#, structs ans classes


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



Submit

Your Comment


Sign Up or Login to post a comment.

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