Structure
It is also a user define similar to a class
that can contain variables methods as well as constructor in it.
Differences between classes and structure – (v. imp)
CLASS
|
STRUCTURE
|
1. It reference type.
|
1. it is a value type
|
2. Memory allocation is done on
managed heap, so gets the support of garbage collector follow
Automatic memory management.
|
2. Memory allocation is done on
stack which doesn’t have support of garbage collector for memory management,
but faster in access.
|
3. Using new operator to create
the object of class (reference type) is mandatory.
|
3. Using new operator to create
the object of structure (value type) is only optional.
|
4. Can contain variable
declaration as well as initialization.
|
4. Can contain variable
declaration but cannot be initialized.
|
5. variable of the class can be
initialized in three ways i.e. –
- at the time of declaration or
- under the constructor or
- using the object.
|
5. variable of the Structure
can be initialized only in two ways i.e. –
- under the constructor or
- using the object.
|
6. A class require a
constructor for creating the object of it , which need not be a default
constructor
|
6. A structure also requires a
constructor for creating its object without using new operator and in this
case it use default constructor only. So default constructor is mandatory for
structure and will be defined implicitly, that cannot be defined by
programmer explicitly...
|
7. If defined with Zero
constructor after compilation there will be one constructor and if defined
with ‘n’ constructors after compilation there will be ‘n’ constructors only
|
7. If define with Zero
constructor after compilation there will be One constructor and define with
‘n’ after compilation there will be ‘n+1’ constructor , because there is
implicit default constructor always
|
8. It supports both
Implementation and Interface inheritance.
|
8. It supports only Interface
Inheritance.
|
Note – All the predefine type which comes
under the value type category are implemented as structure under namespace.
Eg – int32, single, Boolean etc,
Whereas all predefined data types which comes
under refinance type category are implemented as Classes
Eg – string and object.
- Add a code file naming it as MyStruct.cs and
write the following :
using System;
namespace oopsProject
{
struct MyStruct
{
int x;
public MyStruct(int x)
{
this.x = x;
}
public void Display()
{
Console.WriteLine(" Method under
struct :" + x);
}
static void
{
MyStruct obj1; // using default
constructor
obj1.x = 50; obj1.Display();
MyStruct obj2 = new MyStruct(150);
obj2.Display();
Console.ReadLine();
}
}
}
|
Add one more code file naming it as
MyStruct2.cs and write the following:
using System;
namespace oopsProject
{
struct MyStruct2
{
static void
{
MyStruct obj = new MyStruct(300);
obj.Display();
Console.ReadLine();
}
}
}
|
0 Comments