Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey guys I need you help, I am trying to get the size of a hashtable in c# but it doesn't seem to work out so well. In java you can do this by calling the size function.

Java
public int size() {
hashmap hasDataTable = new hashmap();           
int liSize = hashDataTable.size();
return liSize;
}


but since c# hastable does not have the size function, I tried this

C#
public int size() 
{
  hashTable Data = new hashTable();
  int liSize = sizeof(Data);
  return LiSize;
}


but Visual Studio woun't let me compile it saying "Data is a field but its being used as a type".

thanks for your help
Posted

Try int liCount = Data.Count.

Hope this helps,
Fredrik
 
Share this answer
 
Comments
rudolph098 23-Sep-13 10:11am    
it did. thanks
rudolph098 23-Sep-13 10:20am    
also how do I check if the hashtable is empty?
Fredrik Bornander 23-Sep-13 10:33am    
You can either check if .Count == 0 or, if you import Linq (using System.Linq;) you can use Data.Any() which returns true if it is NOT empty.
Its not really a valid concept here unless you are using unmanaged code. .NET has its own memory management system that can make objects larger in memory than the sum of their parts. Its not the same as in C++ where the size of an object in memory is really equal to the amount of data it contains.

You have 2 ways to do this, if you want to know the size of the hash table for unmanaged code, you can do:

C#
int sizeBytes = System.Runtime.InteropServices.Marshal.SizeOf(Data);


Which will give the size of the object if it were to be marshalled to unmanaged code. Its not really the size in memory.

The other option you have is to serialize it to a memory stream then read the size of the stream. This only works if the objects in your hash table are all serializable. You would have to iterate through it and serialize the objects (not the entire hash table itself since its not serializable).
 
Share this answer
 
Comments
rudolph098 23-Sep-13 10:23am    
very insightful. thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900