In general, the members of a class can be accessed by instance of that class when they are in public, but there comes a situation to access or call members of a class without an instance and this can be achieved by declaring them as static.
How to create a static class and access in our application?
Step 1: Create a Static class name as "StaticExample"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace KumarConsoleApplication
{
public static class StaticExample
{
public static int AddNum(int num1, int num2)
{
return num1 + num2;
}
public static int SubNum(int num1, int num2)
{
return num1 - num2;
}
}
}
Step 2: Add reference of the above class in our application.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KumarConsoleApplication;
namespace OurApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Addition " + StaticExample.AddNum(10, 20));
Console.WriteLine("Substraction " + StaticExample.SubNum(30, 10));
Console.Read();
}
}
}
Saturday, December 26, 2009
Static Class for Beginners
Step 3: Run the application and see the output in console application
The output is :
Addition 30
Substraction 20
Features:
Hope this article gave you some idea about static classes
Happy coding and learning
Subscribe to:
Post Comments (Atom)
0 Comments:
Post a Comment