Case (keyword)
From The Oxygene Language Wiki
This is a Language topic
Feel free to add your notes to this topic below.
The "case" statement
Case statements provide a convenient way to process different values contained in an ordinal value:
case status of 0: DoNothing; 1: DoMinor 2: DoDefault 3..7: DoMajor end;
This code is equivalent to:
if status=0 then DoNothing else if status=1 then DoMinor else if status=2 then DoMinor else if 3 <= status <= 7 then DoMajor end;
The else statement is optional and not necessary to test every possible value. Whenever possible the compiler will create a jump table.
Support for Strings
Delphi Prism also allows the testing of string values:
method TestApp.ProcessStatus(status: String); begin case status of 'urgent': DoUrgent; 'high': DoHigh; 'low': DoLow; else DoNormal; end; end;
The "case type" statement
As an expanded version of standard "case" statements, "case type" allows you to execute different code paths based on the type of the variable.
Example
case lMember type of CodeMemberField: GenerateField(...); CodeTypeConstructor: GenerateTypeConstructor(...); CodeConstructor: GenerateConstructor(...); CodeMemberMethod: GenerateMethod(...); CodeMemberEvent: GenerateEvent(...); CodeMemberProperty: GenerateProperty(...); CodeSnippetTypeMember: GenerateSnippetMember(...); else Output.WriteLine(lMember.Name+' '+lMember.GetType().Name); end;
The type checking is satisfied by the type or a descendant, so you need to be careful about the order of the statements.
Consider the following, where Employee is a descendant of Person:
case somebody type of Person: msg := msg_Person; Employee: msg := msg_Employee; end;
The above will never recognize an employee. The fix is simple, of course, just switch the order of the two statements.
Case Expressions
The case keyword can also be used in expressions. See Case Expressions for more information.
Notes
While in general most applications of "case type" are better handled by a proper polymorphic design of the class library at hand, there are cases where the design of the accessed library is outside of the developer's hands and the "case type" construct comes in handy.
Each block in the case statement allows a single statement (or begin/end to have multiple). The else block however allows multiple statements before end.
See Also
Area: Oxygene Language
Compiler version: Oxygene 5
Language Glossary — Keywords — Types — FAQ — How To