C# Basics – Static Methods – Part 14
This tutorial demonstrates how static functions work and how different are from non - static functions.
This tutorial demonstrates how static functions work and how different are from non - static functions.
We get to know how to use object arrays in C# programming language. We can create custom data type or object and use it in an array.
We explore how constructors work and for what we might need to use them.
We introduce classes in C# programming language in this tutorial.
We get to know how functions work in C# programming language.
We take a look at exception handling statements in C# programming language.
We introduce arrays in C# programming language. Arrays come in handy when there is a repetitive action needed upon values of the same data type.
We introduce data types like strings and chars in C# programming language
Let's talk about loops and what is their purpose.
Let's have a look at some of the logic operators in C# programming language.
Now what exactly are static methods and what is their purpose? Let’s first take a look at a static method Sqrt from the class Math. If we think about how did we use it in the past, we will realize, that we didn’t have to create a separate object in order to use this method. All we did was write Math.Sqrt, in case you skipped that chapter.
So how is that possible?
Some functions are so important, that it would be cumbersome to create an instance and use it that way. And besides all that, a value we’re trying to calculate is not connected to an object anyway. So the answer lies in static methods or functions.
Every method must be declared inside a class. And if we add a keyword static before the name of the function, we will be able to call that function like we can call Sqrt from Math class.
Here’s an example
1 2 3 4 5 6 7 8 | class MyClass { public static string Message() { string m = "You've called a static method."; return m; } } |
And if we want to call this function we’d write
1 | MessageBox.Show(MyClass.Message()); |
Comments