|
Delphi |
|
Function is just a part of code which can be called by its name. You can pass some parameters into function and then use the returned value. Returned result can be assigned to the function name or to special predefine result variable. The following declarations are identical:
function Cube(X: Double): Double;
begin
Cube:=X*X*X;
end;
function Cube(X: Double): Double;
begin
Result:=X*X*X;
end;
The function which returns nothing, called procedure:
procedure ShowScreenResolution;
begin
with Screen do ShowMessage(Format('Screen resolution is %dx%d'),[Width,Height]);
end;
As parameter you can pass value or reference to variable with var. Value can be passed also as const. Such parameter cannot be modified within function/procedure code. var parameters can be modified within the function/procedure code and its modified value will be saved after exit from routine:
procedure JustDemo(const A: Integer; B: Integer; var C: Integer);
begin
A:=B+C; < illegal code, you cannot modify the const parameter!
B:=A+C; // correct code, but the new value is available only in this procedure
C:=A+B; // the new C value will be saved after exiting this procedure
end;
|
|
C# |
|
There is no function and procedure reserved words, because all the functions must have parameters section with "()". Function without returned value must have void return type.
void ShowScreenResolution()
{
MessageBox.Show("Screen resolution: " + SystemInformation.PrimaryMonitorSize.ToString());
}
Parameters can be by default (value-type parameter) and by ref (reference-type parameter). Paremeters with ref can be modicifed inside and this value will be passed outside after function return. Also you can use out type. It works like ref, but it is used only for passing some values outside from the function body, so you don't need to initialize it before function call.
Retuned value defins with return keyword. The following example shows the function that modifies passed parameter, returns square by out parameter and cube by return value.
float AbsCube(ref float x, out float square)
{
x = Math.Abs(x);
square = x * x;
return square * x;
}
Please note that retunr assigns returned value and exits the function, so all the code after return will never call.
|
|
Useful out parameters. |
|
|
|
There is no predefined Result variable, so you have to create it yourself, if you need some manipulations with returned value before return. |
|
|
|
Do not forget that return immediately exits function. |
|
|
|
|
|
|
|
|
|
|
|