C# Instance Constructor vs Static Constructor - c#

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

Related

There are two ways to initialize members in a C# class via constructor or through member initialization

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.

Why the compiler allow to create an object of non static class in static context?

As per the definition
Non static things can not be accesses in static context
then how does it allow to create an object of non-static class to the static main method.
class Test
{
static void Main()
{
Base x = new Derived();
x.Foo();
}
}
This is not the right definition. Here is one from MSDN:
Static methods and properties cannot access non-static fields and
events in their containing type, and they cannot access an instance
variable of any object unless it is explicitly passed in a method
parameter.
Note that you are not accessing nont-static members of Test, and neither you are using some outer variables.
Compare this, which is not allowed, to your snippet:
class Test
{
int t = 1;
static void Main()
{
Base x = new Derived();
x.Foo(t); // not allowed!
}
}
You understand that completely wrong. Static methods can't access the instance members, because they don't have the this reference. That isn't a prohibition, simply a fact of a missing reference. If you supply the reference (eg. through method parameter, creating an instance inside etc.), there's nothing to stop you from doing the call.
In other words,
class Test
{
int testField = 23;
static int GetTestField()
{
// Doesn't compile - static methods don't have a
// `this` reference to get the instance member
return testField;
}
}
Fails to compile. However,
public class Test
{
public int testField = 23;
}
public static class Tester
{
public static int GetTestField(Test test)
{
return test.testField;
}
}
works just fine, because you pass the instance of Test you're trying to access.
You're not forbidden from using instance members in static methods (that would make them almost useless!). You just don't have a this reference, as simple as that.
Not really for Stack Overflow, but okay:
To understand this, it's helpful to know something of what's going under the hood. Basically, the CPU doesn't really have a notion of things like "classes" or "methods". That's why higher level programming languages invented calling conventions - common ways to invoke methods and pass them parameters. So, for example, if you wanted to call Print(23);, it might do something like this:
push 23
call Print
The Print method would then know it's parameter is store on top of the stack, and it could retrieve it using the current stack pointer, for example.
When classes came around, they brought a concept known as encapsulation. Basically, the class effectively has its own memory storage, and its own methods. When you want to access that data (or functionality), you have to do it through the class instance. On the lower level, this is usually handled by passing the reference to the object as the first parameter of the method. So, calling test.GetTestField(23, 21) (where test is a reference to an instance of the Test class) would do something like this:
push test
push 23
push 21
call Test.GetTestField
(this is all pseudo-code, the actual way the compiler handles that differs between calling conventions and languages; for example, parameters are often sent in reverse-order)
This way, the GetTestField method has access to the instance of the Test class (which it may or may not need for what it does). So when the method has to get the value of an instance field, for example, it can get this.testField (in C# and most other languages, the this can be ommited and is implied - everytime you access an instance field/method/etc. inside a class, it adds the this under the covers).
Static methods don't have this luxury - but that's also why they exist in the first place. They're used for functionality that is related to the class in which they are defined, but they don't require the instance members of the class (or they get the instance reference some other way).
Example - there's an int class in .NET framework (actually, it's a struct, but let's ignore that for now). The class has a couple of static methods, and a couple of instance methods. For example, the instance method ToString() takes the value of the int, and converts it to a string value - for this, it (obviously) needs to have the value of the integer. On the other hand, it has a static method Parse(string), which takes a string parameter with the string value of the integer, and converts it to an integer. It creates a new integer, and parses the string value into it as an integer value. Since it creates a new instance of integer, it doesn't actually use this, and as such, can be safely declared as static. This avoids some extra costs of instance methods (even more so in languages where methods are virtual by default), at the very least, passing the extra parameter, but more importantly, it broadcasts the intent of the method - "I don't read or modify the instance members of this class". If you didn't have static methods, and you wanted to write the Parse method mentioned above, you'd have to create an instance of int first and call Parse on that.
you need to remember that you are not accessing the Foo() directly but with the help of instance variable x.That is always possible.
Note : you can not access non static members as below:
void Foo()
{
}
static void Main()
{
Foo();//compile error
}
You absolutely can access non-static members in a static context, as long as you have a valid reference to an object.
The only reason a static context is different from a non-static context in this regard, is that the static context doesn't have the this reference (which is implied when you access non-static members without explicitly referencing an object). The non-static context, on the other hand, always has an implicit this reference.
The problem isn't that you can't access non-static fields/methods/etc in a static context, it's that you can't access non-static fields/methods without an instance.
In the code you provided, there is an instance of Base, and so you can access it's methods, regardless of the context.
You can make object of non-static class in static method but could not access the non-static member int that class. Suppose you have an object of Derived class as a member of Test then you wont be able to access that object in static method main.
Define a non-static method in Test class and try to call it from Main method you will get error again.
class Test
{
Derived d = new Derived();
static void Main()
{
// You can not access d here.
// You can not access MyFun() here.
}
void MyFun()
{
}
}

C# - Class , constructors and Resharper - clarification

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!");
}
}

singleton pattern in C# Question

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 does a static modifier on a constructor means?

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.

Categories