Previous Topic Next topic Print topic


Functions, Methods - in COBOL and C#

Functions in Managed COBOL

method-id TestFunc.
procedure division using by value x as binary-long, 
                            by reference y as binary-long, 
                            output z as binary-long.
   add 1 to x, y
   move 5 to z
end method.
 
01 a binary-long value 1.
01 b binary-long value 1.
01 c binary-long.  *> c doesn't need initializing
 
    invoke self::TestFunc(value a reference b output c)
*> Or 
    invoke self::TestFunc(a b c)
    display a space b space c
 
*> sum is an intrinsic function in COBOL
01 total binary-long.
    set total to function sum(4 3 2 1) *> returns 10
 
*> To create a non intrinsic variable argument list function:
method-id MySum.
local-storage section.
01 i binary-long.
procedure division using params nums as binary-long occurs any
                   returning mysum as binary-long.
    perform varying i through nums
        add i to mysum
    end-perform
end method.
 
*> then to call it:
method-id main.
local-storage section.
01 i binary-long.
procedure division 
    set i to self::MySum(1 2 3 4)
    display i
end method.
 
*> COBOL doesn't support optional arguments/parameters.
*> Just create two different versions of the same function.  
method-id SayHello.
   procedure division using by value nam as string, prefix as string.
   display "Greetings, " prefix space nam
end method SayHello.
 
method-id SayHello.
   procedure division using by value nam as string.
   invoke self::SayHello(nam "")
end method.

Functions in C#

// Pass by value (in, default), reference (in/out),
// and reference (out)
void TestFunc(int x, ref int y, out int z) 
{
   x++;  
   y++;
   z = 5;
}
 
int a = 1, b = 1, c;  // c doesn't need initializing
TestFunc(a, ref b, out c);
Console.WriteLine("{0} {1} {2}", a, b, c);  // 1 2 5
 
 
 
 
 
// Accept variable number of arguments
int Sum(params int[] nums) 
{
  int sum = 0;
  foreach (int i in nums)
  {
      sum += i;
  }
  return sum;
}
 
int total = Sum(4, 3, 2, 1);   // returns 10
 
 
 
 
 
 
 
 
 
 
/* C# doesn't support optional arguments/parameters.  
   Just create two different versions of the same function. */  
void SayHello(string name, string prefix) 
{
   Console.WriteLine("Greetings, " + prefix + " " + name);
} 
 
void SayHello(string name) 
{ 
   SayHello(name, ""); 
}
Previous Topic Next topic Print topic