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
1The 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 variableAnd 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.