I often use such a scheme.

I have a dictionary in which the value type is some basic type (the key type is not important), and the output method should return a specific subclass of this type. To get the value from the dictionary, I use the TryGetValue method. This method has an out parameter that has a dictionary value type. Accordingly, I need to declare a variable of this type and cast it at the output of the method.

Can I write something like:

 MyRetType value; my_dic.TryGetValue(myKey, out (MyBaseType)value); 

This option is not compiled.

  • Pull out first, then cast. - Acne
  • Acne is right, only for this you will have to implement implicit or explicit ghost statements of the parent class to the child class. - Specter
  • Acne, I do. Just hoping there is a way more poetic. - Modus

1 answer 1

A post by Eric Lippert explaining this behavior: " Why are there no alternative types in the ref and out parameters? ".