static method
In this chapter you will learn:
- How to create static methods
- Return value from static method
- How to intialize value with static methods
Create static methods
A static method can directly call only other static methods, but not an instance method of its class. A static method does not have a this reference.
using System; //from ja v a2 s . c o m
class StaticDemo {
// a static variable
public static int val = 100;
// a static method
public static int valDiv2() {
return val/2;
}
}
class MainClass {
public static void Main() {
Console.WriteLine("Initial value of StaticDemo.val is "
+ StaticDemo.val);
StaticDemo.val = 8;
Console.WriteLine("StaticDemo.val is " + StaticDemo.val);
Console.WriteLine("StaticDemo.valDiv2(): " +
StaticDemo.valDiv2());
}
}
The code above generates the following result.
Return value from static method
The following code returns the value from a static variable from static function.
using System;/* j av a2s. co m*/
class MyClass {
public MyClass()
{
instanceCount++;
}
public static int GetInstanceCount()
{
return(instanceCount);
}
static int instanceCount = 0;
}
class MainClass
{
public static void Main()
{
MyClass my = new MyClass();
Console.WriteLine(MyClass.GetInstanceCount());
}
}
The code above generates the following result.
Initialize value with static methods
using System;//from j a va 2 s . c om
public class MyClass
{
private static int InitX()
{
Console.WriteLine( "MyClass.InitX()" );
return 1;
}
private static int InitY()
{
Console.WriteLine( "MyClass.InitY()" );
return 2;
}
private static int InitA()
{
Console.WriteLine( "MyClass.InitA()" );
return 3;
}
private static int InitB()
{
Console.WriteLine( "MyClass.InitB()" );
return 4;
}
private int y = InitY();
private int x = InitX();
private static int a = InitA();
private static int b = InitB();
}
public class MainClass
{
static void Main()
{
MyClass a = new MyClass();
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- How to return value from a function
- How to return an object value from a method
- How to return a value of an array from a method
Home » C# Tutorial » Class