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?
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
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#)
I can't say why it's required in your particular case, but the motivation for a static constructor is usually one of these:
All instances of the class need
access to the same instance of an object, or
Initialization of some external object
is a prerequisite for all instances
of the class (seems like the case in your example) or
Initialization of some data structure or service takes takes too much time to do repeatedly (a variation of the first case).
Here's a simpler example of when a static constructor is useful. The following class has some static fields. The first can be initialized inline with its declaration, but the second one can't. Static constructor to the rescue. The key guarantee it provides is that no part of the class can be accessed before the initialization code runs.
class NeedsStaticConstructor
{
private static Size s_size = new Size(100, 100); // can be done inline
private static StringFormat s_format; // more complex initialization needs code
static NeedsStaticConstructor()
{
s_stateTextFormat = new StringFormat(StringFormatFlags.NoWrap);
s_stateTextFormat.Alignment = StringAlignment.Near;
s_stateTextFormat.LineAlignment = StringAlignment.Far;
}
}
A static constructor is used to initialize class-wide (i.e. static) members, as opposed to instance members.
Just to add to the above answers, static constructor (or static blocks as in the case of Java) get executed only once when the class is first loaded in to memory. The objective is to initialize static fields, which otherwise would assume the respective default value of the data type. Sometimes I use static constructors to build an object model that I want to use throughout the life time of the application.
Related
There are two ways to initialize members in a C# class, via constructor:
class MyClass{
private int Member;
public MyClass()
{
Member = 0;
}
}
or through member initialization:
class MyClass
{
private int Member = 0;
}
My question: Are there problems / benefits of one approach vs. another?
From what I can see, it's a wash if you only have a default constructor. If you have multiple constructors, member initialization is preferable for those members that are set to the same value by all constructors.
As far as the execution of your program is concerned, the two examples you gave are identical. Member initialization expressions in your class execute "as-if" they were part of your constructor (IL is identical either way), so it is entirely a matter of style.
The inline initializers are usually more convenient, and are what you are likely to see if you look through existing C# code. Mostly, the initializers in the constructor body are only used when they are necessary, e.g.:
If you need to compute the initial value using data only known at runtime, e.g. constructor parameters
If you need (for some reason) to initialize values in a different order than they appear in the code.
If you need to conditionally initialize certain fields
In those cases, your only option is to have a constructor.
There is one case where the member initialize is explicitly preferred over the constructor body: when the member is static. FxCop, for example, will produce a CA1810 or CA2207 if you include a static constructor that initializes static fields. In those cases, there is a difference between the inline and constructor body styles, though it is rather technical (see the CA1810 explanation for the gory details.) The recommendation here is to avoid even having a constructor: if needed, initialize your static fields with a static member function, called inline:
// Don't do this:
public static class Foo
{
private static int i;
static Foo()
{
i = somecomputedvalue;
}
}
// Do this:
public static class Foo
{
private static int i = initializeI();
private static int initializeI()
{
return somecomputedvalue;
}
}
In this specific example, there is no difference. Initialization in the constructor body is mainly so you can dynamically set the value based on constructor parameters and/or other custom logic. In this case the compiler will produce the first case I believe even if the original source is the second.
Otherwise it's a case of style and/or repetition.
Personally I prefer to initialize in the constructor body unless I have multiple constructors and having constructors call other constructors isn't appropriate.
I use Resharper tool in visual studio
Consider a very simple class written below.
class Test()
{
//constructors do not have any return type.
Test()
{
System.Console.WriteLine("Hello World!");
}
static Test()
{
System.Console.WriteLine("Hello World in Static constructors");
}
public void A()
{
System.Console.WriteLine("A simple function in a class");
}
}
class Program
{
static void Main(string[] args)
{
var asa = new Test(); //Implicitly Typed local variables.
asa.A();
}
}
Using var (the compiler has to infer the type of the variable from the expression on
the right side of the initialization statement).
I have some clarification questions and they are below.
Extra burden to compiler?
How many constructors a class can have?
Why is static constructor called first ? (I checked out by putting a breakpoint?)
Why not Test asa = new Test(); is not preferred by Resharper?
Is it really a good idea to use Resharper first as a beginner? (Myself being a newbie to C and .net programming!)
Thanks in Advance.
Any extra burden to the compiler is basically irrelevant - it should not be part of your decision about whether or not to use var. As noted in comments, it may well require slightly more work for the compiler when you use explicitly declared variable... but again, it's not going to be significant.
A class can have any number of constructors... although it will become unwieldy pretty quickly.
The static constructor will be called once, before the first use of the class (whether that's via a static method or a constructor call). Read the C# spec for more details - section 10.12 of the C# 5 spec includes:
The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:
An instance of the class type is created.
Any of the static members of the class type are referenced.
You can configure ReSharper to suggest alternatives, or treat them as warnings, etc. Make it work however you think it should, on this front.
Negligible if any. The return type would otherwise be compile checked. You shouldn't base decisions on it, anyhow.
As many as you want as long as they are distinguishable.
Static constructors are part of the type definition. They are invoked when the type is first referenced.
What message are you receiving? R# is configurable.
Edit:
(You can't beat the Skeet).
yes, there is some extra work required, but it is possible to use var keyword only in those situations in which it is pretty easy for the compiler to infer the type.
There is no constraint on number of constructors, but there are some rules constructors have to follow (ie: it needs to be clear for the compiler which constructor to call)
I can't telly you why - let's say this is just one of the rules. The interesting thing is beforefieldinit (http://stackoverflow.com/questions/610818/what-does-beforefieldinit-flag-do, http://csharpindepth.com/Articles/General/Beforefieldinit.aspx)
I personally think that in this case it is just a matter of taste. Some people tend to use var as much as they can, while others do the opposite. I try to use when:
I am working with collections (or it takes a lot of text to tell the compiler about the type: instead of:
Dictionary<<OneOfMyClasses, OtherClasss> dictionary = new Dictionary<OneOfMyClasses, OtherClass>();
I tend to use var:
var dictionary = new Dictionary<OneOfMyClasses, OtherClass>();
Please mind that it doesn't affect readability of the code (i.e. it is still easy to understand what is actually happening).
Thanks Everyone. After some time spent on research, I would like to add some points that might help someone.
Disclaimer:(The following points were derived(or even pasted) from codeproject and other such websites.
1) Every single class can have only one static constructor.
Reason: Static constructor must be parameter-less or simply, constructor overloading is not permitted. And since CLR is going to call this constructor, we do not have any control over passing values to this function. As we directly can’t call static constructors, there is no point in having multiple static constructors.
class Test
{
static Test() {...}
static Test(int a) {...} //would throw error as "Static constructor must be parameter less"
}
2) Static constructor should be declared without any access specifier.
Reason: Again CLR is going to call the static constructor not any object of the class. Hence, we donot need any access-specifier.
3) Static constructor must operate only on static variables of that class
Reason: Non-static members are specific to the object instance. There is no point in modifying a variable whose value depend/bind to their specific object instance.
4) Why should I use a static constructor ? Give me one good example
Reason: You can use a static constructor, say when you want to log the operations that you are going to perform using that class. MSDN says "A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file".
5) When exactly a static constructor is called ?
Answer: The user has no control on when the static constructor is executed in the program.
.As others and MSDN points out "A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced."
6)When using base class and derived class in C#, when a new instance of a derived class is created, does base class constructor is called first or derived class constructor is called first?
Answer: The base class constructor is called first and then the derived class constructor.
Code example
class DerivedClass : ParentClass
{
public DerivedClass()
{
Console.WriteLine("Derived class constructor!");
}
}
class ParentClass
{
public ParentClass()
{
System.Console.WriteLine("Parent class constructor!");
}
}
class Program
{
static void Main(string[] args)
{
var a = new DerivedClass(); //Implicitly Typed local variables.
}
}
7) Why in your above examples, both constructors have public access specifier ? What if I specify private or do-not specify access specifier at all?
Answer: When you do not specify access specifier(this case, the constructor automatically becomes private) or whenever you use a private access specifier, the class cannot be instantiated. Whenever a class contain one or more private constructors it strictly (!) cannot be instantiated. This type of constructors are called special instance constructor and is generally used when all the members of a class are static methods. (Probably the Math class should be a good example.)
**8)Bonus question on inheritance. Does a class inherit from two different classes ?
Strictly No. C# supports only direct inheritance and ofcourse you can use interfaces.For example,
interface Test
{
void abc();
}
class DerivedClass : ParentClass, Test //Test should not be a class. It can be a interface.
{
public DerivedClass()
{
Console.WriteLine("Derived class constructor!");
}
public void abc()
{
//should be publicly defined!
//non public method could not implement from interface Test
}
}
class ParentClass
{
public ParentClass()
{
System.Console.WriteLine("Parent class constructor!");
}
}
I was researching on the singleton pattern for C# I found this example from the msdn website.
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
Because the Singleton instance is
referenced by a private static member
variable, the instantiation does not
occur until the class is first
referenced by a call to the Instance
property. This solution therefore
implements a form of the lazy
instantiation property, as in the
Design Patterns form of Singleton.
I am not pretty sure when will the memory will get allocated to
private static readonly Singleton instance
1)Will it happen when the Instance property is called or even before it?
2) I need to force the class to create a new memory sometimes to purge its content. Is it safe to do so using set ?
set
{
instance = null;
}
In the example code you provided, the singleton instance will be created at the time of the first access to the class. This means for your example at the time when Instance gets called for the first time.
More insight you can find in Jon Skeet's article Implementing the Singleton Pattern in C#, see Method 4.
Basically, in order to achieve truly lazy behaviour something like
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
static Singleton(){}
private Singleton(){}
public static Singleton Instance
{
get { return instance; }
}
}
is enough.
(But anyway, the full and much better overview can be found in the mentioned article.)
EDIT
Actually, as it follows from the mentioned article, the instance is not guaranteed to be created at the first access, because of BeforeFiledInit mark. You need to add an empty static constructor, this way it's guaranteed to be lazy. Otherwise the instance will get created at some unspecified time between the program start and first access. (.NET runtime 2.0 is known to have more eager strategy, so you'll probably not get the lazy behaviour.)
Quoting from the said article:
The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler [...] marks all types which don't have a static constructor [...] as beforefieldinit.
EDIT 2
If you want the singleton object to clean up, you should include this functionality into the class Singleton itself.
Removing the property value will effectively make your class not a singleton any more! Imagine that someone accesses the singleton and gets the singleton instance. After that you set the property to null. The existing object of the Singleton class won't disappear, because there's still a reference to it! So the next time you access the Instance property, yet another instance of the Singleton class would be created. So you lost two things: your object is not a singleton any more (because you have got 2 instances existing at the same time), and the memory hasn't been cleared either.
The singleton instance will be loaded into memory when the class itself is loaded which is when the method which could call it begins execution. The actual line that calls into the class doesn't have to actually execute. This is a very slight distinction but can create hard-to-debug problems when a static constructor or static field initializer can throw an error (which you don't have here).
This is fixed in .NET 4 with the new Lazy<T> implementation.
http://msmvps.com/blogs/jon_skeet/archive/2010/01/26/type-initialization-changes-in-net-4-0.aspx
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
http://csharpindepth.com/Articles/General/Singleton.aspx
The C# specification says:
10.5.5.1 Static field initialization
The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (§10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor. Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.
i.e. They only guarantee you get is that it happens before the instance field is read. But it can happen much earlier.
If you want to guarantee that it that it doesn't run earlier than the first access of the property you'll need to add a static constructor(potentially empty):
The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:
· An instance of the class type is created.
· Any of the static members of the class type are referenced.
As a side node: I noticed that when using DI it is rarely necessary to use an actual singleton. Simply telling DI that it should create a single instance is enough. This is very nice if you decide at a later point that you want more than one instance, since then the fact that it's a singleton isn't baked into all the code using it.
It says in the quote you posted:
the instantiation does not occur until
the class is first referenced by a
call to the Instance property
So... Whenever you call .Instance, or at some point before.
Static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called.
Read more on MSDN
What are the differences between the two? I've only used one kind of constructor and I believe it's the static constructor. Only familiar with C++ and Java.
Static constructor is called the first time your class is referenced i.e.
MyClass.SomeStaticMethod()
Instance constructor is called every time you do 'MyClass dummy = new MyClass()' i.e. create instance of the class
Semantically first is used when you want to ensure that some static state is initialized before it is accessed, the other is used to initialize instance members.
Static constructors allow you to initialize static variables in a class, or do other things needed to do in a class after it's first referenced in your code. They are called only once each time your program runs.
Static constructors are declared with this syntax, and can't be overloaded or have any parameters because they run when your class is referenced by its name:
static MyClass()
{
}
Instance constructors are the ones that are called whenever you create new objects (instances of classes). They're also the ones you normally use in Java and most other object-oriented languages.
You use these to give your new objects their initial state. These can be overloaded, and can take parameters:
public MyClass(int someNumber) : this(someNumber, 0) {}
public MyClass(int someNumber, int someOtherNumber)
{
this.someNumber = someNumber;
this.someOtherNumber = someOtherNumber;
}
Calling code:
MyClass myObject = new MyClass(100, 5);
The static constructor runs only once for all instances or uses of the class. It will run the first time you use the class. Normal constructors run when you instantiate an object of the class.
Everything you should need to know about static constructors can be found here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors
For instance, if I have a class like this:
namespace Sample
{
public Class TestObject
{
private Object MyAwesomeObject = new MyAwesomeObject();
}
}
Is there any benefit to set it up so that the property is set in the constructor like this?
namespace Sample
{
public Class TestObject
{
private Object MyAwesomeObject;
public TestObject()
{
MyAwesomeObject = new MyAwesomeObject()
}
}
}
The two are (nearly) identical.
When you define the initializer inline:
private Object MyAwesomeObject = new MyAwesomeObject();
This will happen prior to the class constructor code. This is often nicer, but does have a couple of limitations.
Setting it up in the constructor lets you use constructor parameters to initialize your members. Often, this is required in order to get more information into your class members.
Also, when you setup values in your constructors, you can use your class data in a static context, which is not possible to do with inlined methods. For example, if you want to initialize something using an expression tree, this often needs to be in a constructor, since the expression tree is in a static context, which will not be allowed to access your class members in an inlined member initializer.
It makes it easier to do step by step debugging
It makes it easier to control the order in which you call constructors
It makes it possible to send parameters to the constructors based on some logic or passed in argument to the object you are working on.
Another nice property of initializing stuff at the declaration site is that doing so on readonly fields guarantees that the field is not observable in its default (initiaized to zero) state.
Here's my article on the subject:
http://blogs.msdn.com/ericlippert/archive/2008/02/18/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx
The only benefit is that you can be a bit more dynamic in the constructor, where inline initialization requires that you only use static values for constructor arguments and such. For example, if MyAwesomeObject needs the value from a config file, you would have to set that in the constructor
Fields are initialized immediately
before the constructor for the object
instance is called. If the constructor
assigns the value of a field, it will
overwrite any value given during field
declaration.
See Fields (C# Programming Guide).
In your particular example, there's no advantage.
There is, however, lazy instantiation, which reduces your memory footprint in many cases:
namespace Sample
{
public Class TestObject
{
private Object m_MyAwesomeObject;
public TestObject()
{
}
public Object MyAwesomeObject
{
get
{
if (m_MyAwesomeObject == null)
m_MyAwesomeObject = new Object();
return m_MyAwesomeObject;
}
}
}
}
I like to keep all initialization for any class property whether primitive or object in the class constructor(s). Keeps the code easier to read. Easier to debug. Plus the intention of a constructor is to initialize your classes properties.
Also for clients developing against your classes it's nice to make sure that all your properties get a default value and all objects get created. Avoids the NullReferenceExceptions, when a client is using your class. For me putting this all in constructors makes it easier to manage.
I do not like to duplicate code, even if it is among a (hopefully) small number of constructors. To that end I tend to favor inline initialization wherever it makes sense.
Generally, requiring a non-default constructor ensures that the instance is in something other than the default state. This also allows immutable classes, which have their own advantages.