Static Method Calls - c#

Does each static call will initiate a new thread?
For E.g.:
class A
{
public static void displayName()
{
Console.WriteLine("myName");
}
public static void displayAge()
{
Console.WriteLine("myAge");
}
}
class B
{
public void Foo()
{
A.displayName();
A.displayAge();
}
}
Will the above calls runs independent of each other? If yes, then, is it something similar to Threading?

Reply to your doubt regarding static call:
But i heard each static call is
independent of each other as there is
no instance and only static members
are involved. is it so? – Sri Kumar 36
mins ago
You can think there is a 'global' instance of your class, and all static methods are held by this instance.
As in your example, you can create a 'user' instance by calling ClassA myA = new ClassA(). Meanwhile, there will be a 'global' instance, which is created by the runtime but invisible to you, and static methods reside in this instance. Static methods behavior as instance methods within this 'global' instance.
Amazingly, in C# there is a static constructor, which will be called when the 'global' instance is initialized by the runtime.
You can test this code:
class A
{
static A() {
Console.WriteLine("Creating the global instance of class A....");
}
public static void displayName()
{
Console.WriteLine("myName");
}
public static void displayAge()
{
Console.WriteLine("myAge");
}
}
class B
{
public void Foo()
{
A.displayName();
A.displayAge();
}
}
The output will be:
Creating the global instance of class A....
myName
myAge
Apart from this, static methods have nothing difference from instance methods.
Variables in each static method will have its own scope, and they are independent from one method to another method.

No they will run sequentially on the same thread

No. Static methods are like any other methods unless you invoke them in different threads they will run in same thread from which you have invoked.
It really depends on where do you invoke. Static methods itself does not create any threads and run within.

A static method is a method that does not have any class associated with it. This means that calling a static method does not have to go through any indirection, unlike a virtual method which is resolved based on the object it is called on.
All methods will run on the thread of the invoking method, whether virtual or static. If you want a method to run on a different thread, use the thread pool or some other technique.

One more thing:
i heard each static call is independent of each other
Static method calls are not really independent.
Static method can still access other static fields and properties within the same class, or publicly visible static fields and properties of other classes, which are also global and retained during the lifetime of your app.
Static methods which are changing the state of static fields are not "independent", as you suggested. The only thing you can say for sure that they are always invoked on a single instance (always using the same private data).

Related

Confused about public, static and private methods/classes/variables in C#

I'm a beginner in programming with C# and coming from a Python background.
I'm confused about the keywords public and static. Can someone please clarify the difference for me?
(Btw, I already know that Private variables/methods can never be accessed outside the function, whereas Public can be)
Here is just something I randomly tried to understand the difference between static, and non-static methods.
using System;
public class MainClass
{
public static void Main ()
{
int[] anArray = getAnArray();
foreach (int x in anArray)
{
Console.WriteLine (x);
}
MainClass m = new MainClass ();
foreach (int x in anArray)
{
m.Print(x);
}
}
public static int[] getAnArray()
{
int[] myArray = { 1, 2, 3, 4 };
return myArray;
}
public void Print(int x)
{
Console.WriteLine(x);
}
}
I understand that to use the non-static method Print, I first need to create an instance of the MainClass, then access the method by doing m.Print()
However I don't understand when exactly to use which. As far as I can see it would be a lot easier if Print was static, as I wouldn't need to create a new instance of my own function.
For eg, this would be simpler
private static void Print(int x)
{
Console.WriteLine (x);
}
And call the Print function with Print(x) instead of creating the instance of Main first.
So basically when to use what? When to use static or non-static in regard to not only methods but variables and even classes? (For eg when should I use public static class MainClass)
Small, self-explaining example of public/non-static and static methods in use:
Car car1 = new Car();
car1.setBrand("Ford"); //public non-static method
Car car2 = new Car();
car2.setBrand("Opel"); //public non-static method
Car.CompareParameters(car1, car2); //static method
Basically, non-static methods and properties describe objects of such class.
You can't call Car.setBrand() - non-static method using class name.
As a general rule of thumb:
Static methods
The static keyword makes the method directly accessible without having to create an instance of an object. As such, any state or side-effects it has will be static, ie "global". So only use static to create pure functions, ie methods that derive a return value from their inputs only, neither reading or writing state from outside the method.
The use of static is a trade-off between simplifying code and testing. The more side-effects you put in to a static method, the harder your code will be to test.
public methods
Anything marked public is accessible throughout your application. Marking something internal restricts it to just that assembly (you can view the term "assembly" as equivalent to a project in your solution") and private restricts it to only being assessable within a class/struct.
If you follow the principle of encapsulation, then the rule to follow is use private all the time, only using internal if you need to. And only use public if you really have to.
static members are class members, and shared between all instances of that class.
public methods/properties are available to other classes. It's possible to have a public static member which is available to other classes.
You can't access a non-static member from a static member.
If a function doesn't need access to any instance variables then it can be made static for a slight performance gain, but there are more useful ways to use static members.
Some uses for static off the top of my head:
Singletons (you create a protected constructor that is accessed by a static variable inside the class)
Console.WriteLine is static
Locks/semaphores (where there is only one available at the class level that is shared by all instances)
If something makes sense to be shared by all instances of a class, make it static

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.

Calling a class with a private constructor and private static methods?

I created a class with 6 private static methods and a private constructor. The private constructor runs all of the static methods. I want to call the class's private constructor in another class, but I'm not able to. All I want is to run this class once without creating an instance of anything. The class populates a small database and I have no need for it other than calling it once.
I could put it into a method, but I don't want to put unrelated code into my main class. I want everything more separated. I could just do it with a public constructor and create an instance of the class, but I don't see why I would have to do it that way when an instance isn't needed.
Is there a good way to accomplish what I'm trying to do?
Why not replace your private constructor with a public static method?
Your original code:
public class DatabaseInitializer
{
private DatabaseInitializer()
{
init1();
init2();
...
}
private static void init1() { ... }
private static void init2() { ... }
...
}
Your new code
public class DatabaseInitializer
{
public static void Init()
{
init1();
init2();
...
}
private static void init1() { ... }
private static void init2() { ... }
...
}
Than you call it:
Main()
{
DatabaseInitializer.Init();
}
Singleton would make exact one Instance. If you don't want an Instance, just make one static method public. If you want to make sure this is called only once make a static counter or a bool in your class which stop the method from being called a second time
call constructor without an instance is impossible, even if it was public
I want to call the class's private constructor in another class
--
All I want is to run this class once without creating an instance of anything
If you do not want to create an instance of your class, then do not use the constructor. I think you just want to use a class to "separate" some code? Use a static method for that.
Or if this code should run once and call some static methods. You can use a static ctor
class B
{
static B() {
//this stuff called when you create this class or when a static member is referenced
}
IMHO, this is not an unrelated code for main class. It's dependent on these methods.
You could just have one public method in the class. Dependent classes can then call that method which in turn calls all the private methods doing processing.
If you want to call it or its members from another class, you will need to make a public method.
If you don't want any instances of this class around, then you should make a public static method that can be called.
The public static method should have a static boolean. When called, it checks that value, and if not set, switches the static boolean value (so it knows it has been called before) and then calls all the private static methods that need to be run once and only once.
If you only need this initialization done once ever to the database, rather than once per effort, then you should have your static code run out and check the database to see if it has already been initialized. You could make this particularly easy by having a one row table that holds a boolean in it that you can test. Just update the initialization code to set that value when the DB is initialized, and have your start up code test for that value to determine its value and what actions to take based upon that value.

Is it safe for a class to create instances of itself inside the static constructor?

I stumbled upon a problem where i need an instance of the class inside its static constructor. I believed it was not possible to do it so i tried the following:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Foo.someString);
Console.ReadLine();
}
}
class Foo
{
public static readonly string someString;
static Foo()
{
someString = new Foo().CreateString();
}
private string CreateString()
{
return "some text";
}
}
To my surprise, it works - the output is "some text". I believed the static constructor must run and complete before instances of the class can be created. This answer shows that this is not necessarily the case. Does this mean that static and instance constructors are independent of each other? And finally, is it safe to do this (create instances in static constructor)?
p.s. Let's ignore the fact that this can be avoided by using a different approach.
All that the specification says is that the static constructor will be called before any instance of the class is created. But it doesn't state anything about the fact that this constructor must finish:
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.
You could perfectly fine create instances of the class inside the static constructor and this is safe.
It is safe as it will be called only once.
Static constructor called automatically before the first instance is created or any static members are referenced any static fields are referenced. Hence when your application ran and you accessed Foo, the static constructor was executed and your string was initialized.
Is it safe ? : As such there is no harm in doing this. It is just they are executed only once.
For information on this read Static Classes and Static Class Members on MSDN

c# : console application - static methods

why in C#, console application, in "program" class , which is default, all methods have to be static along with
static void Main(string[] args)
Member functions don't have to be static; but if they are not static, that requires you to instantiate a Program object in order to call a member method.
With static methods:
public class Program
{
public static void Main()
{
System.Console.WriteLine(Program.Foo());
}
public static string Foo()
{
return "Foo";
}
}
Without static methods (in other words, requiring you to instantiate Program):
public class Program
{
public static void Main()
{
System.Console.WriteLine(new Program().Foo());
}
public string Foo() // notice this is NOT static anymore
{
return "Foo";
}
}
Main must be static because otherwise you'd have to tell the compiler how to instantiate the Program class, which may or may not be a trivial task.
You can write non static methods too, just you should use like this
static void Main(string[] args)
{
Program p = new Program();
p.NonStaticMethod();
}
The only requirement for C# application is that the executable assembly should have one static main method in any class in the assembly!
The Main method is static because it's the code entry point to the assembly. There is no instance of any object at first, only the class template loaded in memory and its static members including the Main entry point static method. Main is predefined by the C# compiler to be the entry point.
A static method can only call other static methods (unless there is an instance handle of something composited for use). This is why the Main method calls other static methods and why you get a compile error if you try to call a non-static (instance) method.
However, if you create an instance of any class, even of the Program class itself, then you start creating objects in your application on the heap area of memory. You can then start calling their instance members.
Not all methods have to be static, you can add instance methods and also create an instance of your Program class.
But for Main it has to be static beacause it's the entry point of your application and nobody is going to create an instance and call it.
So, technically correct answers are above :)
I should point out that generally you don't want to go in the direction of all static methods. Create an object, like windows form, a controller for it and go towards object-oriented code instead on procedural.

Categories

Resources