Is there a way to mark a function as only called/callable from a static constructor?

476 views Asked by At

I have quite a sizeable static constructor for one of my classes, and was wanting to refactor it to encapsulate various bits of the initialization within static functions.

One of the things this static constructor does a lot of is initialize the values of static readonly fields. However, when I try to move these parts into functions, obviously the compiler wont let me as these can only be set in the static constructor. This makes sense as it doesn't know that I only intend to call these functions from my static constructor.

Is there any way around this? e.g. is there some sort of attribute I can put on the functions to tell the compiler the functions are only to be called from the static constructor?

2

There are 2 answers

1
Jeremy Lakeman On BEST ANSWER

You can define local functions inside a static constructor;

public class MyClass {
    public static readonly int Value;
    
    static MyClass(){
        Value = Calc(1);
        
        return;
        
        int Calc(int a) => a;
    }
}

The C# compiler will turn those local functions into static methods, with unpronounceable names.

5
Nick Vu On

You can do it with static and private keywords

using System;

public class User {
    public static readonly string Name;
    
    static User(){
        Name = GetName();
    }
    
    //`private` function to only be called in static class itself
    private static string GetName() {
       return "Testing";
    }
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine(User.Name);
    }
}

A side note for this solution is that it can help you to prevent outsider functions' calls but cannot prevent being called internally by inner functions.