C
C#16mo 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
Moods16mo ago
Uh That’s because myData can’t be converted to a Dictionary<string, Data>
r2d25551
r2d25551OP16mo ago
How would I fix it? c++ we use templates. . . And I was trying similar here.
Thinker
Thinker16mo 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
r2d25551OP16mo ago
Oh.
Moods
Moods16mo ago
Is that interface covariant? The more you know
r2d25551
r2d25551OP16mo ago
Okay, thank you for letting me. My syntax is correct then?
Thinker
Thinker16mo ago
(I think so at least) syntax is all fine
MODiX
MODiX16mo 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
Thinker16mo ago
well nevermind then I guess
Moods
Moods16mo ago
Why isn’t it though
Moods
Moods16mo ago
Oh
r2d25551
r2d25551OP16mo ago
It does seem extremely limited.
Thinker
Thinker16mo ago
I mean, variance is variance :/ We fortunately don't have C++ templates 😄
r2d25551
r2d25551OP16mo 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
Accord16mo 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.
Want results from more Discord servers?
Add your server