Both Classes
and Structs are constructs in C#
which are used to create custom complex types by encapsulating a set of basic
types and logic. Though they are used to create custom types there are some
underlying differences between the two, the following are some of the
differences between classes and structs.
Classes are Reference type, when an
instance is created from the class only a pointer is created, whenever a copy
of the instance is made both the original instance and the copied instance
share the same memory reference.
Structs
are Value Types, when an instance is created a separate memory reference is
created and whenever a copy is made from the instance a separate memory
reference is created for the copy.
Classes
are used to create more complex types which are used extensively in object
oriented programming.
Structs are used to create simple types which do not have complex operational logic to be added.
Structs are used to create simple types which do not have complex operational logic to be added.
Since Classes
are Reference Type, their object creation and destruction are managed using
heaps.
Since Structs
are Value Type, their object creation and destruction are managed using stacks.
Classes
can have empty constructors, but we need to define the constructor if we need
one.
Structs
have a built-in default constructor, if we need to add additional constructors
we need to make sure that the constructor initializes all the member variables
of the struct.
Classes
can have a destructor.
Structs cannot have a destructor.
Structs cannot have a destructor.
Class Example
class Calculator
class Calculator
{
// Private Members
private int
_inputNumber1;
private int
_inputNumber2;
//
// Methods
public int Add(int nNumber1, int
nNumber2)
{
return nNumber1 + nNumber2;
}
//
public int Subract(int nNumber1, int
nNumber2)
{
return nNumber1 - nNumber2;
}
//
public int Multiply(int nNumber1, int
nNumber2)
{
return nNumber1 * nNumber2;
}
//
public int Divide(int nNumber1, int
nNumber2)
{
return nNumber1 / nNumber2;
}
}
Structs Example
struct SEmployee
{
public int id;
public string Name;
//
public SEmployee(int
nid, string sName)
{
id = nid;
Name = sName;
}
}
No comments:
Post a Comment