Home > Archive > C# > April 2006 > sizeof(T) for C# 2.0 generic classes
You are viewing an archived Text-only version of the thread.
To view this thread in it's original format and/or if you want to reply to
this thread please [click here]
| Author |
sizeof(T) for C# 2.0 generic classes
|
|
| Anatoli Koutsevol 2006-04-12, 7:02 pm |
| Is there some way to determine size in bytes
for a type parameter T in generic class cls<T>.
For instance, I need some generic way to covert
T [] array to an array of bytes and conversely,
as in BitConverter.GetBytes.
To create a buffer I'd like to have something like this
T [] srcData;
byte [] buffer = new byte[srcData.Length*sizeof(T)];
But it cannot be compiled in this syntax.
Any suggestions?
Thanks.
| |
| Randolpho 2006-04-13, 7:02 pm |
| Er... sizeof() only works on value types. What if T is a reference
type? The compiler can't handle that.
There's a better way to do this. If you're trying to seralize your
generic class, you should just mark it serializable and then use the
..NET seralization mechanisms. Then you don't have to roll your own
serialization, and the world is a better place. :)
| |
| Nils Petter Liadal 2006-04-18, 7:03 pm |
|
"Randolpho" <randolpho@gmail.com> skrev i melding
news:1144959782.586364.321170@v46g2000cwv.googlegroups.com...
> Er... sizeof() only works on value types. What if T is a reference
> type? The compiler can't handle that.
>
> There's a better way to do this. If you're trying to seralize your
> generic class, you should just mark it serializable and then use the
> .NET seralization mechanisms. Then you don't have to roll your own
> serialization, and the world is a better place. :)
Hi
I'm a real newbie to C#, but isn't it possible to constrain the generic
class to a value type? ('where T:struct') Then his code maybe would compile?
(if this is an utterly stupid question/suggestion; pls forgive me :-)
I think about something like this:
class GenericTestClass<T> where T: struct
Of course, then the class could be used only with value types, not with
reference types. Not so generic anymore, I know :-)
| |
| Randolpho 2006-04-19, 7:03 pm |
| You're right, you can constrain the types to value types, but I think
that sizeof() will still not work on a generic type.
|
|
|
|
|