Hashtable Question

A

aperrien

Hello all,
I'm learning C# from a C/C++ background, and I came across an odd
problem.

I have a hashtable that holds a string and a struct like so:

private Hashtable MyTable = new Hashtable();



public class MyData
{
public long int x,y,number;

public Tile( long int xx, long int yy, long int num )
{
x = xx;
y = yy;
number = num;

}
}


MyData DataPoint;

MyData.Add[SomeString,DataPoint];

----- More code ----

foreach(DictionaryEntry DataPoint in MyTable)
{

MyData D = (MyData)DataPoint.Value;


D.x = 10;
}

When I try to access the members of D, I get errors. Why?
Can't I use a hashtable to store struct or class elements like a C++
map?
 
B

Bill Butler

Hello all,
I'm learning C# from a C/C++ background, and I came across an odd
problem.

I have a hashtable that holds a string and a struct like so:

From your definition of MyData below, you have a class, not a struct.
class and struct have very different behavior in C#.
You will most likely want to keep this a class.

private Hashtable MyTable = new Hashtable();



public class MyData
{
public long int x,y,number;

public Tile( long int xx, long int yy, long int num )
{
x = xx;
y = yy;
number = num;

}
}


MyData DataPoint;

DataPoint is an unassigned reference (null)
Try
MyData DataPoint = new MyData(0,0,0);

MyData.Add[SomeString,DataPoint];

----- More code ----

foreach(DictionaryEntry DataPoint in MyTable)
{

MyData D = (MyData)DataPoint.Value;

This is probably where it is bombing.
- DataPoint is null
- MyData has no Value members

D.x = 10;
}

When I try to access the members of D, I get errors. Why?
Can't I use a hashtable to store struct or class elements like a C++
map?

It is generally a bad Idea to have public fields in your classes.
Try making the field private and adding public properties for set/get
functionality (if needed)


Many new C# developers that come from a C++ background trip all over
structs.
They should not be treated as lightweight classes the way they generally
are in C++.
Structs are very different critters from classes in C# and they have
many subtle gotchas.

I recommend sticking with classes until you understand all of the
differences.

Good luck
Bill
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top