Going from Java
to C#
I have the following question:
In java I could do the following:
public class Application {
static int attribute;
static {
attribute = 5;
}
// ... rest of code
}
I know I can initialize this from the constructor but this does not fit my needs (I want to initialize and call some utility functions without create the object). Does C# support this? If yes, how can I get this done?
Thanks in advance,
I find something else useful. If your variable needs more than one expressions/statements to initialize, use this!
This approach is not limited on classes.
You can use the C# equivalent static constructors. Please don't confuse it with a regular constructor. A regular constructor doesn't have a
static
modifier in front of it.I am assuming your
//... rest of the code
need to be also run once. If you don't have such code you can just simply do this.-A static constructor doesn't have any parameter.
-A static class can contain only one static constructor.
-A static constructor executes first when we run the program.
Example:
Output:
This is static constructor.
This is main function.
You just can write a static constructor block like this,
This is what I could think of.
In your particular scenario, you could do the following:
UPDATE:
It sounds like you want to call a static method. You can do that as follows: