Access data types in collections by reference

  • Thread starter Thread starter Mitja Semolic
  • Start date Start date
M

Mitja Semolic

// Example

public struct SomeData
{
public int X;
public int Y;

public SomeData(int x, int y)
{ ... }
}

....

Hashtable table = new Hashtable();
SomeData sd = new SomeData(1, 2)
table.Add(1, sd);


// this of course does not work, cause is passed by value
// but is there a way, or I need a class to encapsulate data types (stupid
solution)

((SomeData)table[1]).X = 2;
 
Mitja Semolic said:
// Example

public struct SomeData
{
public int X;
public int Y;

public SomeData(int x, int y)
{ ... }
}

...

Hashtable table = new Hashtable();
SomeData sd = new SomeData(1, 2)
table.Add(1, sd);


// this of course does not work, cause is passed by value
// but is there a way, or I need a class to encapsulate data types (stupid
solution)

((SomeData)table[1]).X = 2;

Well, you can do:

SomeData sd = (SomeData)table[1];
sd.X=2;
table[1]=sd;

I would seriously suggest considering using a class instead though. I
find the number of times when it's a good idea to define my own value
types is very small indeed.
 
Back
Top