yahoo invisible

Thursday, March 12, 2009

Differences between structs and classes

1. structs are value types and classes are reference types.
2. structs created in stack, classes are allocated in the heap.
3. For instantiation classes need new keyword, but structs don't need.
4. classes support inheritance but strcuts don't.
5. classes can have explicit constructors without parameters. but structs need parameters for explicit constructors.
6. No initialized fields in structs. but classes can have initializers.
ex: class A
{
int a=10; //ok
}

struct A
{
int a=10; //error
}
7. When passing a class to a method, it is passed by reference. When passing a struct to a method, it's passed by value instead of as a reference.
8. You will always be dealing with reference to an object ( instance ) of a class. But you will not be dealing with references to an instance of a struct ( but dealing directly with them ).
9. Classes permits to declare a destructor. But struct doesn't.
10. It is not mandatory to initialize all Fields inside the constructor of a class.
But all the Fields of a struct must be fully initialized inside the constructor.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home