Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent for C++ const size_t in C#?

Tags:

c++

c#

I'm trying to translate some Ogre code to it's C# version and I ran into a problem :

    const size_t nVertices = 8;
    const size_t vbufCount = 3*2*nVertices;

    float vertices[vbufCount] = {
            -100.0,100.0,-100.0,        //0 position
            -sqrt13,sqrt13,-sqrt13,     //0 normal
            //... 
           -sqrt13,-sqrt13,sqrt13,     //7 normal
    };

Basically, const size_t doesn't exist in C#, and const int can't be used to declare array's size.

I was wondering how to declare arrays with a constant value?

like image 998
Greed Avatar asked Jan 14 '23 06:01

Greed


2 Answers

size_t is a typedef (kind of like a #define macro) which is basically an alias for another type. Its definition depends on the SDK, but it's usually unsigned int.

Anyway, in this case it doesn't really matter because they're constants, so you know that nVertices is 8 and vbufCount is 48. You can just write it like this in C#:

const int nVertices = 8;
const int vbufCount = 3 * 2 * nVertices;

float[] vertices = new float[vbufCount] {
    -100.0,100.0,-100.0,        //0 position
    -sqrt13,sqrt13,-sqrt13,     //0 normal
    //... 
    -sqrt13,-sqrt13,sqrt13,     //7 normal
    };
like image 172
user1610015 Avatar answered Jan 16 '23 20:01

user1610015


Basically, const size_t doesn't exist in C#, and const int can't be used to declare array's size.

That's not because of const int, but because array size is not part of the array type in C#. You can change your code into this:

float[] vertices = {
        -100.0f,100.0f,-100.0f,     //0 position
        -sqrt13,sqrt13,-sqrt13,     //0 normal
        //... 
       -sqrt13,-sqrt13,sqrt13,      //7 normal
};

There are also several other ways to do the same thing, including:

const int nVertices = 8;
const int vbufCount = 3*2*nVertices;

float[] vertices = new float[vbufCount] {
        -100.0f,100.0f,-100.0f,     //0 position
        -sqrt13,sqrt13,-sqrt13,     //0 normal
        //... 
       -sqrt13,-sqrt13,sqrt13,      //7 normal
};

The only difference is that if the number of items in the initializer doesn't match the number you specified, you will get a compile-time error.

like image 42
svick Avatar answered Jan 16 '23 21:01

svick