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,
The static block executes at class loading time because it can contain only static data that binds with class. So, there is no dependency on object creation. But the non-static block(Instance block) executes when the object is created. Because it can have non-static members that bind with the object.
There is no concept with the name "static block" in C/C++. Java has it however, a "static block" is an initializer code block for a class which runs exactly once, before the first instance of a class is created.
Java 8Object Oriented ProgrammingProgramming. Instance variables are initialized using initialization blocks. However, the static initialization blocks can only initialize the static instance variables. These blocks are only executed once when the class is loaded.
The static block gets executed only once by JVM when the class is loaded into the memory by Java ClassLoader. The syntax to declare static block in Java program is as follows: Syntax: static { // Logic here or Java code. }
public class Application { static int attribute; static Application() { attribute = 5; } // removed }
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.
public class Application { static int attribute = 5; }
You just can write a static constructor block like this,
static Application(){ attribute=5; }
This is what I could think of.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With