Monday, August 3, 2009

Arrays (C# Programming Guide)

class TestArraysClass
{
static void Main()
{
// Declare a single-dimensional array
int[] array1 = new int[5];

// Declare and set array element values
int[] array2 = new int[] { 1, 3, 5, 7, 9 };

// Alternative syntax
int[] array3 = { 1, 2, 3, 4, 5, 6 };

// Declare a two dimensional array
int[,] multiDimensionalArray1 = new int[2, 3];

// Declare and set array element values
int[,] multiDimensionalArray2 = { { 1, 2, 3 }, { 4, 5, 6 } };

// Declare a jagged array
int[][] jaggedArray = new int[6][];

// Set the values of the first array in the jagged array structure
jaggedArray[0] = new int[4] { 1, 2, 3, 4 };
}
}

String Array in C#

1. Declaring string arrays
First, here we see that there are several ways to declare and instantiate a string[] array local variable. They are all equivalent in the compiled code [see note], so choose the one you think is clearest to read.

class Program
{
static void Main()
{
// String arrays with 3 elements:
string[] arr1 = new string[] { "one", "two", "three" }; // A
string[] arr2 = { "one", "two", "three" }; // B
var arr3 = new string[] { "one", "two", "three" }; // C

string[] arr4 = new string[3]; // D
arr4[0] = "one";
arr4[1] = "two";
arr4[2] = "three";
}
}



Thursday, July 30, 2009

Getting Command-Line Input:

// Namespace Declaration
using
System;

// Program start class
class NamedWelcome
{
// Main begins program execution.
static void Main(string[] args)
{
// Write to console
Console.WriteLine("Hello, {0}!", args[0]);
Console.WriteLine("Welcome to the C# Station Tutorial!");
}
}

Interacting via the Command-Line

Besides command-line input, another way to provide input to a program is via the Console. Typically, it works like this: You prompt the user for some input, they type something in and press the Enter key, and you read their input and take some action


// Namespace Declaration
using System;

// Program start class
class InteractiveWelcome
{
// Main begins program execution.
public static void Main()
{
// Write to console/get input
Console.Write("What is your name?: ");
Console.Write("Hello, {0}! ", Console.ReadLine());
Console.WriteLine("Welcome to the C# Station Tutorial!");
}
}

A Simple C# Program

Listing 1-1. A Simple Welcome Program: Welcome.cs
// Namespace Declaration
using
System;

// Program start class
class WelcomeCSS
{
// Main begins program execution.
static void Main()
{
// Write to console
Console.WriteLine("Welcome to the C# Station Tutorial!");
}
}