Michael Tot Korsgaard
Michael Tot Korsgaard

Reputation: 4014

Array with two classes

Hi im doing a school assignment, and I need to convert this JAVA code to C#

private Map<ItemID, ProductDescription> descriptions = new HashMap()<ItemID, ProductDescription>;

Is it possible to make a straight conversion?

I've already decided to make ItemID into an int, and ProductDescription is a class.

Upvotes: 0

Views: 127

Answers (7)

IvoTops
IvoTops

Reputation: 3531

private Dictionary<ItemID, ProductDescription> descriptions = new Dictionary<ItemID, ProductDescription>();

The hasmap indeed allows for one null key entry. In the (rare?) case you would need this I'd simply create a special ItemID and use that for the null key.

You could ofcourse make a dictionary descendant with null key support, but that would be overdoing it imho ;-)

Upvotes: 1

Jodrell
Jodrell

Reputation: 35716

This is a good match but,

private IDictionary<ItemID, ProductDescription> descriptions
    = new Dictionary<ItemID, ProductDescription>();

Note

HashMap will accept null key values, where as Dictionary will not.

If you really want to support null key values, I'd like to see you reasoning before attempting a perfect .Net HashMap implementation.

Upvotes: 0

mihirj
mihirj

Reputation: 1219

Yes, of course you can. Please look into following examples:

IDictionary<int, string> h = new Dictionary<int, string>();
            h.Add(1, "a");
            h.Add(2, "b");
            h.Add(3, "c");

SortedList<int, string> s = new SortedList<int, string>();
            s.Add(1, "a");
            s.Add(2, "b");

I think this is what you are looking for.

Upvotes: 1

Lews Therin
Lews Therin

Reputation: 10995

There are many options.

There is an

Hashtable in C#

KeyValuePair So it can be List<KeyValuePair<T,U>>

Dictionary //Preferred

Upvotes: 0

Chathuranga Chandrasekara
Chathuranga Chandrasekara

Reputation: 20906

Yes, You can do the conversion using a Dictionary instead of HashMap. And of course it is more effective to get the idea of each code segment and convert. Trying to convert line by line is not recommended since you may miss a better way that can be used to resolve the problem.

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460138

You could use a Dictionary<int, ProductDescription> instead.

Dictionary<TKey, TValue> Class

Represents a collection of keys and values. The key must be unique.

Upvotes: 1

Jon
Jon

Reputation: 437386

Yes, just replace HashMap with Dictionary. You might want to type the variable as an IDictionary (in the same spirit as the Java code), but that's not strictly necessary.

Upvotes: 0

Related Questions