Compile-Time Constant Id

Default parameter for value must be a compile time constant?

DateTime.MinValue is not a const, because the language doesn't like const on DateTime. One option is to use DateTime? instead, i.e.

public static void DatesToPeriodConverter(DateTime start, DateTime? end = null,
out string date, out string time)
{
var effectiveEnd = end ?? DateTime.MinValue;
// ...
}

However, you will still have the issue of having non-default parameters after default parameters - you may need to re-order them to use that as a default.

Optional parameters must be a compile-time constant

No, the expression PersonRespository.ColumnID is not classified as a compile-time constant. The expression "ID" is, but that's not what you're using as the default parameter.

In particular, if ColumnID is "just a normal field" then any references to it will be resolved as a field - so if you compile an assembly which refers to the field, then change the value and rebuild the assembly containing PersonRepository, the referring assembly will see that change.

If you change your declaration to:

 public const string ColumnID = "ID";

then it is a compile-time constant expression. That means in our previous scenario, the value of the constant is baked into any code that refers to it - and changing the value later without recompiling that referring code won't change the value used by that referring code.

See section 7.19 of the C# 4 language specification for more details about what counts as a constant expression.

Why is typeid not compile-time constant like sizeof

When you are dealing with types, you'd rather use simple metaprogramming techniques:

#include <type_traits>

template <class T>
void Foo()
{
static_assert((std::is_same<T, int>::value || std::is_same<T, double>::value));
}

int main()
{
Foo<int>();
Foo<float>();
}

where is_same could be implemented like this:

template <class A, class B>
struct is_same
{
static const bool value = false;
};

template <class A>
struct is_same<A, A>
{
static const bool value = true;
};

typeid probably isn't compile-time because it has to deal with runtime polymorphic objects, and that is where you'd rather use it (if at all).

What does compile time 'const' mean?

It just means that every instance of the member marked as const will be replaced with its value during compilation, while readonly members will be resolved at run-time.

Compile time generated constant type ID

Putting aside the question of the wisdom of a design that requires comparing type for equality, you can do that with typeid. No need to write your own. Base* a and Base* b point to objects that have the same derived type if typeid(*a) == typeid(*b).



Related Topics



Leave a reply



Submit