[Mono-list] new color.cs for inclusion in CVS

Brian Crowell brian@fluggo.com
Thu, 7 Mar 2002 13:22:50 -0600


> Casts are not checked either.  The only difference that you will get is
> that "unchecked" will disable the compile-time checking for overflows
> (that might happen inadvertently), the resulting code is the same
> cast-wise.
> 
> (Either that, or I have to fix a bug in mcs, so if we can actually pin
> point a problem, I would love to hear about this, because then I need to
> go fix mcs ;-)

See for yourself. Try compiling and running the code below.


======================================

using System;

namespace test
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class Class1
	{
		public struct Color
		{
			public byte a, r, g, b;
			
			public override string ToString()
			{
				return string.Format( "[{0},{1},{2},{3}]", a, r, g, b );
			}
		}
	
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			Color colorChecked, colorUnchecked, colorHouston;
			
			int packed = 0x12345678;
			
			// This code prints "Unchecked color: [18,52,86,120]"
			try
			{
				unchecked {
					colorUnchecked.a = (byte)(packed >> 24);
					colorUnchecked.r = (byte)(packed >> 16);
					colorUnchecked.g = (byte)(packed >> 8);
					colorUnchecked.b = (byte)(packed);
				}
				
				Console.WriteLine( "Unchecked color: {0}", colorUnchecked );
			}
			catch( Exception e )
			{
				Console.WriteLine( e.ToString() );
			}

			// This code causes a run-time System.OverflowException
			try
			{
				checked {
					colorChecked.a = (byte)(packed >> 24);
					colorChecked.r = (byte)(packed >> 16);
					colorChecked.g = (byte)(packed >> 8);
					colorChecked.b = (byte)(packed);
				}
				
				Console.WriteLine( "Checked color: {0}", colorChecked );
			}
			catch( Exception e )
			{
				Console.WriteLine( e.ToString() );
			}

			// This code will not compile:
			// colorHouston.a = ( packed & 0xff000000 ) >> 24;
			// colorHouston.r = ( packed & 0xff0000 ) >> 16;
			// colorHouston.g = ( packed & 0xff00 ) >> 8;
			// colorHouston.b = ( packed & 0xff );
				
			// This line will not compile:
			// int mask = 0xFF000000;
			
			// Nor will this:
			// checked { int mask = (int)0xFF000000; }
			
			// But this will:
			unchecked { int mask = (int)0xFF000000; }
			
			Console.ReadLine();
		}
	}
}