Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is static context always single in C#?

Tags:

c#

.net

I have a library that has a static field inside. I want to create an app and reference this library so I'd have two instances of this static field. .Net runtime does not allow to reference the same library twice, but I wonder is it possible to overcome this limitation?

I'm not allowed to change the library, but I can copy/rename it.

like image 655
Archeg Avatar asked Jan 30 '15 11:01

Archeg


People also ask

What is static context?

But static contexts(methods and blocks) doesn't have any instance they belong to the class. In a simple sense, to use “this” the method should be invoked by an object, which is not always necessary with static methods. Therefore, you cannot use this keyword from a static method.

What is a static variable C#?

Static variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it. Static variables can be initialized outside the member function or class definition. You can also initialize static variables inside the class definition.


2 Answers

That's not as crazy as you think. In fact, you can achieve this using AppDomains.

Each AppDomain has its own storage location for static variables. So you can just create a second AppDomain in your process, and communicate between them using an object that inherits from MarshalByRefObject like in this MSDN example.

like image 71
Lucas Trzesniewski Avatar answered Sep 21 '22 19:09

Lucas Trzesniewski


While Lucas' suggestion on AppDomains would work, alternatively you could create this effect using generics, as a class with different generic type arguments is treated as a different class, and therefore has its own static fields.

public class SomeClass<T> {     public static string SomeField; } 

Then:

SomeClass<int>.SomeField = "A"; SomeClass<string>.SomeField = "B";  Console.WriteLine(SomeClass<int>.SomeField);    // A Console.WriteLine(SomeClass<string>.SomeField); // B 

For example, the SomeClass<int> would be set in the library, whereas the SomeClass<string> would be your copy. Of course this would only work if you could change the library, or the library already used generics.

like image 24
Daniel A.A. Pelsmaeker Avatar answered Sep 22 '22 19:09

Daniel A.A. Pelsmaeker