A
class in C sharp declared with static keyword is a C# static class. The static
class prevents the object creation and can be used directly without creating any
instance of class. A class that is not a static class is used after creating
its object with new keyword. But the class that is static is used directly
without creating its object.
How to create static class in c#?
In order to create static
class in C sharp, you need to put static keyword before the name of the class
as follow:
static class calculation
{
}
1. The static class can contain only static members.
2. The static class cannot be instantiated.
3. The static class is a sealed class so you cannot inherit
and override its members.
Static Member
A static method, field, property,
or event is callable on a class even when no instance of the class has been
created. If any instances of the class are created, they cannot be used to
access the static member. Only one copy of static fields and events exists, and
static methods and properties can only access static fields and static events.
Static members are often used to represent data or calculations that do not
change in response to object state.
Example
using System;
namespace StaticKeywordConsoleApplication
{
static class calculation
{
public static int add(int num1, int
num2)
{
return num1 + num2;
}
}
class Program
{
static void Main(string[] args)
{
int result;
result = calculation.add(6,
22);
Console.WriteLine("Addition = "
+ result);
}
}
}
Output:-
Addition = 28
In
this example, I’ve created a static class calculation with a static member
function add() who add two numbers
and return the value. In class Program, add()
is called directly with the calculation class name and dot operator, there is no need of object.
No comments:
Post a Comment