Showing posts with label Creating an instance. Show all posts
Showing posts with label Creating an instance. Show all posts

Creating and Killing an instance in c sharp

Creating an instance of a class



  • Every member ( here in above example variable x) of a class if it is non-static can access from the main method only by using Instance of the class(p is the instance of a class Program).
  • A variable of a class is a Copy of class that is not Initialized whereas the Instance of the class is  copy of a class that is Initialized by using new keyword.



How to kill Instance of a class ?

  • we can kill the Instance of a class by assigning null to it and once null is assigned to an Instance the Instance cannot access the Object memory that is allocated to it and Object memory is marked as unused. After assigning null to an instance we cannot call any member using that instance because the Instance is again treated like a variable of a class.


















Creating an Instance in c sharp

Syntax for creating the Instance

                            <class ><instance> = new <class> ([< list of value>])
Examples : 
                  Program P= new program ();  // P is instance of the class

                  Program P;                               // P is variable of the class.
                  P = new  Program ();               // P is instance of the class.

Note: A variable of a class is a copy of a class that is not initialized where the instance of a class is a copy of a class that is initialized by using new keyword.

  • The instance of a class can be created under the same class or under other classes also whereas if we want to create the instance in the same class it can be created under any static block of the class, but generally we create instance under main method of the class because main is also a static method and more over the entry point of the program.