C# Examples
Dave Braunschweig
Strings
// This program demonstrates string functions.
using System;
class Strings 
{
    public static void Main (string[] args) 
    {
        String str = "Hello";
        Console.WriteLine("string: " + str);
        Console.WriteLine("string.ToLower(): " + str.ToLower());
        Console.WriteLine("string.ToUpper(): " + str.ToUpper());
        Console.WriteLine("string.IndexOf('e'): " + str.IndexOf('e'));
        Console.WriteLine("string.Length: " + str.Length);
        Console.WriteLine("string.Replace('H', 'j'): " + str.Replace('H', 'j'));
        Console.WriteLine("string(Substring(2, 2)): " + str.Substring(2, 2));
        Console.WriteLine("string.Trim(): " + str.Trim());
        String name = "Bob";
        double value = 123.456;
        Console.WriteLine(String.Format("{0} earned {1:$0.00}", name, value));
    }
}
Output
string: Hello
string.ToLower(): hello
string.ToUpper(): HELLO
string.IndexOf('e'): 1
string.Length: 5
string.Replace('H', 'j'): jello
string(Substring(2, 2)): ll
string.Trim(): Hello
Bob earned $123.46
Files
// This program demonstrates reading a text file with exception handling.
// References:
//     https://en.wikibooks.org/wiki/C_Sharp_Programming
using System;
public class Files
{
    public static void Main(String[] args)
    {
        string FILENAME = "temperatures.txt";
    
        ReadFile(FILENAME);
    }
    private static void ReadFile(string filename)
    {
        System.IO.StreamReader file;
        string line;
        try
        {
            using (file = System.IO.File.OpenText(filename))
            {
                while (true) 
                {
                    line = file.ReadLine();
                    if (line == null)
                    {
                        break;
                    }
                    Console.WriteLine(line);
                }
            }
        }
        catch(Exception exception)
        {
            Console.WriteLine("Error reading " + filename);
            Console.WriteLine(exception.Message);
        }
    }
}
Output
Celsius,Fahrenheit 0,32 10,50 20,68 ... 80,176 90,194 100,212
