Defining Generics in Managed COBOL
*> Generic class
class-id Point3D using T.
*> With constraints
class-id Point3D using T.
constraints.
constrain T implements type IComputable.
*> Generic interface
interface-id IComputable using T.
*> Generic method
method-id MakePoint3D static public using T.
procedure division using by value
x as T y as T z as T
returning ret as type Point3D[T].
*> With constraints
method-id MakePoint3D static public using T.
constraints.
constrain T implements type IComputable.
*> Generic value type
valuetype-id container using T Y.
01 a T public.
01 b Y public.
end valuetype.
*> With constraints
valuetype-id container using T Y.
constraints.
constrain T implements type IComputable.
*> Generic iterator, use a parametrised class
class-id a using T.
iterator-id itg static.
01 val binary-long value 1.
procedure division using by value x as T yielding y as T.
perform until val = 50
add 1 to val
set y to x *> Just for example!
goback
end-perform
end iterator.
end class.
*> To use, parametrise the class
perform varying thg through type a[string]::itg("Dog")
display thg
end-perform
Defining Generics in C#
// Generic class
class Point3D<T>
// Generic class with constraints
class Point3D_c<T> where T : IComputable
// Generic interface
interface IComputable<T>
// Generic method
public static Point3D<T> MakePoint3D<T>(T x, T y, T z)
{
return new Point3D<T>(x, y, z);
}
// Generic method with constraints
public static void MakePoint3D<T>(T x, T y, T z) where T : IComputable
{
return new Point3D<T>(x, y, z);
}
// Generic value type
struct container<T, Y>
{
public T a;
public Y b;
}
// Generic value type with constraints
struct container<T, Y> where T : IComputable
// Generic iterator, use a parameterised class
class a<T>
{
public static IEnumerable<T> itg(T x)
{
int val = 1;
while (val < 50)
{
val++;
yield return x;
}
}
}
// Using generic iterator
foreach (string dog in a<string>.itg("Dog"))
System.Console.WriteLine(dog);