Print this page

C Sharp

 

Csharp Quick Reference

 

Example

using System;

class Test {

  static void Main ( ) {

    int x = 3;

    int y = x;

    x++;

    Console.WriteLine (y);

  }

}

 

For Loop

For (int=1, i<=10; i++)

   Console.WriteLine(“The number is {0}”,i );

 

While Loop

While (x<100)

X++;

 

If…Then

If (nCount < nMax)

{

     nTotal += nCount;

     nCount++;

}

Else

{

     nTotal += nCount;

     nCount-;

}

 

Array

Int[] nums = new int[2];

nums[0] = 100;

nums[1] = 200;

char[ ] vowels = new char[ ] {'a','e','i','o','u'};

Console.WriteLine(vowels [1]);

int[,] array = {{1,2},{3,4}};

 

Struct

struct Point {

  public int x, y;

}

Point p1 = new Point(  );

Point p2;

p2.x = p2.y = 0;

Point[] points = new Point[3];

 

Function Method

public void Remove(int index)

  {

  if (index > Count - 1 || index < 0)

     {

        System.Windows.Forms.MessageBox.Show("Index not valid!");

     }

  else

     {

        List.RemoveAt(index);

     }

  }

 

Class

Public class Widget

   {

      public string Name;

      public Widget()

      {

      }

   }

 

Throw Exceptions

public void Accelerate(int finalVelocity)

  {

    if (finalVelocity > cnstSpeedOfLight)

  {

    throw new

        SpeedOfLightException("You cannot exceed light speed!");

   }

   // Additional code omitted.

      }

 

Catch Exceptions

int cmdresults = 0;

// The following two property settings can also me done

// in the Properties window, but are shown here for completeness.

OleDbCommand2.CommandText = "NewAuthor";

OleDbCommand2.CommandType = CommandType.StoredProcedure;

 

// Set parameter values. In this case, all parameter values

// are strings.

OleDbCommand2.Parameters["au_id"].Value = TextBox1.Text;

OleDbCommand2.Parameters["au_lname"].Value = TextBox2.Text;

OleDbCommand2.Parameters["au_fname"].Value = TextBox3.Text;

OleDbCommand2.Parameters["phone"].Value = TextBox4.Text;

OleDbCommand2.Parameters["address"].Value = TextBox5.Text;

OleDbCommand2.Parameters["city"].Value = TextBox6.Text;

OleDbCommand2.Parameters["st"].Value = TextBox7.Text;

OleDbCommand2.Parameters["zip"].Value = TextBox8.Text;

OleDbCommand2.Parameters["contract"].Value = CheckBox1.Checked;

 

OleDbConnection2.Open();

try

{

   cmdresults = OleDbCommand2.ExecuteNonQuery();

}

catch (Exception ex)

{

   MessageBox.Show("Failed to execute command, err = " + ex.Message);

}

OleDbConnection2.Close();

MessageBox.Show("Number of records inserted = " + cmdresults.ToString());

 

Database

ADO.net => System.Data

SqlConnection cnPubs = New SqlConnection

(“Server =(Local);uid=sa;pwd=;database=pubs”);

SqlDataAdapter daTitle=new SqlDataAdapter(“select title,notes,price,pubdate from titles”,cnPubs)