Monday, 9 July 2012

Third Class(Static Class,Method & Variables)

Third class material (Static class, method and variable)


class level variable

1. Static variable
2. Non static variable

class level static variable or non static variable cant access to other class...
it will access  in a class.
static variale intialize value automatically with 0(Zero).
like u can see on this Example.


using System;
class State
{
static int a;
  public static void Main()
{
Console.WriteLine("value is : "+a);
}
}


Output is 0;                                                              
                                                                                                        
                                                                                       

If you will declare non static variable in a NON static class and wanna access on static method error will occur...



using System;
class State
{
int a;
  public static void Main()
{
Console.WriteLine("value is : "+a);
}
}


Output Error...
                                                     


if you will declare non static variable without intializing in a Main method and wanna access in a same method also cant possible...



using System;
class State
{

  public static void Main()
{
int a;
Console.WriteLine("value is : "+a);
}
}


Output is use of unassigned local variable 'a'.
Explanation: because 'a' is not initialize here and in static variable 'a' automatically assigned because of static intialize value automatically with 0 (Zero).


we cant access non static variable in static function...



we cant access non static variable in static function


using Sysytem;
class state
{
public void roy()
{
int a=2;
}
public static void Main()
{
Console.WriteLine(a);
}
}
output : Error



But we can access static variables in non static function...



using System;
class State
{

public static int a=5;
public  void Disp()
{
Console.WriteLine("static var in non static func: "+a);
}
public static void Main()


{


State v1=new State();


v1.Disp();


Console.WriteLine("static var in static func: "+a);
}

}


THANKS TO ONLINE SUPPORT BY : HamaraSem

No comments:

Post a Comment