VS C# Sample codes

Code: Declaring an Array (Visual C#)

This example shows three different ways to declare different kinds of arrays: single-dimensional, multidimensional, and jagged.

Example

Copy

// Single-dimensional arrays.

int[] myArray1 = new int [5];

string[] myArray2 = new string[6];

 

// Multidimensional arrays.

int[,] myArray3 = new int[4,2];

int[,,] myArray4 = new int [4,2,3];

 

// Jagged array.

int[][] myArray5 = new int[3][];

Compiling the Code

Copy the code and paste it into the Main method of a console application.

Robust Programming

Make sure you initialize the elements of the jagged array before using it, as follows:

myArray5[0] = new int[7];

myArray5[1] = new int[5];

myArray5[2] = new int[2];

Code: Initializing an Array (Visual C#)

This example shows three different ways to initialize different kinds of arrays: single-dimensional, multidimensional, and jagged.

Example

// Single-dimensional array (numbers).

int[] n1 = new int[4] {2, 4, 6, 8};

int[] n2 = new int[] {2, 4, 6, 8};

int[] n3 = {2, 4, 6, 8};

// Single-dimensional array (strings).

string[] s1 = new string[3] {“John”, “Paul”, “Mary”};

string[] s2 = new string[] {“John”, “Paul”, “Mary”};

string[] s3 = {“John”, “Paul”, “Mary”};

 

// Multidimensional array.

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

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

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

 

// Jagged array.

int[][] n7 = new int[2][] { new int[] {2,4,6}, new int[] {1,3,5,7,9} };

int[][] n8 = new int[][] { new int[] {2,4,6}, new int[] {1,3,5,7,9} };

int[][] n9 = { new int[] {2,4,6}, new int[] {1,3,5,7,9} };

Code: Iterating Through an Array (Visual C#)

This example uses the foreach statement to access and display items of an array.

Example

int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9};

foreach (int element in numbers)

{

System.Console.WriteLine(element);

}

Code: Iterating Through a Collection (Visual C#)

This example uses the Add method on the Hashtable class to add entries to a Hashtable collection. It then uses a foreach statement to iterate through the collection.

Example

Hashtable phones = new Hashtable();

// Add items.

phones.Add(“John”, “123-4567”);

phones.Add(“Enju”, “351-8765”);

phones.Add(“Molly”, “221-5678”);

phones.Add(“James”, “010-4077”);

phones.Add(“Nelly”, “110-5699”);

phones.Add(“Leah”, “922-5699”);

 

// Iterate through the collection.

Console.WriteLine(“Name\t\tNumber”);

foreach (string name in phones.Keys)

{

Console.WriteLine(name +”\t”+ phones[name]);

}

Code: Declaring a Property (Visual C#)

This example declares an instance property. For more information and examples on instance and static properties, see Properties.

Example

private string name;

// A read-write instance property:

public string NameProperty

{

get

{

return name;

}

set

{

name = value;

}}

Robust Programming

  • You can use the get accessor to either return the field value or compute the value and return it, for example:

get

{

return (name != null) ? name : “NA”;

}

  • Do not use the get accessor to change the state of the object, for example:

get

{

return myNumericField++;

}

Code: Determining the Span Between Two Dates (Visual C#)

This example calculates the difference in days between two dates and constructs a TimeSpan value for that difference.

Example

DateTime oldDate = new DateTime(2002,7,15);

DateTime newDate = DateTime.Now;

 

// Difference in days, hours, and minutes.

TimeSpan ts = newDate – oldDate;

// Difference in days.

int differenceInDays = ts.Days;

 

Console.WriteLine(“Difference in days: {0} “, differenceInDays);

 

 

 

 

Code: Inheriting From a Class (Visual C#)

This example defines the Circle and Rectangle classes, which both inherit from the Shape class, and the Square class, which inherits from the Rectangle class.

Example

public class Shape

{

// Definitions of properties, methods, fields, and events.

}

public class Circle : Shape

{

// Specialized properties, methods, fields, events for Circle.

}

public class Rectangle : Shape

{

// Specialized properties, methods, fields, events for Rectangle.

}

public class Square : Rectangle

{

// Specialized properties, methods, fields, events for Square.

}

Code: Passing Object Arrays to Methods (Visual C#)

This example shows how an array of objects is passed to the DisplayMyCollection method, which uses the params keyword to accept any number of arguments.

Example

class MyBoxingClass

{

public static void DisplayMyCollection(params object[] anArray)

{

foreach (object obj in anArray)

{

System.Console.Write(obj + “\t”);

}

 

// Suspend the screen.

System.Console.ReadLine();

}

 

static void Main()

{

DisplayMyCollection(101, “Visual C# Basics”, 2002);

}

}

 

 

Code: Reading a Text File One Line at a Time (Visual C#)

This example reads the contents of a text file, one line at a time, into a string using the ReadLine method of the StreamReader class. Each text line is stored into the string line and displayed on the screen.

Example

int counter = 0;

string line;

 

// Read the file and display it line by line.

System.IO.StreamReader file =

new System.IO.StreamReader(“c:\\test.txt”);

while((line = file.ReadLine()) != null)

{

Console.WriteLine (line);

counter++;

}

 

file.Close();

 

// Suspend the screen.

Console.ReadLine();

Code: Reading Class Data from an XML File (Visual C#)

This example reads the data stored in an object in the IntroToVCS.xml file using the Deserialize method of the XmlSerializer class.

Example

public class Book

{

public string title;

 

static void Main()

{

Book introToVCS  = new Book();

System.Xml.Serialization.XmlSerializer reader = new

System.Xml.Serialization.XmlSerializer(introToVCS.GetType());

 

// Read the XML file.

System.IO.StreamReader file=

new System.IO.StreamReader(“c:\\IntroToVCS.xml”);

 

// Deserialize the content of the file into a Book object.

introToVCS = (Book) reader.Deserialize(file);

System.Windows.Forms.MessageBox.Show(introToVCS.title,

“Book Title”);

}

}

 

Code: Reading From a Text File (Visual C#)

This example reads the contents of a text file into a string using the ReadToEnd method of the StreamReader class.

Example

// Read the file as one string.

System.IO.StreamReader myFile =

new System.IO.StreamReader(“c:\\test.txt”);

string myString = myFile.ReadToEnd();

 

myFile.Close();

 

// Display the file contents.

Console.WriteLine(myString);

// Suspend the screen.

Console.ReadLine();

 

Code: Reading XML From a File (Visual C#)

This example uses the XMLTextReader class to extract the element names and text strings from the IntroToVCS.xml file and store the information in a string variable.

Example

System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(“c:\\IntroToVCS.xml”);

string contents = “”;

while (reader.Read())

{

reader.MoveToContent();

if (reader.NodeType == System.Xml.XmlNodeType.Element)

contents += “<“+reader.Name + “>\n”;

if (reader.NodeType == System.Xml.XmlNodeType.Text)

contents += reader.Value + “\n”;

}

Console.Write(contents);

Code: Writing Class Data to an XML File (Visual C#)

This example writes the data stored in an object to the IntroToVCS.xml by means of the Serialize method of the XmlSerializer class.

Example

public class Book

{

public string title;

 

static void Main()

{

Book introToVCS = new Book();

introToVCS.title = “Intro to Visual CSharp”;

System.Xml.Serialization.XmlSerializer writer =

new System.Xml.Serialization.XmlSerializer(introToVCS.GetType());

System.IO.StreamWriter file =

new System.IO.StreamWriter(“c:\\IntroToVCS.xml”);

 

writer.Serialize(file, introToVCS);

file.Close();

}

}

Code: Writing to a Text File (Visual C#)

This example writes a string to a text file using the WriteLine method of the StreamWriter class.

Example

// Compose a string that consists of three lines.

string lines = “First line.\r\nSecond line.\r\nThird line.”;

 

// Write the string to a file.

System.IO.StreamWriter file = new System.IO.StreamWriter(“c:\\test.txt”);

file.WriteLine(lines);

 

file.Close();

 

Code: Running a Program (Visual C#)

This example loads and runs the MSPaint application using the Process.Start method.

Example

System.Diagnostics.Process.Start(“mspaint.exe”);

Compiling the Code

Copy the code and paste it into the Main method of a console application.

Replace "mspaint.exe" with the path to the application you want to run

Code: Running a Program Associated With a File Type (Visual C#)

This example opens the test.txt file in Notepad using the Process.Start method.

Example

System.Diagnostics.Process.Start(“c:\\test.txt”);

Code: Searching for a String in an Array of Strings (Visual C#)

This example calls the IndexOf method on an array of strings to report the string number and index of the first occurrence of a substring.

Example

string[] strArray = {“ABCDEFG”, “HIJKLMNOP”};

string findThisString = “JKL”;

int strNumber;

int strIndex = 0;

for (strNumber = 0; strNumber < strArray.Length; strNumber++)

{

strIndex = strArray[strNumber].IndexOf(findThisString);

if (strIndex >= 0)

break;

}

Console.WriteLine(“String number: {0}\nString index: {1}”,

strNumber, strIndex);

Code: Searching Within a String (Visual C#)

This example calls the IndexOf method on a String object to report the index of the first occurrence of a substring.

Example

string searchWithinThis = “ABCDEFGHIJKLMNOP”;

string searchForThis = “DEF”;

int firstCharacter = searchWithinThis.IndexOf(searchForThis);

 

Console.WriteLine(“First occurrence: {0}”, firstCharacter);

Code: Simulating Default Parameters (Visual C#)

This example demonstrates the use of method overloading to simulate default parameters, which is not allowed in C#.

Example

class MyClass

{

static string myMethod(string precip, string country, string location)

{

return string.Format(“The {0} in {1} stays mainly in the {2}.”,

precip, country, location );

}

 

static string myMethod(string precip, string country )

{

return myMethod(precip, country, “plain”);

}

 

static string myMethod()

{

return myMethod(“rain”, “Spain”, “plain”);

}

 

static void Main(string[] args)

{

Console.WriteLine(myMethod());

Console.WriteLine(myMethod(“snow”, “Walla Walla”));

}

}

Code: Finding the Names of Resources in an Assembly (Visual C#)

This example creates a string that contains the names of all the resources in an assembly.

Example

System.Reflection.Assembly thisExe;

thisExe = System.Reflection.Assembly.GetExecutingAssembly();

string [] resources = thisExe.GetManifestResourceNames();

string list = “”;

 

// Build the string of resources.

foreach (string resource in resources)

list += resource + “\r\n”;

Code: Catching an Exception (Visual C#)

This example uses the trycatch blocks to catch division by zero as an exception.

Example

int top = 0, bottom = 0, result = 0;

try

{

result = top / bottom;

}

catch (System.DivideByZeroException ex)

{

Console.WriteLine(“{0} Exception caught.”, ex);

}

 

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s