Home > Net >  What is the use of static functions in C#? Can you please explain with real time example
What is the use of static functions in C#? Can you please explain with real time example

Time:11-26

I don't understand the real use of static functions. I don't when to use it. An explanation with real time example will be more useful.

CodePudding user response:

I'll start with some terminology. There are instance methods and static methods. Instance methods belong to an instance of a class or type. Static methods belong to the type, not to any particular instance.

As an example, you can't add to a List<int> without an instance of List<int>.

var list = new List<int>(); // creates an instance
list.Add(1);

When you call Add, you're adding to a specific instance of List<int>. You can have multiple instances and add different numbers to each one. It is an instance method.

Sometimes an instance is unnecessary. An example of this is the static Math class which has various static methods like Sqrt to get the square root of a number.

var squareRoot = Math.Sqrt(100);

Compare this to List<T>s Add method which changes the list, and its Count property which is different for each instance because each list can have a different number of items.

Sqrt does not change anything, and it doesn't depend on the state of the class. You could make Math non-static and make Sqrt an instance method, but what would be the point? Then you would have to write this code:

var math = new Math();
var squareRoot = math.Sqrt(100);

...but even if you created multiple instances of Math the result would always be the same, so what is the point of having instances of Math?

Methods that don't depend on the state of an instance or change the state of an instance are good candidates for static methods.

This is not the only use for static methods, but it's a common one. If you don't need an instance of a class for a method to work then the method can be static.


Static members can also change a class's static state, as in this example:

public class Counter
{
    private static int _count;

    public static void Increment()
    {
        _count  ;
    }

    public static int Count => _count;
}

There are no instances of Counter. There's only the type, and when you call Counter.Increment() you change the value of _count for any code that checks the Count property.

We can write static classes that modify their state like this, but there are downsides. If we decide that for some reason we want to count two different things, we can't with the class above. If we could create separate instances of Counter then we could increment them separately, just like adding different items to different instances of List<T>.

Static methods like this also introduce global state. That means any code throughout an application can potentially call a method and change some static state, and that potentially makes it harder to understand code.

Global state isn't automatically wrong. It might exactly what you want for some reason. But we tend to avoid it because of the way it makes it harder to tell how different parts of the code affect each other by changing and reading the same values.


There are no doubt more answers to the question, but this should cover the more common uses of static methods.

CodePudding user response:

I'm sure more knowledgeable persons will give better answers, but here is one anyway.

C# was born when Object-Oriented Programming (OOP) was very popular. So it was designed so that (almost) everything is an object. This means you can't really define a function out of the scope of a class (This is an approximation, but good enough for a first discussion on this matter). By the way, a "function" defined in a class is called a method.

As you know a class (in the general sense) is supposed, among other things, to associate together related data and functions. But sometimes, you might not have any meaningful data to associate with a function or set of functions. You might just be interested in the function (or a set of functions).

How to do that? Simply by having static methods defined in a static class.

The classic example is given by the C# Programming Guide

A static class can be used as a convenient container for sets of methods that just operate on input parameters and do not have to get or set any internal instance fields. For example, in the .NET Class Library, the static System.Math class contains methods that perform mathematical operations, without any requirement to store or retrieve data that is unique to a particular instance of the Math class. That is, you apply the members of the class by specifying the class name and the method name[...].

Here is an example of the use of three static methods, Abs, Floor and Round, defined in the static class Math:

var number = -5.263;  
var absoluteValue = Math.Abs(number);  // 5.263
var floorNumber = Math.Floor(number);  // -6
var roundedNumber = Math.Round(Math.Abs(number)); // 5

But C# is a multi-paradigm language, and besides OOP, functional programming (FP) is partly supported. In FP, functions are the basic building blocks of code. They have no data associated with them. They can take inputs (arguments) and can produce an output (return value). They should not have side effects (this is called purity). To help support these principles, many features were added to C#. One of them, extensions methods, are based on static methods.

Here is a concrete example: the most obvious part of C# that is inspired by functional programming is Linq. Linq could not exist as it is without extensions methods, which are static.

See the C# Programming Guide on extension methods.

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type. For client code written in C#, F# and Visual Basic, there's no apparent difference between calling an extension method and the methods defined in a type. The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections.IEnumerable and System.Collections.Generic.IEnumerable types.

Here is a Linq example:

var bestMovies = movies
    .Where(m => m.Rating > 8)
    .OrderByDescending(m => m.Rating);

Here Where and OrderByDescending are static methods.

So static methods are a very important component of C#, and are heavily used.

Static methods can be used when you only need a simple helper method that does not depend on associated data. They allow simple constructs that can quickly and easily help with redundant code. They are a valuable tool to use in the right circumstances.

Here is an example of a pair of static methods (one is an extension method). You can run it in Linqpad.

void Main()
{
    var hello = "Hello";
    Console.WriteLine(hello.Decorate("@")); // ====== @HELLO ======
    
    var result = Utils.MyMathFunction(6); 
    Console.WriteLine(result); // 42
}

// You can define other methods, fields, classes and namespaces here
public static class Utils
{
    public static string Decorate(this string text, string decoration)
    {
        return $"====== {decoration}{text.Trim().ToUpper()} ======";
    }
    
    public static double MyMathFunction(double number)
    {
        return (number   3) * number - 12;
    }
}
  • Related