I'm trying to use Roslyn like a LinqPad, but I'm taking code snippets that are perfectly valid C# and are being told they are invalid. Consider this bog standard utility method.
public static class EnumConvert<TEnum, TUnderlying>
where TEnum : struct,IFormattable, IConvertible, IComparable
where TUnderlying : struct,IFormattable, IConvertible, IComparable, IComparable<TUnderlying>, IEquatable<TUnderlying>
{
public static readonly Converter<TEnum, TUnderlying> ToUnderlying;
public static readonly Converter<TUnderlying, TEnum> ToEnum =
Init(out ToUnderlying);
private static Converter<TUnderlying, TEnum> Init(out Converter<TEnum, TUnderlying> underlier)
{
if (Type.GetTypeCode(typeof(TEnum)) != Type.GetTypeCode(typeof(TUnderlying)) ||
typeof(TEnum) == typeof(TUnderlying))
{
throw new ArgumentException("TEnum does not derive from TUnderlying");
}
Func<TUnderlying, TUnderlying> Identity = x => x;
underlier = Delegate.CreateDelegate(typeof(Converter<TEnum, TUnderlying>), Identity.Method) as Converter<TEnum, TUnderlying>;
return Delegate.CreateDelegate(typeof(Converter<TUnderlying, TEnum>), Identity.Method) as Converter<TUnderlying, TEnum>;
}
}
Roslyn is claiming that it is invalid for me to call the out parameter for ToUnderlying
.
Before you ask me why I don't use a static constructor, I'd like to make sure I retain the beforefieldinit
class attribute on my class. Otherwise, I will be paying the cost for initializing it everytime the method is accessed. In C# this is considered valid but Roslyn is telling me that (6,76): error CS0199: A static readonly field cannot be passed ref or out (except in a static constructor)
It looks like you're simply hitting a bug in the Roslyn compiler in the CTP version you're using. The current (internal-to-Microsoft) build of Roslyn has no problems with that code.