Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# new class with only single property : derive from base or encapsulate into new?

I've tried to be descriptive :) It's rather programming-style problem than coding problem in itself.

Let's suppose we have :

A:

public class MyDict {
     public Dictionary<int,string> dict;
     // do custom-serialization of "dict"
     public void SaveToFile(...);
     // customized deserialization of "dict"
     public void LoadFromFile(...);
} 

B:

public class MyDict : Dictionary<int,string>
{

}

Which option would be better in the matter of programming style ? class B: is to be de/serialized externally.

Main problem is : is it better to create new class (which would have only one property - like opt A:) or to create a new class derived - like opt B: ? I don't want any other data processing than adding/removing and de/serializing to stream.

Thanks in advance!

like image 761
Gobol Avatar asked Jan 22 '23 10:01

Gobol


2 Answers

Why do you need to create a new class at all? Or rather, why does it have to be a class which can load and save itself? Why not have methods elsewhere of:

public void SaveDictionary(Dictionary<int, string> dictionary, string fie)

public Dictionary<int, string> LoadDictionary(string file)
like image 160
Jon Skeet Avatar answered Jan 24 '23 22:01

Jon Skeet


I would go for option B. I would only use Option A if I wanted to use the Dictionary behind the scenes (ie. make it private/protected) and only expose a limited amount of functionality from the Dictionary in my new class.

If you are offering all of the functionality if the Dictionary and then some, the obvious solution would be inheriting from Dictionary (a la Option B)

like image 26
FallenAvatar Avatar answered Jan 25 '23 00:01

FallenAvatar