Prism Code Snippets Page
These Code Snippets are contributed by you (our online community members). They are organized by our knowledge base topics. Specifically, by the Prism sub-topics.
|
46 Delphi Prism Code Snippets
Group: Delphi Prism
Topic: Delphi Prism
|
1. Delphi Prism Assignment (:=) |
|
FullName: String; Age: Integer; FullName := "Randy Spitz"; Age := 38;
|
|
2. Delphi Prism Comments (// or { ... } or (* ... *)) |
|
Delphi uses // for a single line comment and both {} and (**) for multiple line comments. Although you can nest different types of multiple line comments, it is recommended that you don't. Commenting code generally has three purposes: to document your code,
for psuedo coding prior to coding, and to embed compiler directives.
Most languages support both a single line comment and a multiple line
comment. Some languages also use comments to give instructions to the
compiler or interpreter. A special comment. Delphi compiler
directives are in the form of {$DIRECTIVE}. Of interest for comments is
using the $IFDEF compiler directive to remark out code.
//This is a single line comment. { Multiple line comment. } (* This too is a multiple line comment. *) {$IFDEF TEMPOUT} //...code here {$ENDIF}
|
|
3. Delphi Prism Constants (const kPI: Double=3.1459;) |
|
In Prism, you define constants similar to how you define variables but use the Const keyword instead of the Var keyword. Specifying the type is optional. If you don't specify the type, the compiler chooses the most appropriate type for you.
Declare class constants as part of the class definitions. Declare local constants above the begin..end. Although Prism support inline variables, inline constants are not supported.
//Specified type: const kFeetToMeter: Double = 3.2808; kMeterToFeet: Double = .3048; kName: String = "Mike"; //Unspecified type: const kPIShort = 3.14;
|
|
4. Delphi Prism Development Tools |
|
Delphi.Net first shipped as a compiler only with Delphi 7. Delphi 8 is a .Net dedicated solution (no Win32) but was not clearly better than VS.Net so more developers moved to VS.Net and bypassed Delphi 8. Delphi for .Net shipped with Delphi 2005, 2006, and 2007 but languished because of a lack of development and VS.Net clearly implemented more .Net CLS features than Delphi for .Net. Delphi Prism (Oxygene) strives to keep pace and in some cases out pace C# and VB.Net using the Object Pascal language.
|
|
5. Delphi Prism Empty String Check (length) |
|
In Prism, a string can be nil (unassigned), assigned an empty string (""), or assigned a value. Therefore, to check if a string is empty, you have to check against both nil and (""). Alternatively, you can check the length of the string or use String.IsNullOrEmpty.
var s: String; if (s = nil) or (s = '') then MessageBox.Show("empty string");
or use length: if length(s) = 0 then MessageBox.Show("empty string");
|
|
6. Delphi Prism Event Handler |
|
The Delphi Prism
Most notable for Delphi developers is the fact that Prism does not offer initialization nor finalization sections.
|
|
7. Delphi Prism If Statement (if..else if..else) |
|
Notice in the more complete example that the semicolon for the begin..end block after end is not included. That tells the compiler something else is coming (the statement is not finished). Also note the semicolon is missing right before the final "else" statement.
//Complete example: if x = true then begin ShowMessage('x is true'); end Else If y = 'Mike' Then ShowMessage('hello mike') Else ShowMessage('last option');
|
|
8. Delphi Prism Member Events (event) |
|
Like all .Net languages, Prism events are a separate type of class member. You define a member event by using the event keyword. Events depend on Delegates to define the signature (the type) of the event they represent and they maintain a list of multiple subscribers - unlike in Delphi for Win32, where each event can only have one handler
|
|
9. Delphi Prism Variables (var x: Integer := 0;) |
|
Prism supports type inference where you just use a variable and
the compiler will then choose the lowest type possible (such as an Integer before a LongInt). With Prism, you frequently do not have to use commands to convert from one type to another. Variable names are not case sensitive. The Prism language offers both old-style declaring variables before the begin as well as inline variable declaration. Prism does support variable initialization too. Prism offers many variable types. Some common variable types include Integer, LongInt, Single, Double, Boolean, and String.
var FName: String; //This is old-style. begin FName := "Mike Prestwood"; MessageBox.Show(FName); Var Age: LongInt; //Local variables. Age:=36; MessageBox.Show(Fname + " is " + Age + " years old"); //Assign values too... Var Wife: String:="Lisa"; Var WifeAge: Integer:=32; messagebox.Show(wife + " is " + Wifeage + "."); end;
|
Topic: Tool Basics
|
10. Delphi Prism Deployment Overview |
|
Prism projects require the .Net framework and any additional dependencies you've added such as Crystal Reports.
In Visual Studio.Net, you can create a Setup and Deployment project by using any of the templates available on the New Project dialog (Other Project Types).
Prism doesn't directly support ClickOnce. At least not yet. In other words, there isn't a Security tab on the solution properties dialog. To create a ClickOnce deploy package, search the internet for mage.exe and mageui.exe.
In addition, you can use any of the many free and commercially available installation packages.
|
Topic: Language Basics
|
11. Delphi Prism Case Sensitivity (No) |
|
Prism is generally not case sensitive. Commands and variable names are not case sensitive.
Note: Prism (and Delphi for .Net) do not automatically match your typed case with the defined case as C# and VB.Net do within the Visual Studio Shell.
The following demonstrates command and variable case insensitiviy. var FullName: String; begin fullname := 'Mike Prestwood'; MessageBox.Show(fullNAME); MESSAGEBOX.SHOW(FULLNAME); messAGEbox.sHow(fullname); end;
|
|
12. Delphi Prism Code Blocks (begin..end) |
|
Same as in Delphi for Win32 but Prism also supports inline variable declaration.
function DoSomething : integer; var a, b : integer; begin a := 1; b := 2; var c : integer; //Prism allows inline (local) variables. c := a + b; result := c; end;
|
|
13. Delphi Prism Comparison Operators (=, <>) |
|
//Does Prism evaluate the math correctly? No! //This is different than later versions of //Delphi that muse MaxSingle in math.pas. If .1 + .1 + .1 = .3 Then MessageBox.Show("correct") Else MessageBox.Show("not correct");
|
|
14. Delphi Prism Custom Routines (method, procedure, function) |
|
In Prism, everything is within a class (just like with C#, VB.Net, and Java). So you create class methods using the method keyword. Alternatively, you can use procedure or function if you want the compiler to enforce returning or not returning a value.
method Form1.IntroduceYourself; begin MessageBox.Show("Hello, I do not have a name yet."); end; procedure Form1.SayHello(pName: String); begin MessageBox.Show("Hello " + pName); end; function Form1.Add(p1, p2 : Double): Double; begin Result := p1 + p2; end;
|
|
15. Delphi Prism End of Statement (;) |
|
Object Pascal uses a semicolon ";" as an end of statement specifier and you can put multiple statements on a single line of code and put a single statement on two or more code lines if you wish.
MessageBox.Show("Hello1"); MessageBox.Show("Hello2"); MessageBox.Show("Hello3"); //Same line works too:
MessageBox.Show("Hello4"); MessageBox.Show("Hello5"); //Two or more lines works too: MessageBox.Show ("Hello6");
|
|
16. Delphi Prism File Extensions |
|
Common or primary file extensions used (not a complete list, just the basics). Delphi Prism common source code file extensions include:
- .SLN - Solution File.
- .Oxygene
- Project File. Contains project specific information but this is not
the Delphi-like project file Delphi developers are used to. This is the
VS.Net project file.
- Program.pas - This is
the Delphi-like .dpr project-equivalent file and contains the Main
method.
- .pas - Delphi Prism source file (same extension as Delphi for Win32).
- .Designer.pas - Prism form file (a text resource file).
|
|
17. Delphi Prism Literals (quote or apostrophe) |
|
A value directly written into the source code of a computer program (as opposed to an identifier like a variable or constant). Literals cannot be changed. Common types of literals include string literals, floating point literals, integer literals, and hexidemal literals. Literal strings are usually either quoted (") or use an apostrophe (') which is often referred to as a single quote. Sometimes quotes are inaccurately referred to as double quotes. Languages Focus: LiteralsIn addition to understanding whether to use a quote or apostrophe for string literals, you also want to know how to specify and work with other types of literals including floating point literals. Some compilers allow leading and trailing decimals (.1 + .1), while some require a leading or trailing 0 as in (0.1 + 0.1). Also, because floating point literals are difficult for compilers to represent accurately, you need to understand how the compiler handles them and how to use rounding and trimming commands correctly for the nature of the project your are coding. Delphi Prism LiteralsIn Prism, you use either quotes or apostrophes for string literals.
Different than Delphi, you can start floating point literals with a decimal or an integer. For example, to specify a fractional floating point literal between 1 and -1, you can preceed the decimal with a 0 or not. x := .1 + .1; //Does work. x := 0.1 + 0.1; //Does work.
MessageBox.Show('Hello'); MessageBox.Show("Hello"); //Example of embedding quotes and apostropes: MessageBox.Show('He said, "Who''s computer?"'); MessageBox.Show("She said, ""Mike's computer"".");
|
|
18. Delphi Prism Logical Operators |
|
Prism logical operators:
and |
and, as in this and that |
or |
or, as in this or that |
not |
Not, as in Not This |
xor |
either or, as in this or that but not both |
//Given expressions a, b, c, and d: if Not (a and b) and (c or d) then //Do something.
|
|
19. Delphi Prism Overview and History |
|
Language Overview: Prism is a type safe language and a fully OOP language (no global functions or variables except for a very special __Global class). You code using a fully OOP approach (everything is in a class) but you have the additional benefit of a hybrid language using a special __Global class. Prism targets the .Net CLR and Mono. Based on Borland's original work with Delphi.Net and the continued by RemObjects as Oxygene, and now co-developed by CodeGear and RemObjects.
Target Platforms: Delphi Prism is most suitable for creating any type of application that runs on the .Net platform. This includes desktop business application using WinForms and websites using WebForms.
|
|
20. Delphi Prism Parameters (var, const, out) |
|
Prism
allows parameters of the same type to be listed together, separated by
commas, and followed with a single data type (more params of different
data types can follow, after a semi-colon). The default for parameters is by value. For by reference, add var in front of the parameter. Prism also offers constant parameters where you add const in
front of the parameter. A constant parameter is like a local constant
or read-only parameter the compiler can optimize.
function Add(a, b: integer) : integer; begin Result := a + b; end; procedure ReplaceTime(var pDT: TDateTime; const pNewDT: TDateTime); begin end;
|
|
21. Delphi Prism Report Tools Overview |
|
For WebForm applications the client target is the browser (a
document interfaced GUI), a common solution is to simply output an HTML
formatted page with black text and a white background (not much control
but it does work for some situations). For WinForm applications Rave Reports and Crystal Reports are very popular with Delphi Prism and Delphi for .Net developers.
|
|
22. Delphi Prism String Concatenation (+) |
|
Unlike Delphi, Prism performs implicit casting. To concatenate two strings, a string to an integer, or a string to a floating point number, use the + operator. For example, to convert a floating point number to a string just concatenate an empty string to the number as in "" + 3.2.
var FirstName : String; var LastName : String; FirstName := 'Mike'; LastName := 'Prestwood'; ShowMessage('Full name: ' + FirstName + ' ' + LastName); //Implicit casting of numbers. // //This fails: //MessageBox.Show(3.3); // //This works: MessageBox.Show("" + 3.3);
|
|
23. Delphi Prism Unary Operators |
|
The Prism unary operators are:
var i: Integer := 1; Inc(i); MessageBox.Show("" + i); //Displays 2
|
Topic: Language Details
|
24. Delphi Prism Exception Trapping (try..except, try..finally) |
|
Use a try..except..end block to trap and process errors.
try var y: Integer; y := 0; y := 1/y; except MessageBox.Show("You cannot divide by zero."); end;
|
|
25. Delphi Prism Inlining (Automatic) |
|
In Prism, inlining is automatically done for you by the JIT compiler for all languages and in general leads to faster code for all programmers whether they are aware of inlining or not.
|
|
26. Delphi Prism Left of String (Substring) |
|
Delphi Prism Left of String
MessageBox.Show("Prestwood".Substring(0, 3));
|
|
27. Delphi Prism Overloading (implicit) |
|
Like Delphi, Prism supports overloading. However, Prism supports implicit overloading (no need for an overload keyword).
method MainForm.Add(a, b: integer): Integer; begin Result := a + b; end; method MainForm.Add(const msg: String; a, b: integer): String; begin Result := msg + (a + b); end;
|
|
28. Delphi Prism Pointers |
|
Although pointer data types in Prism coding are less important than in other languages such as C++, Prism does support developer defined pointers. Use the ^ operator to declare a pointer data type. Use the @ operator to return the current address of a variable.
In .Net managed coding the use of pointers is not safe because the garbage collector may move memory around. To safely use pointers, use the unsafe keyword. However, avoid unsafe code if possible.
|
Topic: OOP
|
29. Delphi Prism Abstraction (abstract, override) |
|
Prism supports abstract class members and abstract classes using the abstract keyword. An abstract class is a class with one or more abstract members and you cannot instantiate an abstract class. However, you can have additional implemented methods and properties. An abstract member is either a method (method, procedure, or function), a property, or an event in an abstract class. You can add abstract members ONLY to abstract classes using the abstract keyword. Alternatively, you can use the empty keyword in place of abstract if you wish to instantiate the abstract class.
Cyborg = public abstract class(System.Object) public //You can put "virtual; abstract;" //but it's implied with just "abstract;" method Speak(pMessage: String); abstract; method Walk; virtual; abstract; end; Series600 = public class(Cyborg) public procedure Speak(pMessage: String); override; procedure Walk; override; end;
|
|
30. Delphi Prism Base Class (System.Object) |
|
In Prism, the Object keyword is an alias for the base System.Object class and is the single base class all classes ultimately inherit from.
//Specify both namespace and class: Cyborg = class(System.Object) end; //Use Object keyword for System.Object. Cyborg = class(Object) end; //When none, default is System.Object. Cyborg = class end;
|
|
31. Delphi Prism Class Contracts (require, ensure) |
|
Prism supports class contracts with its require and ensure keywords. The require keyword is a pre condition that must be true when the method is called. The ensure keyword is a post condition that much be true when a method exits. With either, if the condition evaluates to false, then an assertion is generated.
They can be used to check for the validity of input parameters, results, or for the state of the object required by the method.
The require and ensure keywords will expand the method body to list the preconditions; both sections can contain a list of Boolean statements, separated by semicolons.
method Cyborg.Walk(pPace); require pPace > 0; pPace < 100;
begin ensure FEnergyLevel >= 10; end;
|
|
32. Delphi Prism Class Member Visibility Levels |
|
In Prism, you specify each class and each class member's visibility with a Class Member Visibility Level preceding the return type. Like Delphi, you group member declarations as part of defining the interface for a class in the Interface section of a unit.
Unlike Delphi, Prism supports a traditional OO approach to member visibility with additional .Net type assembly visibility. For example, private members are truly private to the class they are declared in. In Delphi for Win32, you use strict private for true traditional private visibility.
Prism also supports assembly and protected and assembly or protected which modify the visibility of protected members to include only descendants in the same assembly (and) or publicly accessible from assembly and descendant only outside (or). OO purist might object to assembly and protected and assembly or protected and I suggest you choose the traditional private, protected, and public as your first chose at least until you both fully understand them and have a specific need for them.
Cyborg = public class(System.Object) private //private properties, methods, etc. here. FName: String; protected //protected properties, methods, etc. here. assembly and protected //properties, methods, etc. here. assembly or protected //properties, methods, etc. here. public //properties, methods, etc. here. end;
|
|
33. Delphi Prism Class Members (static) |
|
The Strict keyword was introduced from the beginning (Delphi.Net preview that shipped with D7).
|
|
34. Delphi Prism Class..Object (class..end..new) |
|
Declare your class in the Interface section. Then implement the class in the Implementation section. To create an object instance, use the New keyword. Optionally, you can use Create for backword compatibility with Delphi if you turn it on in the compatibility options. Since Prism does have a garbage collector, you do not have to free the object. If you need to free either unmanaged resources or resources where "timing" is important, implement IDisposable and take control of freeing the object yourself using Dispose.
In the interface section: Cyborg = class(System.Object) public method IntroduceYourself(); end;
In the Implementation section: method Cyborg.IntroduceYourself(); begin MessageBox.Show("Hi, I do not have a name yet."); end;
On some event like a button click: var T1: Cyborg; begin T1 := New Cyborg; T1.IntroduceYourself; //No need to clean up with managed classes. //The garbage collector will take care of it. end;
|
|
35. Delphi Prism Constructors (constructor + class name) |
|
Prism uses unnamed constructor methods for constructors. Prism also supports a Create constructor method for backward compatibility with Delphi for Win32.
Cyborg = public class public constructor(); constructor(pName: String); end;
|
|
36. Delphi Prism Finalizer (finalize()) |
|
Unlike Delphi, Delphi Prism uses the .Net garbage collector to free managed object instances. Prism does not have nor need a true destructor.
In .Net, a finalizer is used to free non-managed objects such as a file or network resource. Because you don't know when the garbage collector will call your finalizer, Microsoft recommends you implement the IDisposable interface for non-managed resources and call it's Dispose() method at the appropriate time.
type Cyborg = class(IDisposable) private disposed: Boolean; method Dispose(disposing: Boolean); public method Dispose; finalizer Finalize; end;
|
|
37. Delphi Prism Inheritance (=class(ParentClass)) |
|
In Prism, like Delphi, you use the class keyword followed by the parent class in parens. If you leave out the parent class, your class inherits from System.Object.
In the following example, a terminator T-600 is-an android. Android = public class end; T-600 = public class(Android) end;
|
|
38. Delphi Prism Interfaces |
|
With Prism, you use the Interface keyword to define an interface and then you include one or more interfaces where you specify the single class inheritance (separated by commas).
//Interface section of unit. IHuman = public interface //Specify interface methods and properties here. end; TCyborg = public class end; TCyborgHuman = public class(TCyborg, IHuman) //Specify each here and implement in //implementation section. end;
|
|
39. Delphi Prism Member Field |
|
In Prism you can set the visibility of a member field to any visibility: private, protected, public, assembly and protected or assembly or protected. Prism supports the readonly modifier for member fields which is handy for constant like data. In this case, I chose not to preface my read-only member field with "F" so it's usage is just like a read-only property. Prism also support the class modifier (static data) for member fields. Delphi developers should notice the use of := to initialize a member field (in Delphi you use an =).
Cyborg = class(System.Object) private FSerialNumber: String:="A100"; public FCyborgName: String; FCyborgAge: Integer:=0;
class SeriesID: Integer:=100; readonly; end;
|
|
40. Delphi Prism Member Method (method, procedure, function) |
|
Prism uses the keyword method for member methods. Alternatively, you can use procedure or function if you want the compiler to make sure all functions return a value and all procedures do not.
In the interface section: Cyborg = class(System.Object) public method IntroduceYourself(); end;
In the Implementation section: method Cyborg.IntroduceYourself(); begin MessageBox.Show("Hi, I do not have a name yet."); end;
On some event like a button click: var T1: Cyborg; begin T1 := New Cyborg; T1.IntroduceYourself; end;
|
|
41. Delphi Prism Member Modifiers |
|
Prism supports a full suite of member modifiers. Prism virtuality modifiers are virtual, override, final, and reintroduce. Prism general modifiers are abstract, empty, async, external, locked, unsafe, implements, and iterator. Not all member types support all member modifiers. For example, member fields support only readonly and implements.
Cyborg = public class(System.Object) public method Speak(pMessage: String); virtual; end; Series888 = public class(Cyborg) public method Speak(pMessage: String); override; end;
|
|
42. Delphi Prism Member Property (property..read..write) |
|
Like Delphi, Delphi Prism uses a special property keyword to both get and set the values of properties. The read and write keywords are used to get and set the value of the property directly or through an accessor method. For a read-only property, leave out the write portion of the declaration.
You can give properties any visibility you wish (private, protected, etc). It is common in Delphi and Delphi Prism to start member fields with "F" ("FName" in our example) and drop the "F" with properties that manage member fields ("Name" in our example).
Cyborg = class(System.Object) private FCName: String; public property CyborgName: String read FCName write FCName; end;
|
|
43. Delphi Prism Overriding (virtual, override) |
|
Same as Delphi. In Prism, you specify a virtual method with the virtual keyword in a parent class and replace it in a descendant class using the override keyword. Call Inherited in the descendant method to execute the code in the parent method.
Robot = class(System.Object) public method Speak; virtual; end; Cyborg = class(Robot) public method Speak; override; end;
|
|
44. Delphi Prism Partial Classes (partial) |
|
Prism supports both partial classes and partial methods using the keyword partial. A partial method is an empty method defined in a partial class.
//Organize a large class in multiple files. T800 = partial class(Cyborg, IHuman); end;
T800 = partial class(ITalk); end;
//Partial methods too:� T800 = public partial class private method Walk; partial; empty; method Run; partial; empty; end;
|
|
45. Delphi Prism Polymorphism |
|
Prism supports the following types of polymorphism:
|
|
46. Delphi Prism Prevent Derivation (sealed, final) |
|
Same keywords as Delphi (sealed uses slightly different syntax). With Prism, use the sealed keyword before the class keyword to prevent a class from being inherited from and use the final keyword to prevent a method from being overridden.
type Robot = public sealed class(System.Object) public method Speak(pSentence: String); virtual; final; end;
|
|
|