Saturday 9 January 2016

What is static function in c#

When we mark any function or variable as static in c# class it becomes shared for all the object.
and a static function or static variables does not comes into memory block that is created by
 new classname(). thats why it can not be called by object dot, it can be called by class name dot static variable or function name.

Class ABC
{
 static void Display()
 {
  Console.WriteLine("Hello");
 }
  static void main()
  {
   ABC.Display();
   }
}

*a static variable for a c# class available into global memory and shared for all object.
* in a static function or any function we can not declare any static variable , we can only declare a static variable at class level.
* inside a static function we can not access any member variable or function directly but by creating the object of class we can access that .
* static function is not supports inheritance.
* by default when we create any static function it becomes sealed.

* memory for any function in c# allocated into stack because if we think that for a function memory should be in heap, then think what happen if we declare 1000 object for a class, it create memory block in heap for each object and there are 1000 objects that means it will be in 1000 places which technically not good.that why it is allocated into stack and that location is shared for each object.

we can prove that a functions memory allocated into stack not in heap:

in c++

Class ABC
{
int eid;
 public:
         void assign()
            {
               cout << "hello world";
            }
public:
         void assignEid()
            {
               eid=201;
               cout << "hello world";
            }
}
now without object creation it will be called

void main()
{
 Abc *abc;
abc->assign();//will wok, because it is available in stack.
abc->assignEid();//will not wok gives error, because eid variable is class level variable and its memory is in heap so before using it we must be allocate for that.

Abc *abc1=new ABC();
abc1->assign();//will wok
abc1->assignEid();//will wok, because now we have created the object and now it is available in memory block.
}


No comments:

Post a Comment

Contact Us:

Email:

Vinodkumar434@gmail.com,
vinodtechnosoft@gmail.com

Skype Name:

vinodtechnosoft