To be clear, I want the behavior of a pointer-to-a-pointer, and the purpose of this question is to generate clean, readable code.
I have some code that contains conditions checking the result of multiple Dictionary.TryGetValue
calls. It would be cleaner if it could retrieve all of the required objects with a single call, so I wanted to write an extension that will allow me to do the following:
Dictionary<string, string> myDictionary; // Initialized somewhere
string x, y, z;
bool foundAllEntries = myDictionary.TryGetValues({"xvalue", out x}, {"yvalue", out y},
{"zvalue", out z});
if (foundAllEntries)
; // Do something with x, y, and z
However, I can't figure out a way to pass the extension method references to the objects that will hold the output. This seems like something that should be very basic.
How can I store a reference to a local reference in an object?
Please note that this question is not asking for alternative approaches to implementing the TryGetValues function. There are many ways I can make this 'work,' but none generate code as clean as the approach I'm trying to take.
This seems like something that should be very basic.
Not only it isn't basic, it's outright impossible: there is no way to decorate a data type with ref
or out
- these modifiers are applicable exclusively to formal method parameters. In other words, there is no such thing as a "reference variable" or an "output variable"; there are only "reference parameters" and "output parameters" in the language.
Moreover, you cannot pass output or by reference parameters as part of a variable-length argument list (i.e. the params
portion) so that approach wouldn't work either.
There are many ways I can make this 'work,' but none generate code as clean as the approach I'm trying to take.
Curiously, the above does not mean that you cannot implement the scheme that you are trying to implement, leaving the code nearly as clean as your original one if you apply the Proxy Design Pattern. The trick is to chain method calls, and provide an implicit conversion operator for the result, like this:
class MyMap {
internal IDictionary<string,string> dict = ...
public ItemGetterResult TryGetValues {
get {
return new ItemGetterResult(this, true);
}
}
}
class ItemGetterResult {
private readonly MyMap map;
private bool IsSuccessful {get;set;}
internal ItemGetterResult(MyMap theMap, bool successFlag) {
map = theMap;
IsSuccessful = successFlag;
}
public static implicit operator bool(ItemGetterResult r) {
return r.IsSuccessful;
}
public ItemGetterResult Get(string key, out string val) {
return new ItemGetterResult(
map
, this.IsSuccessful && map.dict.TryGetValue(key, out val)
);
}
}
Now the call looks like this:
bool foundAllEntries = myDictionary.TryGetValues
.Get("xvalue", out x)
.Get("yvalue", out y)
.Get("zvalue", out z);