A C# Primer for RPG Programmers

  • 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:



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 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



Support MC Press Online





  • White Paper: Node.js for Enterprise IBM i Modernization

    SB Profound WP 5539

    If your business is thinking about modernizing your legacy IBM i (also known as AS/400 or iSeries) applications, you will want to read this white paper first!

    Download this paper and learn how Node.js can ensure that you:
    - Modernize on-time and budget - no more lengthy, costly, disruptive app rewrites!
    - Retain your IBM i systems of record
    - Find and hire new development talent
    - Integrate new Node.js applications with your existing RPG, Java, .Net, and PHP apps
    - Extend your IBM i capabilties to include Watson API, Cloud, and Internet of Things

    Read Node.js for Enterprise IBM i Modernization Now!


  • Profound Logic Solution Guide

    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 companyare not aligned with the current IT environment.

    Get your copy of this important guide today!


  • 2022 IBM i Marketplace Survey Results

    Fortra2022 marks the eighth edition of the IBM i Marketplace Survey Results. Each year, Fortra captures data on how businesses use the IBM i platform and the IT and cybersecurity initiatives it supports.

    Over the years, this survey has become a true industry benchmark, revealing to readers the trends that are shaping and driving the market and providing insight into what the future may bring for this technology.

  • Brunswick bowls a perfect 300 with LANSA!

    FortraBrunswick is the leader in bowling products, services, and industry expertise for the development and renovation of new and existing bowling centers and mixed-use recreation facilities across the entertainment industry. However, the lifeblood of Brunswick’s capital equipment business was running on a 15-year-old software application written in Visual Basic 6 (VB6) with a SQL Server back-end. The application was at the end of its life and needed to be replaced.
    With the help of Visual LANSA, they found an easy-to-use, long-term platform that enabled their team to collaborate, innovate, and integrate with existing systems and databases within a single platform.
    Read the case study to learn how they achieved success and increased the speed of development by 30% with Visual LANSA.


  • Progressive Web Apps: Create a Universal Experience Across All Devices

    LANSAProgressive Web Apps allow you to reach anyone, anywhere, and on any device with a single unified codebase. This means that your applications—regardless of browser, device, or platform—instantly become more reliable and consistent. They are the present and future of application development, and more and more businesses are catching on.
    Download this whitepaper and learn:

    • How PWAs support fast application development and streamline DevOps
    • How to give your business a competitive edge using PWAs
    • What makes progressive web apps so versatile, both online and offline



  • The Power of Coding in a Low-Code Solution

    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:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks



  • Why Migrate When You Can Modernize?

    LANSABusiness 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.
    In this white paper, you’ll learn how to think of these issues as opportunities rather than problems. We’ll explore motivations to migrate or modernize, their risks and considerations you should be aware of before embarking on a (migration or modernization) project.
    Lastly, we’ll discuss how modernizing IBM i applications with optimized business workflows, integration with other technologies and new mobile and web user interfaces will enable IT – and the business – to experience time-added value and much more.


  • UPDATED: Developer Kit: Making a Business Case for Modernization and Beyond

    Profound Logic Software, Inc.Having trouble getting management approval for modernization projects? The problem may be you're not speaking enough "business" to them.

    This Developer Kit provides you study-backed data and a ready-to-use business case template to help get your very next development project approved!

  • What to Do When Your AS/400 Talent Retires

    FortraIT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators is small.

    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:

    • Why IBM i skills depletion is a top concern
    • How leading organizations are coping
    • Where automation will make the biggest impact


  • Node.js on IBM i Webinar Series Pt. 2: Setting Up Your Development Tools

    Profound Logic Software, Inc.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. In Part 2, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Attend this webinar to learn:

    • Different tools to develop Node.js applications on IBM i
    • Debugging Node.js
    • The basics of Git and tools to help those new to it
    • Using as a pre-built development environment



  • Expert Tips for IBM i Security: Beyond the Basics

    SB PowerTech WC GenericIn this session, IBM i security expert Robin Tatam provides a quick recap of IBM i security basics and guides you through some advanced cybersecurity techniques that can help you take data protection to the next level. Robin will cover:

    • Reducing the risk posed by special authorities
    • Establishing object-level security
    • Overseeing user actions and data access

    Don't miss this chance to take your knowledge of IBM i security beyond the basics.



  • 5 IBM i Security Quick Wins

    SB PowerTech WC GenericIn today’s threat landscape, upper management is laser-focused on cybersecurity. You need to make progress in securing your systems—and make it fast.
    There’s no shortage of actions you could take, but what tactics will actually deliver the results you need? And how can you find a security strategy that fits your budget and time constraints?
    Join top IBM i security expert Robin Tatam as he outlines the five fastest and most impactful changes you can make to strengthen IBM i security this year.
    Your system didn’t become unsecure overnight and you won’t be able to turn it around overnight either. But quick wins are possible with IBM i security, and Robin Tatam will show you how to achieve them.

  • Security Bulletin: Malware Infection Discovered on IBM i Server!

    SB PowerTech WC GenericMalicious programs can bring entire businesses to their knees—and IBM i shops are not immune. It’s critical to grasp the true impact malware can have on IBM i and the network that connects to it. Attend this webinar to gain a thorough understanding of the relationships between:

    • Viruses, native objects, and the integrated file system (IFS)
    • Power Systems and Windows-based viruses and malware
    • PC-based anti-virus scanning versus native IBM i scanning

    There are a number of ways you can minimize your exposure to viruses. IBM i security expert Sandi Moore explains the facts, including how to ensure you're fully protected and compliant with regulations such as PCI.



  • Encryption on IBM i Simplified

    SB PowerTech WC GenericDB2 Field Procedures (FieldProcs) were introduced in IBM i 7.1 and have greatly simplified encryption, often without requiring any application changes. Now you can quickly encrypt sensitive data on the IBM i including PII, PCI, PHI data in your physical files and tables.
    Watch this webinar to learn how you can quickly implement encryption on the IBM i. During the webinar, security expert Robin Tatam will show you how to:

    • Use Field Procedures to automate encryption and decryption
    • Restrict and mask field level access by user or group
    • Meet compliance requirements with effective key management and audit trails


  • Lessons Learned from IBM i Cyber Attacks

    SB PowerTech WC GenericDespite the many options IBM has provided to protect your systems and data, many organizations still struggle to apply appropriate security controls.
    In this webinar, you'll get insight into how the criminals accessed these systems, the fallout from these attacks, and how the incidents could have been avoided by following security best practices.

    • Learn which security gaps cyber criminals love most
    • Find out how other IBM i organizations have fallen victim
    • Get the details on policies and processes you can implement to protect your organization, even when staff works from home

    You will learn the steps you can take to avoid the mistakes made in these examples, as well as other inadequate and misconfigured settings that put businesses at risk.



  • The Power of Coding in a Low-Code Solution

    SB PowerTech WC GenericWhen 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:

    • Discover the benefits of Low-code's quick application creation
    • Understand the differences in model-based and language-based Low-Code platforms
    • Explore the strengths of LANSA's Low-Code Solution to Low-Code’s biggest drawbacks



  • Node Webinar Series Pt. 1: The World of Node.js on IBM i

    SB Profound WC GenericHave 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.
    Part 1 will teach you what Node.js is, why it's a great option for IBM i shops, and how to take advantage of the ecosystem surrounding Node.
    In addition to background information, our Director of Product Development Scott Klement will demonstrate applications that take advantage of the Node Package Manager (npm).
    Watch Now.

  • The Biggest Mistakes in IBM i Security

    SB Profound WC Generic The Biggest Mistakes in IBM i Security
    Here’s the harsh reality: cybersecurity pros have to get their jobs right every single day, while an attacker only has to succeed once to do incredible damage.
    Whether that’s thousands of exposed records, millions of dollars in fines and legal fees, or diminished share value, it’s easy to judge organizations that fall victim. IBM i enjoys an enviable reputation for security, but no system is impervious to mistakes.
    Join this webinar to learn about the biggest errors made when securing a Power Systems server.
    This knowledge is critical for ensuring integrity of your application data and preventing you from becoming the next Equifax. It’s also essential for complying with all formal regulations, including SOX, PCI, GDPR, and HIPAA
    Watch Now.

  • Comply in 5! Well, actually UNDER 5 minutes!!

    SB CYBRA PPL 5382

    TRY 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.

    Request your trial now!

  • Backup and Recovery on IBM i: Your Strategy for the Unexpected

    FortraRobot automates the routine 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:
    - Simplified backup procedures
    - Easy data encryption
    - Save media management
    - Guided restoration
    - Seamless product integration
    Make sure your data survives when catastrophe hits. Try the Robot Backup and Recovery Solution FREE for 30 days.

  • Manage IBM i Messages by Exception with Robot

    SB HelpSystems SC 5413Managing messages on your IBM i can be more than a full-time job if you have to do it manually. 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:
    - Automated message management
    - Tailored notifications and automatic escalation
    - System-wide control of your IBM i partitions
    - Two-way system notifications from your mobile device
    - Seamless product integration
    Try the Robot Message Management Solution FREE for 30 days.

  • Easiest Way to Save Money? Stop Printing IBM i Reports

    FortraRobot 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:

    - Automated report distribution
    - View online without delay
    - Browser interface to make notes
    - Custom retention capabilities
    - Seamless product integration
    Rerun another report? Never again. Try the Robot Report Management Solution FREE for 30 days.

  • Hassle-Free IBM i Operations around the Clock

    SB HelpSystems SC 5413For over 30 years, Robot has been a leader in systems management for IBM i.
    Manage your job schedule with the Robot Job Scheduling Solution. Key features include:
    - Automated batch, interactive, and cross-platform scheduling
    - Event-driven dependency processing
    - Centralized monitoring and reporting
    - Audit log and ready-to-use reports
    - Seamless product integration
    Scale your software, not your staff. Try the Robot Job Scheduling Solution FREE for 30 days.