Structs vs. Classes

Standard question which I would like to ask to the rejected candidates as one of the last questions to make them feel that they have not done very badly in their interview ;)

A struct is a user-defined value type created on the stack. It may contain both reference and value types. It’s used to represent a light weight object which consumes a small memory such as point, color and the like.

Unlike classes, the fields of a struct cannot be initialized. It will give an error saying ‘cannot have instance field initializers in structs’.

struct MyStruct
{
int x = 0; // error
int y = 0; // error
}


Structs cannot contain explicit parameter less constructors (default constructor), but we can have one or more constructors. C# compiler provides implicitly provides default constructor to initialize the default values for the members of a struct.

struct MyStruct
{
int i,j;

MyStruct() // error
{
//...
}

MyStruct(int i) //correct
{
this.i = i;
this.j = 0;
}

MyStruct(int i, int j) //correct
{
this.i = i;
this.j = j;
}
}


We can create struct objects as below, in the second case; we must initialize the struct fields before using it as it’s just a declaration.

1. MyStruct obj = new MyStruct();
2. MyStruct obj;


Below is the example showing Structs pass by value and Classes passed by reference

namespace ConsoleApplication1
{
class MyClass
{
public int iVariable;
}

struct MyStruct
{
public int iVariable;
}

class TestClass
{
public static void Method1(MyStruct s)
{
s.iVariable = 200;
}
public static void Method2(MyClass c)
{
c.iVariable = 200;
}

static void Main()
{
MyStruct objStruct = new MyStruct();
MyClass objClass = new MyClass();

objClass.iVariable = 100;
objStruct.iVariable = 100;

Console.Write(objClass.iVariable);
Console.Write(objStruct.iVariable);

//As it is a struct being passed as value
Method1(objStruct);

//As it is a class being passed as reference
Method2(objClass);
Console.Write(objStruct.iVariable);
Console.Write(objClass.iVariable);
Console.ReadLine();
}
}
}

Comments

Popular posts from this blog

Convert XElement to DataTable

Enable mouse scroll-wheel in VB6

C# code to Check IE Proxy Settings