There are really two different mistakes in your approach here:
Dictionary<string, Stats>
is not the same as Dictionary<string, Dictionary<string, double>>
. It's wrong to think of Info
as inheriting Dictionary<string, Dictionary<string, double>>
. It inherits Dictionary<string, Stats>
, which is completely different.
- Even if you get the right base type, you cannot just go around casting any random instance of a base type to a derived type. See Convert/Cast base type to Derived type for one of the many existing Stack Overflow Q&A topics that discuss this.
Without a good Minimal, Complete, and Verifiable code example it's impossible to know for sure how your code works or what would be needed to get it to do what you want. But in your particular example, you might be able to declare an explicit conversion, which would be invoked when you use the cast operator.
For example:
public class Info : Dictionary<string, Stats>
{
public static explicit operator Info(Dictionary<string, Dictionary<string, double>> source)
{
Info result = new Info();
foreach (var kvp in source)
{
result.Add(kvp.Key, Stats.FromDictionary(kvp.Value));
}
return result;
}
}
where:
public class Stats : Dictionary<string, double>
{
public static Stats FromDictionary(Dictionary<string, double> source)
{
Stats result = new Stats();
foreach (var kvp in source)
{
result.Add(kvp.Key, kvp.Value);
}
return result;
}
}
Ideally, we'd like to be able to do something similar in Info
:
public class Stats : Dictionary<string, double>
{
public static explicit operator Stats(Dictionary<string, double> source)
{
Stats result = new Stats();
foreach (var kvp in source)
{
result.Add(kvp.Key, kvp.Value);
}
return result;
}
}
But this is a compiler error:
Stats.explicit operator Stats(System.Collections.Generic.Dictionary)': user-defined conversions to or from a base class are not allowed
This is addressed more thoroughly here: User-defined conversion operator from base class. The short version is that if the compiler allowed this, it would be ambiguous as to what the intent was if you tried to cast from a base reference to the derived reference. The language forces you to be explicit in this case.
Then the statement you want to use would work:
var test = (Info)data;
All that said, in the comments you wrote this:
the class is just to clean up code and use my class name instead of Dictionary<string, Dictionary<string, double>>
everywhere
If that's the case, then instead of inheritance, maybe you just want to use type name aliasing. For example:
using Stats = System.Collections.Generic.Dictionary<string, double>;
using Info = System.Collections.Generic
.Dictionary<string, System.Collections.Generic.Dictionary<string, double>>;
Then you can use the names Stats
and Info
interchangeably with Dictionary<string, double>
and Dictionary<string, Dictionary<string, double>>
, respectively.