Archive for the ‘Programming’ Category.

Simple Write File using C#

A very simple method for writing to a file, not forget to include using System.IO;.

string filename = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\test.txt";
string content = "This is the new file content";
File.WriteAllText(filename, content);

Data Validation and Exceptions in C#

The setName funcion demostrates simple data validation on the argument value.

void setName(string value)
{
    // validate empty
    if (string.IsNullOrWhiteSpace(value))
    {
        throw new ArgumentNullException("Please enter a value");
    }

    // validate length
    if (value.Length > 10)
    {
        throw new ArgumentException("The value is too long");
    }

    // value is valid
    MessageBox.Show("The value is valid");
}

When calling the setName function it is important that we implement code to catch any exceptions

try
{
    setName(textBox1.Text);
}
catch (Exception ex)
{
    MessageBox.Show("Error " + ex.Message);
}

C# type checking with the is statement

A var type can be checked using the ‘is’ statement

var a = 1.0;

if (a is int)
{
    MessageBox.Show("int");
}
else
{
    MessageBox.Show("is NOT int");
}

C# class properties

The code below shows the short hand and long hand syntax for defining class properties.

public class Example
{
  // class property short hand
  public string Firstname {get; set;}


  // class property long hand
  private string _Lastname;
  public string Lastame
  {
     get {return _Lastname}
     set {_Lastname = value}
  }
}

Simple C# LINQ example

The LINQ example below creates a generic collection of the class Car. Then using a LINQ statement the collection is filtered to find cars that are newer than 2009.

List myCars = new List() {
    new Car() { Make="BMW", Model="550i", Year=2009 },
    new Car() { Make="Toyota", Model="4Runner", Year=2010 },
    new Car() { Make="BMW", Model="745li", Year=2008 },
    new Car() { Make="Ford", Model="Escape", Year=2008 },
    new Car() { Make="BMW", Model="550i", Year=2010 }
};


var newCars = from c in myCars
                where c.Year > 2009
                select new { c.Model, c.Make, c.Year };

foreach (var car in newCars)
{
    Console.WriteLine("{0} {1} - {2}", car.Make, car.Model, car.Year);
}

class Car
{
   public string Make { get; set; }
   public string Model { get; set; }
   public int Year { get; set; }
}

Enumerations with tryParse in C#

Here is an example of using enum with a tryParse. The program asks the user to enter a new state. The tryParse then attempts to convert the input into a enum.

// define current state
MyState currentState = MyState.off;
            
// get value from user
Console.WriteLine("Please enter the new state");
string input = Console.ReadLine();

if (Enum.TryParse(input, out currentState) == false)
{
    Console.WriteLine("Unable to compute input");
}
Console.WriteLine("Current state " + currentState);

Console.WriteLine("=== Finished ===");
Console.ReadLine();
}

enum MyState
{
on,
off,
idle
}

Adding days to a DateTime in C#

Add seven days to the current time.

DateTime start = DateTime.Now;
Console.WriteLine("Start date = " + start.ToString("dd/MM/yyyy hh:mm:ss"));
DateTime end = start.AddDays(7);
Console.WriteLine("End date = " + end.ToString("dd/MM/yyyy hh:mm:ss"));

Other methods for defining a DateTime object

DateTime start = DateTime.Parse("23/01/1984 01:02:03");
DateTime start = new DateTime(1984, 01, 23, 01, 02, 03);

Simple c# StringBuilder example

A simple example of using the StringBuilder to concat strings.

StringBuilder mySB = new StringBuilder();
mySB.Append("line 1");
mySB.Append("line 2");
mySB.Append("line 3");
Console.WriteLine(mySB.ToString());

String formating within C#

Below is an example of using string formating to print a time

int h = 12;
int m = 13;
int s = 14;
string myString = string.Format("{0}:{1}:{2}", h, m, s);
Console.WriteLine(myString);

To format a number to two decimal places, you could use the string format.

double s = 14.123;
string myString = string.Format("{0:0.00}", s);
Console.WriteLine(myString);

Reading a file with C#

Reading a text file line by line in C#. Dont forget to include using System.IO;

StreamReader myReader = new StreamReader(@"c:\test.txt");
string line = "";
while (line != null)
{
   line = myReader.ReadLine();
   Console.WriteLine(line);
}

You can read all the text within a file using the ReadAllText function.

string filename = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\test.txt";
string content = File.ReadAllText(filename);
MessageBox.Show(content);