Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static members behavior with multiple instance of application - C#

I'm working on my Window Application and i'm using some static members.

public class MyParameter
{
    public static string connectionString = "...";
}

Now if I install my application on computer and open two instance of same application. Will 'connectionString' common to the two instances?? Or every instance has its connectionString ?

like image 616
dchamba Avatar asked Jun 24 '13 09:06

dchamba


People also ask

Can you have multiple instances of a static class?

A static class cannot be instantiated. All members of a static class are static and are accessed via the class name directly, without creating an instance of the class. The following code is an example of a static class, CSharpCorner. We know that all members of the class are static.

Can static class have instance members?

Static classes cannot contain an instance constructor. However, they can contain a static constructor.

How many possible copies can a static member have?

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.

What is the advantage of using class static members?

Advantages of Static Classes When you try to create an instance to the static class, it again generates a compile time error, because the static members can be accessed directly with its class name. The static keyword is used before the class keyword in a class definition to declare a static class.


3 Answers

The variable static or not is a part of your application memory. When you open 2 instances of your application you create two distinct memory locations in the OS, so there is not any relation between those 2 variables at all.

If you want to create one (relation), you have to look on different IPC (Inter Process Communication) methods available in OS, like:

  • Memory Mapped Files
  • Named Pipes
  • IPC Mechanisms in C# - Usage and Best Practices
like image 198
Tigran Avatar answered Nov 04 '22 01:11

Tigran


No, Each application instance are isolated from one another using AppDomain. Thus each application instance will run in a seperate AppDomain and cannot access the variables from other domain. To do communicate with different domain we need to use Remoting , WCF Service

like image 21
Vimal CK Avatar answered Nov 04 '22 00:11

Vimal CK


Every instance.

Static members are allocated on a per AppDomain basis. If you were to spawn a new AppDomain from within your current one.. they would be different.

like image 40
Simon Whitehead Avatar answered Nov 04 '22 01:11

Simon Whitehead