Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static code blocks

Tags:

c#

.net

static

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,

like image 501
GETah Avatar asked Dec 10 '11 19:12

GETah


People also ask

What is static and non static block?

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.

What is static block in C++?

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.

What are static blocks and static initializers in Java?

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.

How do you declare a static block?

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. }


2 Answers

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;  } 
like image 107
parapura rajkumar Avatar answered Oct 21 '22 12:10

parapura rajkumar


You just can write a static constructor block like this,

static Application(){  attribute=5; } 

This is what I could think of.

like image 40
Ajai Avatar answered Oct 21 '22 12:10

Ajai