c# static constructor problem - c#

The following code does not call the class static constructor. Is this a bug or feature?
class Test
{
static Test
{
//do stuff
}
public static AnotherClass ClassInstance { get; set; }
}
class Program
{
public static void Main()
{
var x = Test.ClassInstance;
}
}
I don't have a compiler right now, but this is what happened to me today. The static constructor is never called, but it is called when ClassInstance is a field instead.
EDIT:
I understand that static constructor is called when first instance is created or a field is accessed. Isn't there a field behind the automatic implemented property?
I am looking for some explanation on why the property does not trigger static constructor when property is implemented as two functions and one field. It is just very unlogical to me and that is why I thought it could be a bug.

Static constructors invoked the first time an instance of a class are created or when a static member is referenced. So the first time your create an instance of Test or when the ClassInstance property is referenced is when your static constructor will be called.
Would you like to know more? - http://msdn.microsoft.com/en-us/library/k9x6w0hc(VS.80).aspx

I verified the same behaviour, but if you change the code like this:
class AnotherClass {}
class Test
{
static Test()
{
Console.WriteLine("Hello, world!");
}
public static AnotherClass ClassInstance { get { return new AnotherClass(); } }
}
class Program
{
public static void Main()
{
var x = Test.ClassInstance;
}
}
it writes "Hello, world!"...

Static constructor is called when any static member is accessed or instance is created
class Program
{
static void Main(string[] args)
{
A.SomeField = new B();
}
}
class A
{
static A()
{
Console.WriteLine("Static A");
}
public static B SomeField { get; set; }
}
class B
{
static B()
{
Console.WriteLine("Static B");
}
}
Result:
Static B
Static A
As you see - there is no "Static B" in the result

the static constructor is called automatically before the first instance is created or any static members are referenced.
more information from Msdn.

Related

Static Class vs Protected Constructor

I Am getting a warning message in my class, like
Add a Protected constructor or the static keyword to the class declaration
Solution
The error is gone after I tried both the below ways,
static class without constructor
public static class Program {
}
Non static class with protected using constructor
public class Program
{
protected Program() { }
}
Question:
So What is the difference between Static Class vs Protected Constructor which is mentioned in my above solution? And which one is best to use?
A static class doesn't need an instance to access its members. A static class cannot have instance members (e.g. public int MyNumber; is not allowed on a static class because only static members are allowed on a static class). Both instance and static members are allowed on a non-static class though. A class with a protected constructor can only have an instance created by itself or something that inherits from it.
public class Program
{
protected Program()
{
// Do something.
}
public static Program Create()
{
// 100% Allowed.
return new Program();
}
public void DoSomething()
{
}
}
public static class AnotherClass
{
public static Program CreateProgram()
{
// Not allowed since Program's constructor is protected.
return new Program();
}
}
public class SubProgram : Program
{
protected SubProgram()
{
// Calls Program() then SubProgram().
}
public new static Program Create()
{
// return new Program(); // We would need to move the SubProgram class INSIDE the Program class in order for this line to work.
return new SubProgram();
}
}
Program.Create(); // Can be called since Create is public and static function.
Program.DoSomething() // Can't be called because an instance has not been instantiated.
var test = Program.Create();
test.DoSomething(); // Can be called since there is now an instance of Program (i.e. 'test').
AnotherClass.CreateProgram(); // Can't be called since Program's constructor is protected.
SubProgram.Create(); // Can be called since SubProgram inherits from Program.
As for performance, this distinction doesn't really have much to do with performance.
You probably only have static members in the class and the code analyser assumes that your intention is to not be able to create instances of the class so it is asking you to either make the class static
public static class Program {
//...static members
}
or put a protected/private constructor
public class Program {
protected Program { //OR private
}
//...static members
}
to prevent instances of that class from being initialized.
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated.
Reference Static Classes and Static Class Members (C# Programming Guide)
The protected constructor means that only derived classes can call the constructor
and a private constructor wont allow any other classes to initialize the class with a private constructor
A static constructor is called when the class type is instantiated. The protected constructor is called when an instance of a class is created. The protected part means only classes that inherit the class can call it.
Static Constructor: Called once when the class type is instantiated and is used to initialize static members. Does not create an instance of the class.
Protected Constructor: A constructor that can be called only by the class or a class that inherits it.
The best practices for this is that you should have a static constructor for initializing static members and a protected constructor if you only want classes that inherit to be able to create an instance of your class. You can have both.
public class MyClass
{
static readonly long _someStaticMember;
private bool _param;
static MyClass()
{
//Do Some Logic
_someStaticMember = SomeValueCalculated;
}
protected MyClass(bool param)
{
_param = param;
}
}
public class ChildClass: MyClass
{
public ChildClass(bool param) : base(param);
}
public class NotChildClass
{
public MyClass someObject = new MyClass(true); //Will Fail
}

Find out on which type a static method was called

I have a class A with a static method, and a derived class B. You can call Foo(), declared in A, on both A and B:
public class A
{
public static void Foo()
{
// How to get typeof(B) here if Foo called by using class B?
}
}
public class B : A
{
}
...
static class Program
{
static void Main()
{
B.Foo();
}
}
Now inside Foo(), how can I find out on which type Foo() was called?
I can't use keyword this, because I do not create any objects here. I have tried already:
MethodBase.GetCurrentMethod().DeclaringType
and
MethodBase.GetCurrentMethod().ReflectedType
but they both return me the typeof(A), while I need to get the typeof(B).
I'm not sure exactly what you want to achieve, and agree with the comments that perhaps you can approach this a different way. Saying this, could you do what you need with a generic base class?
public class AB<T>
{
public static void Foo()
{
Console.WriteLine(typeof(T));
}
}
public class A : AB<A> { }
public class B : AB<B> { }
A.Foo(); // A
B.Foo(); // B
There are no way to obtain typeof(B) inside of static method Foo() in this case. The possible solution is to use parameters in Foo method.
Thanks to #Jon Skeet and #CodeCaster.

initialize constructor with new inside class in C#

I'm new to C# programming. I want to know why this is not possible:
// In file1.cs
public class Test {
public int Rt() {
return 10;
}
}
// In file2.cs
public class Test2 {
// initialize constructor here, but return compile-error
Test k = new Test();
static void Main() {
Console.Write(k.Rt()); // error here
}
}
Additional: I am learning C# for unity, so I also want to know if above is not possible then why this is not an error in unity
public class PlayerScript: MonoBehaviour {
public Vector2 speed = new Vector2(25, 25); // Not an error
void Update() {
Debug.Log(speed); // works
}
}
You're trying to access an instance member inside a static method. That's not allowed. You can define k as static to make it work
static Test k = new Test();
I recommend you to take a look to Static Classes and Static Class Members to get more details
The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. 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.
In addition to the other answers, another option is to make your Test class and Rt method static. Like so:
public class Program
{
public static void Main()
{
Console.Write(Test.Rt());
}
}
public static class Test {
public static int Rt() {
return 10;
}
}
You really don't have many cases to use a static class though they do exist. I would just move Test t = new Test(); inside your Main method.
public class Program
{
public static void Main()
{
Test t = new Test();
Console.Write(t.Rt());
}
}
public class Test {
public int Rt() {
return 10;
}
}
This is because your Main method is static but your Test2 class is not static. The k variable lives in an instance of Test2 but the Main method belongs to the type itself. If something is static, it means you can call it without instantiating a variable of that type:
Test2.Main();
If you attempted to instantiate a Test2 and call Main you'd get an error because it's static.
var test2 = new Test2();
test2.Main(); //ERROR
You can make k static for this to compile:
public class Test2 {
// initialize constructor here, but return compile-error
static Test k = new Test();
static void Main() {
Console.Write(k.Rt()); // error here
}
}
The second example you showed works fine because the Update method is not static, which means that the method lives with an instantiation of PlayerScript, unlike the Main method.

C# static class constructor

Is there a work around on how to create a constructor for static class?
I need some data to be loaded when the class is initialized but I need one and only one object.
C# has a static constructor for this purpose.
static class YourClass
{
static YourClass()
{
// perform initialization here
}
}
From 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
MSDN link
.
A static constructor looks like this
static class Foo
{
static Foo()
{
// Static initialization code here
}
}
It is executed only once when the type is first used. All classes can have static constructors, not just static classes.
Yes, a static class can have static constructor, and the use of this constructor is initialization of static member.
static class Employee1
{
static int EmpNo;
static Employee1()
{
EmpNo = 10;
// perform initialization here
}
public static void Add()
{
}
public static void Add1()
{
}
}
and static constructor get called only once when you have access any type member of static class with class name Class1
Suppose you are accessing the first EmployeeName field then constructor get called this time, after that it will not get called, even if you will access same type member.
Employee1.EmployeeName = "kumod";
Employee1.Add();
Employee1.Add();
Static constructor called only the first instance of the class created.
like this:
static class YourClass
{
static YourClass()
{
//initialization
}
}
We can create static constructor
static class StaticParent
{
StaticParent()
{
//write your initialization code here
}
}
and it is always parameter less.
static class StaticParent
{
static int i =5;
static StaticParent(int i) //Gives error
{
//write your initialization code here
}
}
and it doesn't have the access modifier
You can use static constructor to initialization static variable. Static constructor will be entry point for your class
public class MyClass
{
static MyClass()
{
//write your initialization code here
}
}
Static classes cannot have instance constructors (unlike the accepted answer). However, a class can have a static constructor. That is totally different.

How do I call a non-static method from a static method in C#?

I have the following code, I want to call data1() from data2(). Is this possible in C#? If so, how?
private void data1()
{
}
private static void data2()
{
data1(); //generates error
}
You'll need to create an instance of the class and invoke the method on it.
public class Foo
{
public void Data1()
{
}
public static void Data2()
{
Foo foo = new Foo();
foo.Data1();
}
}
Perhaps what you are looking for is the Singleton pattern?
public class Singleton
{
private Singleton() {}
public void DoWork()
{
// do something
}
// You can call this static method which calls the singleton instance method.
public static void DoSomeWork()
{
Instance.DoWork();
}
public static Singleton Instance
{
get { return instance; }
}
private static Singleton instance = new Singleton();
}
You still have to create an instance of the class but you ensure there is only one instance.
You have to create an instance of that class within the static method and then call it.
For example like this:
public class MyClass
{
private void data1()
{
}
private static void data2()
{
MyClass c = new MyClass();
c.data1();
}
}
You can't call a non-static method without first creating an instance of its parent class.
So from the static method, you would have to instantiate a new object...
Vehicle myCar = new Vehicle();
... and then call the non-static method.
myCar.Drive();
You just need to provide object reference . Please provide your class name in the position.
private static void data2()
{
<classname> c1 = new <classname>();
c1. data1();
}
Apologized to post answer for very old thread but i believe my answer may help other.
With the help of delegate the same thing can be achieved.
public class MyClass
{
private static Action NonStaticDelegate;
public void NonStaticMethod()
{
Console.WriteLine("Non-Static!");
}
public static void CaptureDelegate()
{
MyClass temp = new MyClass();
MyClass.NonStaticDelegate = new Action(temp.NonStaticMethod);
}
public static void RunNonStaticMethod()
{
if (MyClass.NonStaticDelegate != null)
{
// This will run the non-static method.
// Note that you still needed to create an instance beforehand
MyClass.NonStaticDelegate();
}
}
}
You can use call method by like this : Foo.Data2()
public class Foo
{
private static Foo _Instance;
private Foo()
{
}
public static Foo GetInstance()
{
if (_Instance == null)
_Instance = new Foo();
return _Instance;
}
protected void Data1()
{
}
public static void Data2()
{
GetInstance().Data1();
}
}
new Foo();
Foo.StaticMethod();
class Foo
{
private static Foo foo;
public Foo()
{
foo = this;
}
private void PrintHello()
{
Console.WriteLine("Hello");
}
public static void StaticMethod()
{
foo.PrintHello();
}
}
Please I think the response to your question could be :
public class <Classname> {
static method() {
(new <Classname>)->non-static();
}
non-static method(){ ...; }
~<Classname>(){...;}
};
When a data member is declared as static, only one copy of the data is maintained for all objects of the class. A static member has or handles a permanent storage.
for C++ and probably C#, when new operator is used, it allocates memory for a class object, the object constructor is called after the memory is allocated. Thus, as a static member is called preceded by it belonging classname, the same way the non-static member is called. Thus, the use of (new Classname) seems like a call of a member with predefined permanent storage like a static data member.
therefore, this method has an inconvenience: the memory allocated to call the non-static method can't be freed because the access to it is not saved; every time the static method which needs that non-static method is called, the memory is allocated with no access to be freed at the end of it process.
To resolve this inconvenience, the class must have a destructor to free memory allocated after each process. You could also use finalizers.
References
https://learn.microsoft.com/en-us/cpp/cpp/static-members-cpp?view=msvc-170
https://learn.microsoft.com/en-us/cpp/cpp/new-operator-cpp?view=msvc-170
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/finalizers
I hope these details will help you.
Static method never allows a non-static method call directly.
Reason: Static method belongs to its class only, and to nay object or any instance.
So, whenever you try to access any non-static method from static method inside the same class: you will receive:
"An object reference is required for the non-static field, method or property".
Solution: Just declare a reference like:
public class <classname>
{
static method()
{
new <classname>.non-static();
}
non-static method()
{
}
}
Assuming that both data1() and data2() are in the same class, then another alternative is to make data1() static.
private static void data1()
{
}
private static void data2()
{
data1();
}

Categories