Bug 14289 - Casts to generic type parameters with type constraints fails
Summary: Casts to generic type parameters with type constraints fails
Alias: None
Product: Compilers
Classification: Mono
Component: C# ()
Version: unspecified
Hardware: Macintosh Mac OS
: --- normal
Target Milestone: ---
Assignee: Marek Safar
Depends on:
Reported: 2013-08-28 01:54 UTC by Leif Foged
Modified: 2013-08-30 05:51 UTC (History)
4 users (show)

Is this bug a regression?: ---
Last known good build:

Notice (2018-05-24): bugzilla.xamarin.com is now in read-only mode.

Please join us on Visual Studio Developer Community and in the Xamarin and Mono organizations on GitHub to continue tracking issues. Bugzilla will remain available for reference in read-only mode. We will continue to work on open Bugzilla bugs, copy them to the new locations as needed for follow-up, and add the new items under Related Links.

Our sincere thanks to everyone who has contributed on this bug tracker over the years. Thanks also for your understanding as we make these adjustments and improvements for the future.

Please create a new report on GitHub or Developer Community with your current version information, steps to reproduce, and relevant error messages or log files if you are hitting an issue that looks similar to this resolved bug and you do not yet see a matching new report.

Related Links:

Description Leif Foged 2013-08-28 01:54:31 UTC
Not sure if I'm filing this in the wrong place.

This program throws an InvalidCastException (it passes the test "input is TOut" even though input is 3 and TOut is System.Double).

This occurs on both my installed versions of Mono, 3.2.0 and 2.10.12.

class MainClass
	static class TypeConverter<TIn, TOut>
		where TIn : class
		where TOut : struct
		public static TOut Convert(TIn input) 
			if (input is TOut) 
				return (TOut)(object)input;
				throw new NotImplementedException ();

	public static void Main (string[] args)
		object x = 3;
		TypeConverter<object, double>.Convert (x);

Removing the 'where TOut : struct' constraint throws a NotImplementedException as expected.
Comment 1 Zoltan Varga 2013-08-29 22:59:05 UTC
This is an mcs bug. It prints:

bug.cs(11,23): warning CS0183: The given expression is always of the provided (`TOut') type
bug.cs(16,13): warning CS0162: Unreachable code detected

and it eliminates the conditional, thinking it is always true, leading to the runtime error.
Comment 2 Marek Safar 2013-08-30 05:51:04 UTC
Fixed in master