- The main difference between static and non static method is Static method does not require an instance where non static method requires an instance to access them.
- Example code in C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
| class Calculator
{
//Static method
public static int sum(int a, int b)
{
return a + b;
}
//Non-Static methods
public int subtract(int a, int b)
{
return a - b;
}
public int Multilpy(int a, int b)
{
return a * b;
}
public int division(int a, int b)
{
return a / b;
}
}
|
- The sum method is declared as static, we can access the sum method without creating an instance of the Calculator class Code:
1
2
3
4
5
6
| int firstNumber =int.Parse(textBox1.Text);
int secondNumber = int.Parse(textBox2.Text);
int sum = Calculator.sum(firstNumber, secondNumber);
MessageBox.Show("Result form Static Method sum="+sum);
|
- Here,Method subtract is declared without the static keyword , that’s why is will act as non static, so if we want to access the subtract method of calculator class, then we have to create an instance of the calculator class first, then all the non-static methods will be accessible using the instance (i.e result1, result2) Code:
1
2
3
| Calculator result1 = new Calculator();
MessageBox.Show("Result form Non Static Method subtraction= " + result1.subtract(firstNumber, secondNumber));
|
C 6.0 and the .NET 4.6 Framework
No comments:
Post a Comment