C
C#2y ago
r2d25551

✅ Return Proper Dictionary

At the moment my return value is null.
public class Data
{
}

public class MyData : Data
{
}

public interface IHelper
{
public Dictionary<string, T> GetDictionary<T>();
}

public class MyClass : IHelper
{
public Dictionary<string, MyData> myData = new Dictionary<string, MyData>();

public Dictionary<string, Data> GetDictionary<Data>()
{
return myData as Dictionary<string, Data>;
}
}
public class Data
{
}

public class MyData : Data
{
}

public interface IHelper
{
public Dictionary<string, T> GetDictionary<T>();
}

public class MyClass : IHelper
{
public Dictionary<string, MyData> myData = new Dictionary<string, MyData>();

public Dictionary<string, Data> GetDictionary<Data>()
{
return myData as Dictionary<string, Data>;
}
}
15 Replies
Moods
Moods2y ago
Uh That’s because myData can’t be converted to a Dictionary<string, Data>
r2d25551
r2d25551OP2y ago
How would I fix it? c++ we use templates. . . And I was trying similar here.
Thinker
Thinker2y ago
variance issue You can't convert a Dictionary<string, MyData> to a Dictionary<string, Data> even if MyData inherits from Data If you were using an IReadOnlyDictionary<string, Data> instead it would work.
r2d25551
r2d25551OP2y ago
Oh.
Moods
Moods2y ago
Is that interface covariant? The more you know
r2d25551
r2d25551OP2y ago
Okay, thank you for letting me. My syntax is correct then?
Thinker
Thinker2y ago
(I think so at least) syntax is all fine
MODiX
MODiX2y ago
Thinker
REPL Result: Failure
record Data {}
record MyData : Data {}

IReadOnlyDictionary<string, Data> dict = new Dictionary<string, MyData>();
record Data {}
record MyData : Data {}

IReadOnlyDictionary<string, Data> dict = new Dictionary<string, MyData>();
Exception: CompilationErrorException
- Cannot implicitly convert type 'System.Collections.Generic.Dictionary<string, MyData>' to 'System.Collections.Generic.IReadOnlyDictionary<string, Data>'. An explicit conversion exists (are you missing a cast?)
- Cannot implicitly convert type 'System.Collections.Generic.Dictionary<string, MyData>' to 'System.Collections.Generic.IReadOnlyDictionary<string, Data>'. An explicit conversion exists (are you missing a cast?)
Compile: 533.352ms | Execution: 0.000ms | React with ❌ to remove this embed.
Thinker
Thinker2y ago
well nevermind then I guess
Moods
Moods2y ago
Why isn’t it though
Moods
Moods2y ago
Oh
r2d25551
r2d25551OP2y ago
It does seem extremely limited.
Thinker
Thinker2y ago
I mean, variance is variance :/ We fortunately don't have C++ templates 😄
r2d25551
r2d25551OP2y ago
c# is not my strong suit. C++ is a different matter and would quite simple. Thank you both. I will keep looking at it and for another alternative.
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?