c# - Unexpected error on templated function argument: "cannot convert from 'ref T' to 'ref byte'" -
i have test class:
class test { void x(ref byte v) { } void x(ref sbyte v) { } void x<t>(ref t[] a) t: byte, sbyte { (int = 0; < a.length; ++i) x(ref a[i]); } } in error list window, getting error
"argument 1: cannot convert
ref t'ref byte' on linex(ref a[i]);"
intellisense displaying different message on line: "the best overloaded method match 'test.x(ref byte)' has invalid arguments". ideas why?
i tried this, rather writing explicit overloads every array type because actual code has 20 different "x" routines 'scalar' types , didn't want 20 more functions.
good call on multiple constraints being 'anded', not 'ored', got same error without constraint.
i understand why 'ref' in third overload not needed, interface may reallocate array , need ref.
by way: right in thinking constraint "struct" match valuetype, including primitive types?
here code stands now, same error:
class test { void x(ref byte v) { } void x(ref sbyte v) { } void x<t>(t[] a) { (int = 0; < a.length; ++i) x(ref a[i]); } }
exact error message given roslyn is:
(8,34,8,38): error cs0701: 'byte' not valid constraint. type used constraint must interface, non-sealed class or type parameter. (8,40,8,45): error cs0701: 'sbyte' not valid constraint. type used constraint must interface, non-sealed class or type parameter. (11,18,11,22): error cs1503: argument 1: cannot convert 'ref t' 'ref byte' byte , sbyte not valid constrains generic parameter. in c# can use baseclass, interface, reference type, value type , new() constraints.
read this msdn article explains how use generic parameter constrains.
for really interested, third compilation message generated compiler because tried recover errors ignoring invalid constrain on parameter t. without constrains not safe use t byte.
Comments
Post a Comment