"sizeof" in C#
-
I need to translate the following C++ code to C# for (int i = 0; i < sizeof(mnX)/sizeof(float); i++) { mnX[i] = 0f; } where (in C#) float[] mnX = new float[2]; Using this line as it is in C# results in a compile error which says that "sizeof" can be used only in an unsafe context. I changed the line to the following: for( int i = 0; i < System.Runtime.InteropServices.Marshal.SizeOf(mnX)/sizeof(float); i++ ) { mnX[i] = 0f; } which, of course, still results in the same error. My question is this: when I tried to use System.Runtime.InteropServices.Marshal.SizeOf(float), that resulted in a compile error as well. I don't want to wrap this block of code with the *unsafe* keyword and then compile using /unsafe. What would be my best option? Thanks! // Added 4:00PM PDT I guess I could just replace sizeof(float) with 4. Still, just for the sake of knowing how, I'd like to know how to get around the problem. ;)
-
I need to translate the following C++ code to C# for (int i = 0; i < sizeof(mnX)/sizeof(float); i++) { mnX[i] = 0f; } where (in C#) float[] mnX = new float[2]; Using this line as it is in C# results in a compile error which says that "sizeof" can be used only in an unsafe context. I changed the line to the following: for( int i = 0; i < System.Runtime.InteropServices.Marshal.SizeOf(mnX)/sizeof(float); i++ ) { mnX[i] = 0f; } which, of course, still results in the same error. My question is this: when I tried to use System.Runtime.InteropServices.Marshal.SizeOf(float), that resulted in a compile error as well. I don't want to wrap this block of code with the *unsafe* keyword and then compile using /unsafe. What would be my best option? Thanks! // Added 4:00PM PDT I guess I could just replace sizeof(float) with 4. Still, just for the sake of knowing how, I'd like to know how to get around the problem. ;)
If I understand your code correctly, really all you're trying to do is loop for each element in your array. In C#, the number of elements within an array is stored within the "Length" property. You could do something like this, then: for(int i = 0; i < minX.Length; i++) ... You could do it using sizeof, as you've already discovered, but I don't think there's a way around doing that without marking the code as unsafe.
-
If I understand your code correctly, really all you're trying to do is loop for each element in your array. In C#, the number of elements within an array is stored within the "Length" property. You could do something like this, then: for(int i = 0; i < minX.Length; i++) ... You could do it using sizeof, as you've already discovered, but I don't think there's a way around doing that without marking the code as unsafe.
John, thanks for the reply. I was wondering if I could just use mnX.Length myself. It definitely seems more elegant.