Reputation: 5459
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
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