Saturday, July 5, 2014

Class vs Structure

Structures:
These are also user defined types similar to a class under which you can define all the members what we can define under class.

class
structure
it is reference type
it is value type
it wasn’t faster in access than a structure
these are faster in access
to create a object we required to use a new operator which is mandatory
we can create the object of it without using new operator also
get its memory allocated on managed heap which provides automatic memory management with the help of garbage collector
Gets it memory allocated on stack which does not provides dynamic memory allocation. garbage collector can’t come into picture
it supports inheritance
it does not support inheritance
a programmer can define a default constructor or will be defined by the compiler if  no constructor exists in the class
a default constructor can only be defined by the compiler a programmer can never do it.
can contains variables declared and initialized
can contain variable declaration but can’t be initialized should be initialized either using object of the structure or constructor of the structure.




Structure Example

namespaceConsoleApplication2
{
    structmystruct
    {
        intx;
        publicmystruct(int x)
        {
            this.x = x;
        }
        publicvoid Test()
        {
            Console.WriteLine("Method" + x);
        }
        publicstatic voidMain()
        {
            mystructm1;
            m1.x = 100;
            m1.Test();
            mystructm2 = new mystruct(200);
            m2.Test();
            Console.ReadKey();
        }
    }
}


Output:
Method 100
Method 200

No comments:

Post a Comment

Thank you for visiting my blog

Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...