Common dictionary as ref param
I am trying to do something like this
public void GetData(ref Dictionary<T,V> dataDictionary)
{
}
Where T can be a GUID, string, or int and V is a custom object or object object.
Why do you want to change your caller link? Why not
public Dictionary<T,V> GetData<T,V>()
good enough?
In your link based world:
public void GetData<T,V>(ref Dictionary<T,V> dictionary)
EDIT: Not that I am in no way justifying the following, but ...
If you need to take care of the different types of T, you can create generic overrides in the same way you can create any override method.
// client code
Dictionary<int, object> x = null;
GetData(ref x);
Dictionary<string, Guid> y = null;
GetData(ref y);
general overrides:
public void GetData<V>(ref Dictionary<int, V> dictionary)
{
dictionary = new Dictionary<int,V>(); // reassign reference.
}
public void GetData<V>(ref Dictionary<string, V> dictionary) { ... }
public void GetData<V>(ref Dictionary<Guid, V> dictionary) { ... }
While semantically the same, the following overrides are not possible with return values due to ambiguity.
public Dictionary<int, T> ReturnData<T>() { ... }
public Dictionary<string, T> ReturnData<T>() { ... }
error CS0111: Type 'Testing' already defines a member called 'ReturnData' with the same parameters
You can get around the ambiguity by passing the object in and out, but it's just as awful to look at:
public Dictionary<int, T> ReturnData<T>(Dictionary<int, T> self) { ... }
public Dictionary<string, T> ReturnData<T>(Dictionary<string, T> self) { ... }
Does it help? Any additional information would be helpful.
public void GetData<T, V>(ref Dictionary<T, V> dataDictionary) {
if (typeof(T) == typeof(string) || typeof(T) == typeof(int) || typeof(T) == typeof(Guid)) {
...
} else {
throw new ArgumentException();
}
}
What is the purpose here? You say that string
/ Guid
etc. Were just examples, so I don't think we need to focus on those ...
If you just want to be able to manipulate the contents of the dictionary, then "done" already works. since it Dictionary<,>
is a reference type, the caller will already see any changes you make. You can also remove ref
...
public void GetData(Dictionary<T,V> dataDictionary) // or IDictionary<T,V>
{
T key = GetSomeKey();
V value = dataDictionary[key]; // query
dataDictionary.Remove(key); // mutate
}