Go to Artuber found article: C # coding examples

Source: Internet
Author: User
Tags foreach arrays datetime
C # codeing Examples
--------------------------------------------------------------------------------
Provided by Jeffrey Richter
Jeffrey Richter (jeffreyrichter.com) is a cofounder of Wintellect (Wintellect.com), a software consulting, education, and Development firm that specializes in. NET, Windows, and COM programming. Jeffrey is also a contributing editor to MSDN Magazine and is the author of two Microsoft press books:programming Applica tions for Microsoft Windows and programming Server-side applications for Microsoft Windows.

Jeffrey is a design and programming consultant for many companies including Microsoft, Intel, and DreamWorks. It currently writing a book tentatvively titled:programming applications for the. NET frameworks.

The following represents the short bits of code-fragments, Jeffrey had with him in order to illustrate various Of C # that he felt might is usefull to communicate during this episode. While we didn ' t get a chance to work through many of this examples, he graciously has provided us You might is able to look at them and get some additional ideas about the features and capabilities of C #.

Members Only
Everything is a type. There are no global methods or variables. The following "Hello World" sample application defines it "Main" function as part of a class:
Using System;

Class App {
public static void Main (string[] args) {
Console.WriteLine ("Hello World");
}
}

For everything, there are an exception
Exception support in C # is a first-class citizen of the language itself. The following example illustrates the use of the try/catch/finally process for detecting and reacting to errors. The "finally" condition is guaranteed to be run regardless of the error situation.

Also Notice the string @ "C:\NotThere.txt", this illustrates the use of a ' "verbatim string" (which is what the "@" Signifie s) in which you don ' t need to worry about putting in two \ s in order too get it to display one.
Using System;
Using System.IO;

public class App {
public static void Main () {
FileStream fs = null;
try {
FS = new FileStream (@ "C:\NotThere.txt", FileMode.Open);
}
catch (Exception e) {
Console.WriteLine (E.message);
}
finally {
if (fs!= null) fs. Close ();
}
}
}

Getting off to a good start
This example shows a few different aspects the How to pre-initialize values:
Class MyCollection {
Int32 numitemsincollection = 0;
DateTime creationdatetime = new DateTime.Now ();

This even works for static fields
static Int32 numobjinstances = 0;
...
}

Filling all your buckets
This example shows various aspects of defining, initializing, and using arrays.
static void Arraydemo () {
Declare a reference to an array
Int32[] IA; defaults to NULL
ia = new int32[100];
ia = new int32[] {1, 2, 3, 4, 5};

Display the array ' s contents
foreach (Int32 x in IA)
Console.Write ("{0}", x);


Working with multi-dimensional arrays
stringbuilder[,] sa = new stringbuilder[10][5];
for (int x = 0; x < x. x + +) {
for (int y = 0; y < 5; y++) {
Sa[x][y] = new StringBuilder (10);
}
}

Working with jagged arrays (arrays of arrays)
Int32 numpolygons = 3;
point[][] polygons = new point[numpolygons][];
Polygons[0] = new Point[3] {...};
POLYGONS[1] = new Point[5] {...};
POLYGONS[2] = new point[10] {...};
}

When Private things are public
This is example shows how to properly abstract a type ' s data. The data fields are private and are exposed via public properties. It also shows how to throw a exception.
Class Employee {
Private String _name;
Private Int32 _age;
Public String Name {
get {return (_name);}
set {_name = value;}//Tired alue?identifies new value
}

Public Int32 Age {
get {return (_age);}
set {
if (value <= 0)//tired alue?identifies new value
Throw (New ArgumentException ("Age must be >0"));
_age = value;
}
}
}

Usage:
E.age = 36; Updates The Age
E.age =-5; Throws an exception

Castaways
This code demonstrates how to use C # ' s is and as operators to perform type safe casting operations.
Object o = new Object ();
Boolean B1 = (O is Object); B1 is True
Boolean B2 = (O is String); B2 is False

Common usage:
If (O is String) {//CLR checks type
string s = (string) o; CLR Checks type again
...
}


Object o = new Object (); Creates a new Object
Jeff J = o as Jeff; Casts o to a Jeff, J is null
J.tostring (); Throws NullReferenceException

Common usage (simplifies code above):
string s = o as String; CLR checks type (once)
if (s!= null) {
...
}

A new way to spin a loop
Using the "foreach" statement can sometimes simplify your code. This example shows iterating through a set with either a ' while ' statement or with a ' foreach '.
void Withoutforeach () {
Construct a type that manages a set of items
SetType st = new SetType (...);

To enumerate items, request the enumerator
IEnumerator e = St. GetEnumerator ();

Advance enumerator World抯 cursor until no more items
while (E.movenext ()) {
Cast the current item to the proper type
ItemType it = (ItemType) e.current;

Use the item anyway your want
Console.WriteLine ("Do something with this item:" + it);
}
}

void Withforeach () {
Construct a type that manages a set of items
SetType st = new SetType (...);

foreach (ItemType it in St) {
Use the item anyway your want
Console.WriteLine ("Do something with this item:" + it);
}
}

Check your attitude at the door
The "checked" and "unchecked" keywords provide control, overflow exceptions when working with numbers. The following example illustrates can be used:
Byte b = 100;
b = (Byte) checked (b + 200); B contains 44
b = Checked ((Byte) (b + 200)); OverflowException on cast

Checked {
Byte b = 100;
b = (Byte) (b + 200); OverflowException
}

UInt32 Invalid = Unchecked ((UInt32)-1); Ok

Int32 calculatechecksum (byte[] ba) {
Int32 Checksum = 0;
foreach (Byte b in Ba) {
Unchecked {
Checksum + b;
}
}
return (Checksum);
}

Keeps going ... and going. And going ...
Using a "params" parameter allows a method to easily accept a variable number of parameters. A method so uses a "params" parameter must use it as the last (or only) input parameter, and it can is only a Single-dim Ension array:
Int64 Sum (params int32[] values) {
Int64 sum = 0;
foreach (Int32 val in values)
sum = val;
return (sum);
}

void SomeMethod () {
Int64 result = Sum (1, 2, 3, 4, 5);

result = Sum (new int32[] {1, 2, 3, 4, 5}); Also Works
}

Some bits can ' t be twiddled
This is a example that illustrates, work with "Const" and "ReadOnly" Fields:
Class MyType {
Note:const fields are always considered ' static '
Const fields must is calculated at Compile-time
public const int maxentries = 33;
Public Const String Path = @ "C:\Test.dat"; Verbatim string
...
}

Class MyType {
public static readonly employees[] Employees = new employees[100];
Public ReadOnly Int32 Employeeindex;

Public MyType (Int32 employeeindex) {
This.employeeindex = Employeeindex;
}

void SomeMethod () {
This.employeeindex = 10; Compiler Error
}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.