1

i have a windows application under visual studio 2010 c#

i create a class with name book with 3 fields (name, writingDate, author)

i create another class with name book that is a list of book (List<book>)

when i retrieve books class data i need to know its size in byte

how can i do that?

Note: i try Marshal.SizeOf(books) but this error occurred

"Type 'System.Collections.Generic.List`1[books]' cannot be marshaled as 
an unmanaged structure; no meaningful size or offset can be computed."

any help?

  • 2
    Now define "size in bytes" in this context... what are you expecting it to measure? The size of bytes used by the list? or...? Basically: what do you want to do with this number? – Marc Gravell Dec 31 '12 at 06:52
  • i fill books from data base, i need to know the size of books list after filling it from database to monitor its size –  Dec 31 '12 at 06:56
  • Why do you need to know that? Isn't the number of books sufficient? – zmbq Dec 31 '12 at 06:59
  • 1
    @danny well, the size of the books list is essentially 4*count or 8*count, depending on the platform... (x86 vs x64)... but I don't think that is helpful, and certainly isn't the number you are looking for. But then, unless you are measuring serialization, I'm not sure the question is meaningful. – Marc Gravell Dec 31 '12 at 07:00

1 Answers1

6

There's no good way of obtaining the size of the list in bytes. The main question is - what do you need the size for? Are you worried about memory consumption? Are you worried about network bandwidth when transferring the list somewhere?

If memory consumption worried you, you probably have many millions of book entries. In that case, I would expect loading times to be much more significant than anything else, so you may just load the list in parts and fix the memory problem altogether.

If it's network bandwidth, you need to serialize the list (basically convert it to a stream of bytes), then you can tell how long the stream is. When you stream it you'll choose (perhaps implicitly) the character encoding of the strings, which is probably the most important factor here.

zmbq
  • 38,013
  • 14
  • 101
  • 171
  • memory consumption is my problem. i need to know its size to monitor this. books is not the only list i try to get its size in bytes –  Dec 31 '12 at 07:11
  • Well, then, if you really have a memory problem (it rarely happens in 64-bit processes), you should look at .NET memory profilers. See here http://stackoverflow.com/questions/399847/net-memory-profiling-tools. – zmbq Dec 31 '12 at 07:25