Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
C# switch Gripe
Message
From
03/01/2009 09:54:57
 
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Title:
Miscellaneous
Thread ID:
01370558
Message ID:
01370828
Views:
40
>>>>Why in the world must a switch statement need an integer???
>>>>
>>>>Other languages are much more flexible in their CASE structures, so why would MS restrict the evaluation of the switch to an int????
>>>
>>>See Naomi's answer, but also be aware:
>>>
>>>If your trying to compare a switch statement to a VFP "DO CASE", they are very different. To write a VFP style case statement in C# use "else if" .
>>
>>Very different how? To me they seem quite similar. They are both structured as a series of checks of some value. When a match is found, take some action and exit. Both provide for a default action if no match is found.
>
>In VFP DO CASE you can put any condition, even function evaluation. In C# switch you analyze one variable.


You can simulate the vfp do case with a delegate
Disadvantage: all conditions are evaluated
Think I prefer the if - else if - else if
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GregoryAdam.Test
{
	public class CaseTest
	{
		public static void Main()
		{
			int result = 0;
			int a = 23, b = 27;

			Case.Execute
				(
				new CaseOne( a==1, () => { result = 1;}),
				new CaseOne( b==2, () => { result = 2;}), 
				// otherwise
				new CaseOne( true, () => { result = 99;}) 
				);

			Console.WriteLine("result = {0}", result);
			Console.ReadLine();
		}
	}

	public static class Case
	{
		public static void Execute(params CaseOne[] cases)
		{
			for( int i = -1; ++i < cases.Length; )
				if (cases[i].Condition)
				{
					cases[i].Act();
					break;
				}
		}
	}
	public class CaseOne
	{
		public bool Condition;
		public Action Act;

		public CaseOne(bool condition, Action act)
		{
			Condition = condition;
			Act = act;
		}
	}

}
Gregory
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform