Theme:
v
C# Primer

In order for you to better follow the demos and code samples included in this Web Site, let’s introduce C# and Visual Studio 2008 through a sample application.

A simple C# method

Here is a little example to make you become acquainted with C#.

Here is how you would translate the +/ APL operator in C#:

public double PlusRed(double[] values)
{
    double result = 0;
    for (int i = 0; i < values.Length; i++)
        result += values[i];
    return result;
}

Let’s explain the PlusRed C# method a bit: maybe the best way to explain it to an APL developer is to show its literal translation to APL:

    ∇ result←PlusRed values;i
[1]   result←0
[2]   :for i :in ⍳⍴values
[3]       result ← result + values[i]
[4]   :endfor
    ∇

First, PlusRed is the name of the method (similar to a function name in an APL workspace).

The PlusRed method accepts one argument which name is values but which is declared to be a vector (“array” in C#) of double. double is the data type and is the same as what we call floating point in APL; [] following double means that it is a one dimensional array. In C#, you must declare the data type of a variable before you can use the variable.

Similarly, the term double preceding PlusRed means that the result of the PlusRed method is a double.

The body of the method is everything included within the curly braces:

    double result = 0;
    for (int i = 0; i < values.Length; i++)
        result += values[i];
    return result;

We first declare a variable called result to be a double and initialize it to 0.

Then, there is a for loop in which we increment result by values[i], result += values[i]; being equivalent to: result = result + values[i];

Finally, we return the content of the result variable as the method result.

This little example may let you guess 2 things:

  1. First: the C# syntax is simple and easy to understand
  2. Second: it should be easy enough to rewrite most APL primitives as C# methods which you could directly use in your C# programs

A simple C# application in 18 easy steps

We now need to test our C# method: in order to do so, we will create a C# .Net application using Visual Studio 2008. We won’t have room to explain everything in detail here, but will just give you the basic steps and a few important information so that you get a flavor of how to create a C# .Net application.

Proceed as follows:

  1. Start: Visual Studio 2008 SP1
  2. Select: File/New/Project…
  3. Select Visual C# as the Project Type and Class Library as the Visual Studio Installed Template
  4. Enter: APL2000.Conf2008 as the project name

    CSharpPrimer1.jpg

  5. Click OK

    This creates a new .Net C# project called APL2000.Conf2008 including one class, by default named Class1. Visual Studio creates the code for your project and displays it:

    CSharpPrimer2.jpg

  6. Copy/Paste the C# PlusRed method code into Class1

    CSharpPrimer3.jpg

  7. Right click on Solution ‘APL2000.Conf2008’ in Solution Explorer and select Build Solution

    If you have not made any typo, the project should compile ok and the status bar should display: Build succeeded
    Congratulations: you have created your first C# DLL!

    You can find it on your hard disk in the following directory:

    C:\Documents and Settings\Eric Lescasse\My Documents\Visual Studio 2008\Projects\APL2000.Conf2008\APL2000.Conf2008\bin\Debug

    (replace Eric Lescasse by your User Name) and the DLL is named:

    APL2000.Conf2008.DLL

But how can we test our DLL?

A DLL is a non visual piece of code which may contain methods (similar to APL functions), properties and fields (similar to APL variables): if you want, a DLL is a bit like an APL workspace without any User Interface code. So, we now need to add a Form to our Solution in order to be able to test our DLL.

  1. Right Click on Solution ‘APL2000.Conf2008’ in Solution Explorer and select Add/New project…
  2. In the Add New Project dialog, be sure to select Windows Forms Application this time and Name the Project: APL2000.Conf2008.Test

    A new tab gets displayed containing the form you just added, in Design mode.

    CSharpPrimer4.jpg

  3. Drag 2 Label objects, a TextBox object and a Button object onto the Form1 form and position them as follows (also reduce the form height a bit):

    CSharpPrimer5.jpg

  4. Click on label1 so that it is selected and change its Text property (in the Properties pane at the bottom right of VS 2008) to: Values

    This change gets immediately reflected in the form.

    Click on button1 and change its Text property to: Compute

    Click on label2 and change its Text property to: Result:

    Also change its Font Size property to 14 and double click on False, next to Bold, to change it to True

    Your Form should now look as follows:

    CSharpPrimer6.jpg

    We will use this form to enter values in the TextBox and then will display the result of running PlusRed in the Result: label

  5. Right click on APL2000.Conf2008.Test in Solution Explorer and select Set as StartUp Project
  6. Right click on References in Solution Explorer, below APL2000.Conf2008.Test and select Add Reference…

    The Add Reference dialog takes a few seconds to get displayed.

    Select the Browse tab, and navigate to the APL2008.Conf2008/Bin/Debug directory

    Double click on the APL2000.Conf2008.DLL

    It’s now time to write some code in order to have a real functional application.

    We need to handle a Click event on the Compute button.

  7. Double click on the Compute button

    This creates an empty event handler for the Click event on the Compute button and displays it in the Form1.cs tab:

    CSharpPrimer7.jpg

  8. Before you can use the APL2000.Conf2008 Class1 class in your Form you need to do 3 things.

    Add the following using statement to the top of Form1.cs:

    using APL2000.Conf2008;
    

    Add the following statement just above public Form1():

    private Class1 apl;
    

    Add the following statement just below InitializeComponent();:

    apl = new Class1();
    

    Your code should now look like this:

    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using APL2000.Conf2008;
    
    namespace APL2000.Conf2008.Test
    {
        public partial class Form1 : Form
        {
            private Class1 apl;
    
            public Form1()
            {
                InitializeComponent();
                apl = new Class1();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
            }
        }
    }
    

    We are now ready to write code for our application, in the button1_Click event handler.

    We need to read the content of the textBox1 TextBox: this is supposed to be a list of numbers separated by blanks.

    In APL we would use the (Execute) primitive to convert this character string to numbers.

    We need to perform the same kind of transformation in C#: so why not add a new method called Execute to our APL2000.Conf2008 DLL?

  9. Add the following method to the APL2000.Conf2008 Class1 class:
    public class Class1
    {
        public double PlusRed(double[] values)
        {
            double result = 0;
            for (int i = 0; i < values.Length; i++)
                result += values[i];
            return result;
        }
    
        public double[] Execute(string text)
        {
            string[] values = text.Split(new char[] { ' ' });
            double[] result = new double[values.Length];
            for (int i = 0; i < values.Length; i++)
                result[i] = Double.Parse(values[i]);
            return result;
        }
    }
    

    This method is interesting in that it allows me to introduce the .Net Framework. The .Net Framework is the set of thousands of classes built in Microsoft.Net and available to any C# developer. It is a gigantic collection of objects which you can use at any time in your applications and which basically reduce the amount of code you’ve got to write by 95% or so. That’s why .Net is so important for an APL+Win user: we can no longer afford not be able to tap into the .Net Framework power. This is certainly the most important thing an APL+Win developer needs nowadays.

    The Execute argument called text is a string. We need to split it into an array of strings each containing one number, using the space character as the delimiter. Everything in C# is an object, even a single number, or a string. So we can type a dot after the text variable name to see with Intellisense which methods are available for a string object. And here we can see the Split method which does exactly what we need.

    Intellisense tells us what the argument and result types are for any given method and the fundamental idea of C# programming is that you MUST always perfectly conform to these types.

    For example, here is the Intellisense information displayed about the Split method for a string:

    This means that the result of the Split method MUST be declared as an array of strings (string[]) and that its argument must be an array of chars (char[]). As long as you 100% respect the types in C#, you’ll be safe.

    Hence the instruction:

    string[] values = text.Split(new char[] { ' ' });
    

    Similarly, we are using another .Net Framework method in the Execute method and this is Double.Parse which is a static method of the Double class. This method converts a string to a double, which is exactly what we need to do here.

  10. Right click on APL2000.Conf2008 and select Rebuild to recompile the APL2000.Conf2008 project
  11. Now for the final step in our application: writing the button1_Click event handler.

    Add the following code to the button1_Click event handler in Form1.cs:

    private void button1_Click(object sender, EventArgs e)
    {
        double[] values = apl.Execute(textBox1.Text);
        double result = apl.PlusRed(values);
        label2.Text = "Result: " + result;
    }
    

    In this event handler remember that we are using apl which is an instance of our APL2000.Conf2008.Class1 class.

    We are first calling its Execute method to convert the values entered by the user in the textBox1 TextBox to a numeric vector of doubles. We then call its PlusRed method, passing this vector of doubles as an argument, to compute its sum. And we finally display the result as a character string in the label2 Label.

    Pretty easy, isn’t it?

    Those of you who are APL one liners, will certainly appreciate the one line version of our little handler (yes, we can also be one liners in C#!):

    private void button1_Click(object sender, EventArgs e)
    {
        //double[] values = apl.Execute(textBox1.Text);
        //double result = apl.PlusRed(values);
        //label2.Text = "Result: " + result;
        label2.Text = "Result: " + apl.PlusRed(apl.Execute(textBox1.Text));
    }
    

    I have commented the previous lines for an easier comparison of the 2 versions.

    Why has it been so simple to write the button1_Click handlers?

    This is because of our Object Oriented approach to this application: we have taken the time to set up a Class1 object and to write the methods we would need to make our Form1.cs development easy.

    Moreover, Class1 being in an external DLL (i.e. external to our APL2000.Conf2008.Test application) we will be able to reuse it in the future, as often as we need it. For example, every time we will have to convert a TextBox content to a numeric vector or every time we will have to compute the sum of a numeric vector, we can reference the APL2000.Conf2008.DLL in our application and reuse the Class1 class.

    Now there’s no interest in writing an application if it’s not for using it.

   

Let’s start and use our application.

  1. Click on the toolbar button
  2. Enter: 10 20 30 in the TextBox
  3. Click the Compute button

Here is what you get:

CSharpPrimer8.jpg