Replies: 8 comments
-
Short story. Profiling allocations in my code the other day I noticed a few tens of thousands of allocations per second coming from So I tried a few different things, but the main alternative (casting to a number and trivially implementing the function by hand) ran into the issue of what number? Specifically, my enum is being source generated in an ECS implementation, and as you get more and more components the enum type increases in size ( So to sum things up, the main reason why generic math is extremely attractive for enums is two fold:
|
Beta Was this translation helpful? Give feedback.
-
@stephentoub I thought that ENum.HasFlag was already optimized? |
Beta Was this translation helpful? Give feedback.
-
It is in .NET Core in optimized code. If you're measuring startup allocations, you might still be looking at tier 0 / unoptimized code. |
Beta Was this translation helpful? Give feedback.
-
One of the use cases in Roslyn: Here we want a generic code that can and/or integer based flags enums. |
Beta Was this translation helpful? Give feedback.
-
Also wondering if the following generic specialization can be made possible: class OptionValueParser<T>
{
public bool TryParse(string str, out T value)
{
value = default;
if (typeof(T) == typeof(int))
{
if (int.TryParse(str, out var intValue))
{
value = (T)(object)intValue;
return true;
}
return false;
}
if (typeof(T) == typeof(string))
{
// ...
}
// ...
if (typeof(T).IsEnum)
{
if (Enum.TryParse<T>(str, out var enumValue)) // error: The type 'T' must be a non-nullable value type
{
value = (T)(object)enumValue;
return true;
}
return false;
}
return false;
}
} |
Beta Was this translation helpful? Give feedback.
-
@tmat, sounds like you want dotnet/csharplang#6308 |
Beta Was this translation helpful? Give feedback.
-
@tannergooding Yes, provided that |
Beta Was this translation helpful? Give feedback.
-
As far as I can tell from the thread, the compiler is behaving by-design with regards to current language rules. So I'll convert this issue to a discussion. |
Beta Was this translation helpful? Give feedback.
-
Background and Motivation
I was hoping that with static abstract interfaces, there would be a possibility to use generic constraints on Enums. It's useful e.g. for flag enums to set/unset a flag. Unfortunately, the compilator is not happy about the following code. Technically Enums are numbers, so in my opinion, it should be allowed.
Proposed API
Produced error
Beta Was this translation helpful? Give feedback.
All reactions