Matt Parkins Matt Parkins - 2 months ago 10
C# Question

Is a C# static method's variable initialised every time the method is called?

In the example below, will a new StringBuilder(255) be created every time the static Flog.Log() function is called, or will it only be created the first time the method is called?

public class Flog {

public static void Log(FlogType flogType, string msg, params System.Object[] p) {

StringBuilder sb = new StringBuilder(255);
sb.Length = 0;
sb.AppendFormat(msg, p);
Log(flogType, sb.ToString());
}
}


I realise I could work around this with a static member variable.

Edit: The purpose of the question is one of optimisation - in some languages initialisation of the StringBuilder sb variable will only occur once.

Answer

will a new StringBuilder(255) be created every time the static Flog.Log() function is called, or will it only be created the first time the method is called?

It will be created every time the static method called Log is called.

Only static members of a class are created once. So if sb would have been a static field of the class, the the StringBuilder would have been created only once.

Comments