Difference between a Struct and Class

Posted by Techie Cocktail | 6:40 PM | | 0 comments »

Below are some differences:

Class
a. Classes are reference types. When the object of the class gets created, it gets the memory allocation in the heap.
b. Classes support inheritance.
They can be inherited from a class or a struct.

c. Class supports instance field initialization.

class myClass
{
int a =10; //no error.
public void func( ) {..//do something...}
}

d. Class objects can be assigned null value as they are of reference types.
e. Classes are passed by reference as a parameter to a function.
f. Classes can have explicit parameterless constructors.

class myClass
{
int a = 10;
myClass()
{
}
}

g. All fields of the class need not be initialized in its constructor.
As seen in the below code, its alright to initialize any or all fields of a class.

class myClass
{
int a;
int b;

myClass()
{
a = 10;
}
}

Struct
a. Structs are value types. They get the memory allocation depending on where they are declared. If declared within the function, they are placed on stack and if they are member of a reference type then they get allocated in the heap.
b. Struct does not support inheritance, hence a struct members cannot be protected & protected internal access specifiers.
c. Struct does not support instance field initialization.

struct myStruct
{
int a = 10; //syntax error.
public void func( ) {...//do something...}
}


d. Struct variables cannot be assigned null as they are value types.
e. Structs are passed by Val as a parameter to function.
f. Structs cannot have explicit parameterless constructors.

struct myStruct
{
int a;
int b;

public MyStruct() //error
{
a = 10;
b = 20;
}
}

g. It is mandatory for the fields of the struct to be initialized in the struct constructor.

The below code gives error because 'b' is not initialized in the struct constructor and get the following error:
"Field 'namespace.class.myStruct.b' must be fully assigned before control is returned to the caller"

struct myStruct
{
int a;
int b;

public myStruct(int x)
{
a = 10;
}
}

0 comments