Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a compile time constant function in C#

In C++, we can use macro or constexpr (as C++11 said). What can we do in C#?

Please see "Cannot declare..." comment for context:

static class Constant
{
    // we must ensure this is compile time const, have to calculate it from ground...
    public const int SIZEOF_TEXUTRE_RGBA_U8C4_640x480 = 4 * sizeof(byte) * 640 * 480;

    // Cannot declare compile time constant as following in C#
    //public const int SIZEOF_TEXUTRE_RGBA_U8C4_640x480_2 = 4 * PixelType._8UC4.PixelSize() * 640 * 480;
}

public static class PixelTypeMethods
{
    public static /*constexpr*/ int PixelSize(this PixelType type)
    {
        int value = (int)type;
        int unit_size = value & 0xFF;
        int unit_count = (value & 0xFF00) >> 8;
        return unit_count * unit_size;
    }
}

[Flags]
public enum PixelType
{
    RGBA_8UC4 = RGBA | _8U | _C4,

    /////////////////////////
    RGBA = 1 << 16,

    /////////////////////////
    _8UC4 = _8U | _C4,

    /////////////////////////
    _C4 = 4  << 8,

    /////////////////////////
    _8U = sizeof(byte)
}
like image 828
Raymond Avatar asked Apr 22 '13 09:04

Raymond


1 Answers

To declare a constant (const) the value assigned needs to be a compile time constant. Calling a method automatically makes it not a compile time constant.

The alternative is to use static readonly:

public static readonly int SIZEOF_TEXUTRE_RGBA_U8C4_640x480_2 =
    4 * PixelType._8UC4.PixelSize() * 640 * 480;
like image 62
Daniel Hilgarth Avatar answered Oct 20 '22 02:10

Daniel Hilgarth