When creating C# generic classes with static functions should the return type concreate class types?
For example:
And what about returning the same class from deserialization?
5 Replies
i'm unclear about the question?
you likely wouldn't have a
CreateMyData
which returns one specific definition of your generic class
so you could have
which would be entirely pointless because you can just do new MyClass<TKey, TValue>()
anywhere in your code without that Create
method
you probably need to constrain TKey
to notnull
, and your GetData
method is also pretty pointlessMakes sense.
That actually was my initial problem. My original design was from a C++ perspective. The return type could be derived from the baseclass. But that caused problems for the compiler. Now I am rewriting my code, hopefully, that can use the new desing in another class.
Dictionary<string, BaseClass> myData;
Dictionay<string, DerivedClass> myData;
.
And using an interface for Dictionary<string, BaseClass> GetData() { . . }
.
That caused problems for me. So now I am trying to write with generics. . . am I headed in the right direction?
you'll always have this problem when you work with dictionaries
all variations of dictionary have TKey and TValue as invariant
That would seem needed though. Almost like the compiler itself. C++ handles it differently.
I am going to make my changes and see what happens. Bottom line, I want my worker class processing these classes to deal with a common and reliable interface.
Thank you for the help. I will report back later of success or more problems 😄
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.