Microsoft Developer
Microsoft Developer

Reputation: 5459

Share a variable to be used by two function without making it global

I am in a situation where a variable needs to be shared by two function. One way is to make it global. But by making it global, other functions will also have access to that variable. I want that particular variable to be accessed by selected functions only. Is there any way to achieve this type of functionality either by making it global with restriction or bay any other way?

Upvotes: 0

Views: 45

Answers (2)

flq
flq

Reputation: 22849

Apart from the "classic" way you could operate with closures:

public class ClosureProvider {
  private Foo shared;

  public Func<object> GetFirst() {
    return new Func<object>(() => { /* Use shared and whatever else */ });
  }

  public Action<Bar> GetSecond() {
    return new Action<Bar>(bar => { /* Use shared and whatever else */ });
  }
}

The c# compiler will build the required infrastructure for you and the two returned functions have access to shared and whatever other things you want to use

Upvotes: 1

kmcc049
kmcc049

Reputation: 2801

You could pass it between the functions as a parameter.

Upvotes: 2

Related Questions