C# Class and Instance Constructors - c#

The MSDN RyuJIT blog entry gives this instruction for setting up CTP3:
Tricky thing necessary until RyuJIT is final: Add a reference to
Microsoft.Numerics.Vectors.Vector to a class constructor that will
be invoked BEFORE your methods that use the new Vector types. I’d
suggest just putting it in your program’s entry class’s constructor.
It must occur in the class constructor, not the instance constructor.
I'm far better versed in class/instance construction in Objective-C than I am in C#. Is he talking about a different concept? What is the difference between a class constructor and an instance constructor in C#? Is the "class constructor" in this case simply the parameterless constructor?

I think this refers to the static constructor

Class constructor = Static constructor
Instance constructor = Normal constructor
For example,
class MyClass
{
// Static/Class constructor.
// Note: Static constructors cannot have visibility modifier (eg. public/private),
// and cannot have any arguments.
static MyClass()
{
... // This will only execute once - when this class is first accessed.
}
// Normal/Instance Constructor.
public MyClass(...)
{
... // This will execute each time an object of this class is created.
}
}
So as an example, consider the following code:
static void Main(string[] args)
{
var a = new MyClass(); // Calls static constructor, then normal constructor.
a.DoSomething();
var b = new MyClass(); // Calls normal constructor only.
b.DoSomething();
}
Also, consider the following code:
static void Main(string[] args)
{
MyClass.SomeStaticMethod(); // Calls static constructor, then SomeStaticMethod().
MyClass.SomeOtherStaticMethod(); // Calls SomeOtherStaticMethod() only.
// Note: None of the above calls the normal constructor.
}

Related

What is the difference between the parameterless constructor with no members VS default constructor compiler creates in c#?

class Constructor
{
Constructor()
{
}
static void Main()
{
Constructor obj = new Constructor();
}
}
class Compiler
{
Compiler obj1 = new Compiler();
}
In the first program I created a constructor with no members and in the second program I'm not created any constructor so the compiler creates a default constructor so what's the difference between them in c#
Reference: Microsoft docs - Constructors
"...classes without constructors are given a public parameterless constructor by the C# compiler in order to enable class instantiation."
Cases when you do need to write a parameterless constructor:
When you have other constructors defined in the class.
When you want to use a different protection level for your parameterless constructor.
There are other problems (see below) in the code shown, but in general there is no difference between an empty parameterless constructor you create vs. an empty parameterless constructor the compiler creates. It's possible they result in slightly different compiled code, but for all intents and purposes they do the same thing.
Other problems in the code shown...
This will result in an infinite recursion any time you try to create an instance of it:
class Compiler
{
Compiler obj1 = new Compiler();
}
And this constructor is not the same as the compiler-default one because class members are private by default:
class Constructor
{
Constructor()
{
}
static void Main()
{
Constructor obj = new Constructor();
}
}

Do default constructor exists with static constructor in C#?

I am confused with static constructor in a instance class.
As a static constructor is private by default and we can not use access modifier with them, then do default constructor exists with static constructor in a instance class?
If yes, then Why? because we have already defined a constructor(private static and parameter less) and according to C# concept, if we provide a constructor then the default constructor won't exists. (I might be wrong here)
If No, then Why we are able to create a object of instance class with static constructor.
Below example is complied and executing successfully:
public class OOPS
{
static int i = 0;
static OOPS(){
Console.WriteLine("Static Constructor ");
}
//OOPS() {
// Console.WriteLine("Instance Constructor");
//}
public static void ShowStaticMethod() {
Console.WriteLine("Static Method ");
}
public void ShowInstanceMethod()
{
Console.WriteLine("instance Method");
}
}
class Client
{
public void ClientMethod() {
OOPS o = new OOPS();
o.ShowInstanceMethod();
OOPS.ShowStaticMethod();
Console.WriteLine("Client completed");
Console.ReadLine();
}
}
if we provide a constructor then the default constructor won't exists.
(I might be wrong here)
Well you are wrong about one thing, the above statement is true with respect to instance constructor, not static constructor.
Look at the C# language specification.
10.11.4 Default constructors
If a class contains no instance constructor declarations, a
default instance constructor is automatically provided.
So, when you provided the static constructor, it didn't have any relation with the default instance constructor, and that is the one you are using later in your code.
Static constructor does not affect instance constructors. If you do not want for the class to be instantiated, mark the class as static.
public static class OOPS
{
static OOPS()
{
}
}

Static constructor not working for structs

Env.: C#6, Visual Studio 2015 CTP 6
Given the following example:
namespace StaticCTOR
{
struct SavingsAccount
{
// static members
public static double currInterestRate = 0.04;
static SavingsAccount()
{
currInterestRate = 0.06;
Console.WriteLine("static ctor of SavingsAccount");
}
//
public double Balance;
}
class Program
{
static void Main(string[] args)
{
SavingsAccount s1 = new SavingsAccount();
s1.Balance = 10000;
Console.WriteLine("The balance of my account is \{s1.Balance}");
Console.ReadKey();
}
}
}
The static ctor is not being executed for some reason. If I declare SavingsAccount as a class instead of a struct, it works just fine.
The static constructor isn't executed because you are not using any static members of the struct.
If you use the static member currInterestRate, then the static constructor is called first:
Console.WriteLine(SavingsAccount.currInterestRate);
Output:
static ctor of SavingsAccount
0,06
When you are using a class, the static constructor will be called before the instance is created. Calling a constructor for a structure doesn't create an instance, so it doesn't trigger the static constructor.
According to the CLI spec:
If not marked BeforeFieldInit then that type’s initializer method is
executed at (i.e., is triggered by):
first access to any static field of that type, or
first invocation of any static method of that type, or
first invocation of any instance or virtual method of that type if it is a value type or
first invocation of any constructor for that type
For structs which have an implicit default constructor it is not actually invoked, so you can create an instance and access its fields. Everything else (invoking custom constructors, instance property access, method calls, static field access) will trigger static constructor invocation.
Also note that invoking inherited Object methods which are not overridden in the struct (e.g. ToString()) will not trigger static constructor invocation.

Class Initialize() in C#?

In Obj-c there is the static Initialize method which is called the first time that class is used, be it statically or by an instance. Anything like that in C#?
You can write a static constructor with the same syntax as a normal constructor, except with the static modifier (and no access modifiers):
public class Foo {
static Foo() {
// Code here
}
}
Usually you don't need to do this, however - static constructors are there for initialization, which is normally fine to do just in static field initializers:
public class Foo {
private static readonly SomeType SomeField = ...;
}
If you're using a static constructor to do more than initialize static fields, that's usually a design smell - but not always.
Note that the presence of a static constructor subtly affects the timing of type initialization, requiring it to be executed just prior to the first use - either when the first static member access, or before the first instance is created, whichever happens first.
There is a static constructor. As per msdn:
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.
public class Foo
{
static Foo() {} //static constructor
}
Yes, it is called a constructor.
By MSDN:
public class Taxi
{
public bool isInitialized;
//This is the normal constructor, which is invoked upon creation.
public Taxi()
{
//All the code in here will be called whenever a new class
//is created.
isInitialized = true;
}
//This is the static constructor, which is invoked before initializing any Taxi class
static Taxi()
{
Console.WriteLine("Invoked static constructor");
}
}
class TestTaxi
{
static void Main()
{
Taxi t = new Taxi(); //Create a new Taxi, therefore call the normal constructor
Console.WriteLine(t.isInitialized);
}
}
//Output:
//Invoked static constructor
//true

static keyword when creating instance

I came across the following code.
public class Test
{
public static Test Create()
{
return new Test
{
a1 =1,
b1="abc"
};
}
:
:
:
}
And in the calling class it is instantiated as below
static Test model = Test.Create();
What is the use of static keyword in the above line? What will be the difference if we don't use the static keyword? I'm using .NET 4 and VS 2010
EDIT
I know what is static in c#. The main reason I asked this question is why is it used when creating instance of class?
In this concrete presented code, don't see much sence of using this technique, but usually
you can do this in order to control your type instances creation.
For example: immagine that your class interacts with some COM object of the client, that can not be instantiated more the 10 times. To control that consumer of your API will not create more then 10 instances of your type, you can use this technique.
public class MyComWrapper {
private MyComWrapper () {} // MAKE CTOR PRIVATE SO NOONE CAN CREATE
// AN INSTANCE OF YOUR CLASS IF NOT WITH
// `static` METHOD CALL
static int counter = 0; //INSTANCE COUNTER
public static MyComWrapper Create()
{
if(counter >10) //MORE THEN 10, BAD !
throw new InvalidOperationException("Can not instantiate more then 10 instances");
counter ++;
return new Test
{
a1 =1,
b1="abc"
};
}
}
The static keyword makes it available without instantiating the object. The author is creating a function to instantiate the object in a specific way, but since it's the default constructor anyone can instantiate it.
Although not exclusively, along with making the constructor private, this is a pattern commonly used in the Singleton Pattern.
Static modifier belongs to the type itself rather than to a specific object.
You don't have to create an instance to use that static function. you can directly use the static function without creating an instance of the class.
If the static keyword is applied to a class, all the members of the class must be static.
It is simple. They are separate uses of static. The first one creates a static method in a non-static class. The second one create a static member of the "calling" class.
Your Test class itself is not static, so you are allowed to instantiate it.
To answer your question: if you do not use the static keyword in the calling class, it will be a "normal" instance member.

Categories

Resources