Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a static modifier on a constructor means?

Tags:

c#

I saw this kind of code at work:

class FooPlugin : IPlugin // IPlugin is a Microsoft CRM component, it has something special about it's execution
{
  static FooPlugin()
  {
     SomeObject.StaticFunction(); // The guy who wrote it said it's meaningful to this question but he can't remember why.
  }
}

Any idea what does a static modifier on a constructor mean and why in this case it is required?

like image 774
the_drow Avatar asked Jun 09 '10 20:06

the_drow


2 Answers

This is the static initialization of the class.

It would be called when you use a method, a field, a property or anything else of the class. In other word, it would be called the first time you use the class.

See static constructors on MSDN

You can also initialize static stuff here.

In your example it seems that whoever wrote that wanted to call SomeObject.StaticFunction() once before people will use FooPlugin, probably so it will be initialized before using FooPlugin.

Note that there is some performance hit when you use it and visual studio (using code analysis) can let you know that you better off initialize the static fields inline.

See CA1810: Initialize reference type static fields inline on MSDN

like image 155
brickner Avatar answered Sep 24 '22 00:09

brickner


It defines the static constructor for the object.

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.

Read more at MSDN - Static Constructors (C#)

like image 41
Justin Niessner Avatar answered Sep 25 '22 00:09

Justin Niessner