04
Mon, Nov
6 New Articles

A C# Primer for RPG Programmers

General
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

If you already "migrated" to ILE and free-format RPG, learning a modern programming language is easier than it was before. Why not learn C#?

 

This article is a first step in the path to C# mastery, from the perspective of an RPG programmer. You're probably wondering why you should learn C#. Well, this modern and very powerful programming language allows you to supplementor, in some situations, even replacepart of the development you'd do on an IBM i.

 

Many online forums provide help, either as simple samples of code or complete components that are ready to use just by plugging them into your project and writing a few lines of code. Instead of reinventing the wheel, there are plenty of "wheels" out there for nearly anything you can imaginefrom financial calculation to mobile application templates and everything in between.

 

You might argue the same could be said about Java. It's true, and the C#-versus-Java debate is as old as C# itself. For some tasks, C# is more adequate, while for others Java is a better fit. It might come as a surprise, but there are a lot of similarities between C# and RPG, as I'll show you in this article. Arguably, C# is easier to learn than Java, because C#'s "native" Integrated Development Environment (IDE), Visual Studio, provides rich editing features that go way beyond Java's IDEs and the language syntax is somewhat friendlier than Java's.

 

Some C#ontext: The .NET Framework

C# is one of the languages you can use in the .NET framework. This framework is, in a lot of ways, similar to IBM i's ILE. Here are a few common traits:

 

Programming Language Interoperability

They both provide interoperability between programming languages by "translating" code into an intermediary language. This allows programmers to use code written in another programming language, which they might not even be familiar with, in the program they're working on. While an ILE programmer can use code written in RPG, COBOL, C, C++, and CL, a .NET programmer can use code written in Microsoft's Visual Basic, Visual C#, Visual C++, and many other programming languages from various vendors. These include, among others, versions of COBOL, Perl, Eiffel, Python, Pascal, Salford FTN95 (Fortran), SmallTalk, and Dyalog APL tailored for the .NET Framework. A few years ago, even RPG was made available for the .NET framework, with the launch of ASNA's Visual RPG!

 

This interoperability is possible, in .NET's case, thanks to the Microsoft Intermediate Language (MSIL). This "managed code," as Microsoft calls it, runs on the Common Language Runtime, or CLR. CLR is the equivalent to ILE's heart or, if you're familiar with Java, a Java Virtual Machine.

 

Modular and Reusable Components

ILE allows you to create modules, programs, and service programs to organize your code. .NET implements the exact same concept with assemblies. And just like ILE, .NET provides a set of common tools available to all the supported languages, which allow the programmer to simplify tasks and save a lot of time. The difference is that .NET's tools go way beyond ILE's Common Runtime Services in their functionality and ease of use. A significant part of this ease of use is due to the fact that .NET's languages are object-oriented (OO). If you're not familiar with the concept, the next section will help you understand it. Learning what OO is and how it works is fundamental to learning C#.

 

What's This Object-Oriented (OO) Stuff Everybody Is Talking About?

We RPG programmers are used to procedural languages, in which the operations are isolated from the data they manipulate. In an object-oriented language, things are a bit different. To put it simply, data and the operations to manipulate it are parts of the same things, aptly named "objects." These objects intend to mimic real-world objects, thus facilitating the way code is written, stored, and understood. An object is built based upon a class, which is in some ways similar to a service program.

 

Let's look at an example to try to make this clearer. If you wanted to write a program to simulate the life of a horse, here's how you could do it:

 

Life of a Horse, RPG Version:

You'd create a file, where each record would represent a horse. This record format would contain fields like name, breed, date_of_birth, mile_ran, and other relevant information. Then you'd write a set of procedures to bring the horse to life: Change_Horse_Name, Set_Horse_Date_of_Birth, Make_Horse_Neigh, Make_Horse_Run, and so on. These procedures would receive the record, or part of it, as parameters and return something, depending on their purpose. Ideally, these procedures would reside in a service program so they could be easily reused.

 

Life of a Horse, Object-Oriented Version:

You'd define a Horse class (a kind of blueprint of what a horse is) with the data (here named properties or attributes) and the stuff you'd want for the horse (here called methods). In your program, you'd then create a new horse object (a "building" based on the blueprint). To make this new horse object do stuff, you'd just invoke its methods. For instance, to make it neigh, you'd write horse.neigh(), instead of neigh(horse).

 

The big difference is that while the data and procedures are isolated in the RPG version of things, the object's methods are part of the object. In a way, you can think of classes, with their data and code, like service programs. The thing is that, while RPG limits you to one "copy" of the service program per program, you can create as many "copies" of the object as you want in your program. This means that you can easily handle multiple similar things simultaneously, while keeping them totally independent from one another. You can write very specific code and "hide" it within an object, thus making sure it won't be used with the wrong parameters or in the wrong situation. In other words, by storing the code and the data inside the object, you make crystal clear what belongs where: the Horse's "neigh" method will never be applied to a Dog object, for instance.

 

Another big difference is the way you can easily derive and extend functionality in an object-oriented language. For instance, in a procedural language like RPG, if you want to build upon the existing functionality of a service program but you don't want the programs that currently use that service program to be affected, you'd have create a new service program, starting with the same modules and adding new ones, to extend the functionality. In an object-oriented language, you can simply create a class derived from an existing class, thus inheriting all of its data and functionality, while keeping a link to the original one. This inheritance operation is very simple to achieve; you just need to specify a keyword and the name of the parent class in the new class definition. You can still create objects based on both old and new classes without any risk. This is, in a brief and over-simplified way, the concept of inheritance. Object-oriented languages have a few additional fundamental concepts, abstraction, polymorphism, and encapsulation, which I won't be discussing at this time because they're a bit too weird for someone used to procedural languages.

 

Your First C# Program

There's much, much more to know about object-oriented programming languages, but I'm sure what you really want is to see C# in action. Let's dive into your first C# program! Naturally, it is the obligatory "Hello World!" program:

 

using System;

 

namespace MyFirstCSharpProgram

{

   class Program

   {

       static void Main(string[] args)

       {

           Console.WriteLine("A big Hello to the C# World from an RPG programmer!");

       }

   }

}

 

You'll notice a couple of similarities to free-format RPG: most lines of code end with a semicolon, and the methods take parameters just like RPG's procedures and functions. But other than that, it's…well, different. Let's analyze this code one instruction at a time and try to establish a comparison with RPG code.

 

The first line of code, using System;, tells the compiler that you're going to use or import something from a class named System. Remember, classes are more or less equivalent to service programs, so this can be compared to a /COPY line in which you import the prototypes for your service program's functions and procedures.

 

The following line defines the namespace MyFirstCSharpProgram. A namespace is a concept that doesn't have a match in RPG. The namespace keyword declares a scope that contains a set of related objects. It's used to organize code elements and to create globally unique types. You can have classes with the same name coexisting in the same project as long as they belong to different namespaces. The usefulness of this keyword will become more obvious when you dig deeper into C#.

 

Then comes what makes this program work: the definition of the class, with the line class Program, followed by curly braces ({ and }). These are C#'s equivalent to Begin and End. While in an RPG subroutine you'd use BegSr and EndSr to signal the beginning and end of a subroutine, in C# you use curly braces not only for signaling the beginning and end of a class, but for all the blocks of code: namespaces, classes, if statements, loops, everything. Without the proper indentation, this becomes really confusing really quick. Just like in free-format RPG, indentation is of paramount importance in C#.

 

After the class definition comes a method definition. In this particular case, it's the Main method, which will be the entry point of the program. When you create an ILE program, you need to tell the compiler which module is the entry pointor in other words, where the code is that makes the program startby running statements and calling procedures or functions from itself or other modules. In C#, this is achieved via the Main method: your project can have dozens of classes, but you'll need to tell the compiler where to begin. For the moment, let's ignore the static and void keywords and focus on the parameter definition of the method: (string[] args) defines an array of strings named "args." This array is represented here by the string keyword followed by the opening and closing square brackets ([ and ]). This is the same as a Char(<some number to represent the length>) Dim(<number of elements>) in an RPG procedure's prototype definition. While in RPG you need to indicate the number of elements, in C# you're allowed to define arrays and most data types without specifying their length. Just as in RPG, you can create an array of nearly all the existing data types. Let's get back to the method parameter definition: you can have multiple parameters, separated by commas and following the pattern <parameter type> <parameter name>. Similar to RPG, C# also has keywords designed to constraint the usage of the parameters, but let's leave that for later.

 

The next line of code, Console.WriteLine("A big Hello to the C# World from an RPG programmer!");, executes the WriteLine method of the Console object, passing the sentence as parameter or argument, as it's usually referred to in C#. Note that the Console object is not part of the language itself; it's one of the more than 4,000 objects the .NET framework provides to all the programming languages it supports. In order to use it, you need to tell the compiler where it comes from. That's what the first line of code, using System;, is doing there: it's telling the compiler where to look when it finds something that it doesn't recognize as part of the C# programming language. You can think of the using keyword as a hybrid of the /COPY statement and the binding directory, as it provides both the "prototype definition" and the location of a certain object.

 

The rest of the lines of code simply serve to close all the blocks of code, with properly indented curly braces. That's it, your first C# program! When you compile and run it, you get this output:

 

090915RafaelFig1

Figure 1: Press any key to continue…

 

Sorry for the Portuguese: it's simply the standard "Press any key to continue…" message.

 

Real C# programs are much more complex, but they follow a typical structure: they're composed of several classes and can import many others, designed by the programmer or downloaded from the Internet. One of the classes has a Main method, which is executed when the program is called. This is somewhat similar to an ILE program, which can have several modules and "import" others via the respective service programs. When the ILE program is compiled, the programmer indicates which module is the entry point (the equivalent to the Main method) to get the program running.

 

This simple program failed to illustrate the object creation, which is a core concept in any object-oriented programming language, but I tried to keep things as simple as possible for a first contact. There were several other important aspects that I had to leave out of this article, such as the tools to program in C# (Microsoft did a great job with Visual Studio, but there are other tools on the market that you might want to try) and the nitty-gritties of the language itself: how the instructions and their syntax work, how to handle data, how to build graphical user interfaces, and many other things.

 

Let me know in the Comments section below if you found this article useful and if you'd like to know more about C# from an RPG programmer's perspective. I might turn this topic into a running TechTip series, like RPG Academy and SQL 101!

Rafael Victoria-Pereira

Rafael Victória-Pereira has more than 20 years of IBM i experience as a programmer, analyst, and manager. Over that period, he has been an active voice in the IBM i community, encouraging and helping programmers transition to ILE and free-format RPG. Rafael has written more than 100 technical articles about topics ranging from interfaces (the topic for his first book, Flexible Input, Dazzling Output with IBM i) to modern RPG and SQL in his popular RPG Academy and SQL 101 series on mcpressonline.com and in his books Evolve Your RPG Coding and SQL for IBM i: A Database Modernization Guide. Rafael writes in an easy-to-read, practical style that is highly popular with his audience of IBM technology professionals.

Rafael is the Deputy IT Director - Infrastructures and Services at the Luis Simões Group in Portugal. His areas of expertise include programming in the IBM i native languages (RPG, CL, and DB2 SQL) and in "modern" programming languages, such as Java, C#, and Python, as well as project management and consultancy.


MC Press books written by Rafael Victória-Pereira available now on the MC Press Bookstore.

Evolve Your RPG Coding: Move from OPM to ILE...and Beyond Evolve Your RPG Coding: Move from OPM to ILE...and Beyond
Transition to modern RPG programming with this step-by-step guide through ILE and free-format RPG, SQL, and modernization techniques.
List Price $79.95

Now On Sale

Flexible Input, Dazzling Output with IBM i Flexible Input, Dazzling Output with IBM i
Uncover easier, more flexible ways to get data into your system, plus some methods for exporting and presenting the vital business data it contains.
List Price $79.95

Now On Sale

SQL for IBM i: A Database Modernization Guide SQL for IBM i: A Database Modernization Guide
Learn how to use SQL’s capabilities to modernize and enhance your IBM i database.
List Price $79.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: