0

I come today with a weird question. Is there a way where I can use a non static class like static?

I.e: We have the following classes:

public class Parameters { public String LoadType { get; set; } public Parameters (String inLoadType) { LoadType = inLoadType; } } public class MainClass { public Parameters Parameters { get; set; } public MainClass(String inLoadType) { Parameters = new Parameters(inLoadType); } } 

Now we instantiate MainClass, then somewhere in another place that is not the MainClass I would like to access to the LoadType.

It should be threadSafe, also the operation take quite long, that is the reason I cannot simply just use a lock and make it static.

The class where I want to access that variable is static, I thought in a workaround with a static Event in the Parameters class, and whoever call the event would get the value of the instantiated class or something like that. Any other Ideas about it beside passing as parameter to the static method what I need?

Sounds like stupid question but I just want to know if is possible or not.

7
  • 4
    You need a singleton. Commented May 4, 2016 at 10:22
  • Yes singleton class will work here Commented May 4, 2016 at 10:24
  • Singleton would be static if I want to access outside the MainClass,then it would not be threadsafe. Am I wrong? Commented May 4, 2016 at 10:25
  • 1
    Yes you are. Thread safety and static/non static classes are two different concepts. @TareqB. Commented May 4, 2016 at 10:26
  • A singleton doesn't have to be static. But to use it within a class it must be provided as a dependency either in the constructor of that class or passed to it in a method call. Although I'd advocate constructor dependency in this case. Commented May 4, 2016 at 10:28

1 Answer 1

1

Imagine, that you have two Parameters instances

 Parameters one = new Parameters("One"); Parameters two = new Parameters("Two"); 

and then you call:

 String result = SomeWeirdBlackMagicCallOfLoadType(); 

What is the expected result? "One" or "Two"? In order to solve this problem, you can turn Parameters into singletone (one instance only) and thus the call will be

 String result = Parameters.Instance.LoadType; 

but I suggest treating static as static when data doesn't depend on instance. In case of long operations, thread safety you can use Lazy<String> which is specially designed for that:

 public class Parameters { private static Lazy<String> s_LoadType = new Lazy<string>(() => { .... return "bla-bla-bla"; }); public static String LoadType { get { return s_LoadType.Value; } } ... } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.