Yielding results

Yield is a new syntax word within the .net 2 language. This allows for the IEnumerable interface to have direct interaction instead of using the IEnumerator interface to iterate though a result set. For easier demonstration, I think, the code examples, the first code is a .net 1 version of the interface IEnumerable.

using System;
using System.Collections;
 
// the inital class is IEnumerable- means that it has to implement the GetEnumerator
public class Class : IEnumerable 
{
       // internal class to implement the IEnumerator interface, which inturn has to do the MoveNext, Current, Reset methods.
       private class ClassEnumerator : IEnumerator
       {
              // internal values to go through the array
              private int index = -1;
              private Class P;
              // setup the internal variable
              public ClassEnumerator(Class P) 
              {
                     this.P = P; 
              }
              // move within the array, if any values are present.
              public bool MoveNext()
              {
                     index++;
                     return index < P._Names.Length;
              }
              // set the internal to -1, thus restart
              public void Reset() 
              { 
                     index = -1;
              }
 
              // get the Current object
              public object Current 
              { 
                     get 
                     { 
                            return P._Names[index]; 
                     } 
              }
       }
 
       // return a IEnumerator object of the above with itself passed
       public IEnumerator GetEnumerator()
       {
              return new ClassEnumerator(this);
       }
 
       // the internal string array of names
       private string[] _Names;
       // the new class setup process, 
       public Class(params string[] Names)
       {
              _Names = new string[Names.Length];
              // copy the passed parameter starting at position 0
              Names.CopyTo(_Names,0);
       }
}
 
class ClassProgram
{
       static void Main(string[] args)
       {
              Class ClassArr = new Class("Student1", "Student2","Studentx");
              foreach (string s in ClassArr)
                     Console.WriteLine(s);
       }
}

This is able to output a string of

Student1
Student2
Studentx

Since the Class class (it is a class of students), there is allot of code to iterate with the foreach function.

Within .net 2 there is a nice and more tighter method called yield, an yield will yield a result and be able to iterate though a result set with the IEnumerable return set. Again, here is the source code.

using System;
using System.Collections;
 
class yielding
{
       // same as the class as in .net 1 version.
       public class Class : IEnumerable
       {
              // but only need to implement this one method to do the same as the pervious separate class
              public IEnumerator GetEnumerator()
              {
                     int counter = -1;
                     while (counter++ < (_Names.Length-1))
                            yield return _Names[counter];
              }
 
              // same as the other .net 1 class internals for the private variable and the constructor
              private string[] _Names;              
              public Class(params string[] Names)
              {
                     _Names = new string[Names.Length];
                     Names.CopyTo(_Names,0);
              }
       }       
 
       static void Main(string[] args)
       {
              // same as the .net 1 version
              Class ClassArr = new Class("Student1", "Student2", "Studentx");
              foreach (string s in ClassArr)
                     Console.WriteLine(s);
       }
}

Far less code and also the result is exactly the same.

Also there are other benefits of the yield attached to an IEnumerable interface, here is some more code to demonstrate how to implement a power function to display the power result being built up. This demonstrates how to use just a single method to return an iterate-able result.

using System;
using System.Collections;
 
class yielding
{
       // same as the class as in .net 1 version.
       public class Class : IEnumerable
       {
              // but only need to implement this one method to do the same as the pervious separate class
              public IEnumerator GetEnumerator()
              {
                     int counter = -1;
                     while (counter++ < (_Names.Length-1))
                            yield return _Names[counter];
              }
 
              // same as the other .net 1 class internals for the private variable and the constructor
              private string[] _Names;              
              public Class(params string[] Names)
              {
                     _Names = new string[Names.Length];
                     Names.CopyTo(_Names,0);
              }
       }       
 
       // IEnumerable linked to yield is new in .net 2, it allows for the 
       // iteration of this method, acting like array instead of a single return.
       public static IEnumerable Power(int number, int exp)
       {
              int counter = 0, result = 1;       // setup the default values.
              while (counter++ < exp)              // increament counter and whilst lower than the passed parameter exp
              {
                     result *= number;       // result = result * number;
                     yield return result;       // yield the result and return
              }
       }
 
       // can also just iterate though a array of strings (in this example)
       public static IEnumerable StReturn(params string[] names)
       {
              int counter = -1;
              while (counter++ < (names.Length-1))
                     yield return names[counter];
       }
 
       static void Main(string[] args)
       {
              // can do a return of a power function as well
              foreach(int e in Power(4,3))
                     Console.WriteLine(e.ToString());
 
              // you can just iterate a string 
              string[] st = {"student1","student2","studentx"};
              foreach(string s in StReturn(st))
                     Console.WriteLine(s.ToString());
 
              // same as the .net 1 version
              Class ClassArr = new Class("Student1", "Student2", "Studentx");
              foreach (string s in ClassArr)
                     Console.WriteLine(s);
       }
}

I have also include the code from above to demonstrate the similar usage for iterate though a string array.

Output would be

4
16
64
student1
student2
studentx
Student1
Student2
Studentx

You will need to have .net 2 installed or mono (use the gmcs part of mono to use the .net 2 functions.

Generics

A Generic is a way to declassify the type of variable used, e.g. if there was a function to add up two integer values, but you had two double values, then the int function would not function correctly, so there would be a need to function overload the function to allow for the double increment as well. But just envisage that the same function would be required for characters, floats, personally created ones etc, then there would be more functions per type of variable than the actual work done.

A generic class negates this by allowing any class type passed to the function, as long as the type has the standard increment process defined, it will work with any type.

This will demonstrate the basics of the generics.

using System;
 
// create a class with a generic type of T (e.g. pass in the type of your choice
public class GenTest<T>;
{
       // the private value
       private T genericValue;
 
       // default constructor for the class (same name as the class)
       // ~ is the deconstructor
       public GenTest(T generic) 
       {
              genericValue = generic;       // set the internal T = passed value
       }
 
       // return the value of the internal value
       public T ReturnValue()
       {
              return genericValue;
       }
}
 
public class MainProgram
{
       static void Main()
       {
              // create a integer type class, with the default value of 2
              GenTest<int> genInt = new GenTest<int>(2);
              Console.WriteLine("Int generic = " + genInt.ReturnValue());
 
              // same class create a string with the default value of "cool"
              GenTest<string> genString = new GenTest<string>("cool");
              Console.WriteLine("String generic = " + genString.ReturnValue());
       }
}

If you save the code and run with .net 2 or greater (.NET Framework) ( since this was part of .net 2 and not with .net 1). The output will be

Int generic = 2
String generic = cool

As you can see the same class is able to use both integer and strings as the default variable type.

Collections – ArrayList

Collections – ArrayList, the ArrayList is part of the Collections namespace. The ArrayList acts as the same as the array (Array Example) apart from it allows other functional aspects to access the list of array.

Shall comment more on the different aspects in later tutorials, but basically there many different parts to a class that allow for better functionality e.g
1. Interfaces = base of a class for strict implementation)
2. IEnumerable (which is a interface) = means that you implement GetEnumerator aspects of a class, e.g. for the foreach command)
3. Generics (which is part of .net 2) = Similar to templates (Generics) in c++ and also generics from Java).
4. Etc. shall comment more on these.

This is the code

using System;
 
namespace ArrayListTest
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
            arrayList.Add(2);
            arrayList.Add(3);
            arrayList.Add("hi there");
 
            foreach (object obj in arrayList)
                Console.WriteLine(obj.ToString());
        }
    }
}

If you save as arraylisttest.cs, and then run, the output will be

2
3
hi there

It basically allows you to add in any object into the ArrayList, and since objects have the ToString() function, then it is able to print out the object, of course custom made objects will either display there type or the ToString() will have to be implemented.

Arrays

Arrays are ways of having a block of memory allocated to a single variable type, this allows for holding the national lottery numbers within an array of 6 instead of actually having 6 different variables, saves on variable overload

int value1 = new int (1);
int value2 = new int (2);
int value3 = new int (3);
int value4 = new int (4);
int value5 = new int (5);
int value6 = new int (6);

and instead you could just have

int[] values = new int[6] {1,2,3,4,5,6};

This is example code of how to use arrays.

using System;
 
class arrays
{
       public static void Main()
       {
              // the [] means a array declaration, and when you create the new instance of a int you then define the size (3 in this case)
              // if you wish to define the default values, then place these within the {} brackes
              int[] arrayInt = new int[3] { 3,2,1};       
 
              // for each (integer in the array of integers assign to i)
              foreach (int i in arrayInt)
                     Console.WriteLine(i);
 
              // to alter the values within the array, an array always starts at 0
              arrayInt[0] = 20;
              arrayInt[1] = 30;
              arrayInt[2] = 40;
 
              foreach (int i in arrayInt)
                     Console.WriteLine(i);
              return;
       }
}

Save as array.cs and then compile using either mono/csc.exe. The output will be

3
2
1
20
30
40

Method – Add Two numbers

This tutorial uses the same code as Add two numbers but includes a function/method to add two numbers together and return a value. In this case the value is a integer (int) and that is why the int is just before the name of the method (addIntegers) with two parameters passed to the method, these are the values that are being added together. I have called them a and b, so that they are different names to the variables within the main method.

The source code

using System;       // for the console object
 
class addtwonumbers
{
       public static int addIntegers(int a, int b)
       {
              return (a + b);
       }
 
       public static void Main()
       {
              try 
              {
                     // output to the console
                     Console.Write("Please enter value 1 : ");
                     // readin the console input, and then convert to a integer value
                     int val1 = Convert.ToInt32(Console.ReadLine());
                     Console.Write("Please enter value 2 : ");
                     int val2 = Convert.ToInt32(Console.ReadLine());
                     // write out the answer 
                     Console.WriteLine("Answer = " + addIntegers(val1,val2));
              }
              catch (Exception e)
              {
                     // any errors. Like converting a string to a integer value
                     Console.WriteLine("Error : " + e.ToString());
              }
       }
}

save as addtwonumbers_function.cs, this program will function the same as the previous tutorial apart from the inner working will call the method. The method programming allows for one method to be called multiple times, e.g. Within the example above there could be a method that was 5 lines in length and instead of writing the same 5 lines each time, you just write a method that is called.

Add two numbers

This tutorial will demonstrate how to read from the input console (console line) to answer the prompts. The prompts will need to be a integer value to add the two inputs together.

I am using the System.Console object to read from the console and then converting the string inputs into integers with the Convert.ToInt32 function (the System.Convert has many methods and ToInt32 is one of these).

The code

using System;       // for the console object
 
class addtwonumbers
{
       public static void Main()
       {
              try 
              {
                     // output to the console
                     Console.Write("Please enter value 1 : ");
                     // readin the console input, and then convert to a integer value
                     int val1 = Convert.ToInt32(Console.ReadLine());
                     Console.Write("Please enter value 2 : ");
                     int val2 = Convert.ToInt32(Console.ReadLine());
                     // write out the answer 
                     Console.WriteLine("Answer = " + (val1 + val2));
              }
              catch (Exception e)
              {
                     // any errors. Like converting a string to a integer value
                     Console.WriteLine("Error : " + e.ToString());
              }
       }
}

save that as addtwonumbers.cs.

Once compiled (mcp addtwonumbers.cs with mono) and executed (mono addtwonumbers.exe) the output will be

Please enter value 1 : 30
Please enter value 2: 23
Answer = 53

Class structure

This is a general tutorial about the class structure of programming languages.

The class is basically an object that allows public methods (accessed outside that class object) and private methods (the internal class logic) and protected with is the same as private apart from an inherited class can access the protected objects. Basically the 3 main types

Public : Access from outside the class, and internal of course, with inherited/friends etc.
Protected : Access from inherited/friends of the class, but not called from the class object.
Private : Access from only the class and friends of the class.

For example within C# coding …

class example1
{
       private int value1;
       private int value2;
       protected int value3;
 
       public int addtwo(int a, int b)
       {
              value1 = a;
              value2 = b;
              value3 = (a+b);              // setup the local variables
              return value3;
       }
 
       public int returnValue()
       {
              return value1;
       }
}
 
class example2 : example1
{
       public int returnValue2()
       {
              return value2;       // will error due to value2 is private in the inherited class
              //return 0;              // to be able to compile
       }
 
       public int returnValue3()
       {
              return value3;       // fine since a protected part of the inherited class
       }
}
 
class examples 
{
       static public void Main()
       {
              example1 ex = new example1();
              example2 ex2 = new example2();
              // add the two numbers and set the local internal variables
              System.Console.WriteLine("Two numbers 3 + 4 = " + ex.addtwo(3,4));
              // output the value1 from the internal example1 class
              System.Console.WriteLine("Value1 = " + ex.returnValue());
 
              // Just for demo'ing, since the example2 is not linked to example1, just inherites it.
              System.Console.WriteLine(ex2.returnValue2());       // will not compile the class above.
              System.Console.WriteLine(ex2.returnValue3());
              return;
       }
}

save as classexample.cs. The output will be

Two numbers 3 + 4 = 7
Value1 = 3
0
0

The two zero’s are because class example2 only inherits the example class and not does not link to it. I have added the line within the example2 returnValue2 method to be able to compile the source code otherwise you will get the error similar to

classexample.cs(25,10): error CS0122: example1.value2 is inaccessible due to its protection level