1 Chapter 1 C# Data type. 2 Install.NET 2003 or 2005 NET 2005 is better than NET 2003 and very...

24
1 Chapter 1 C# Data type

Transcript of 1 Chapter 1 C# Data type. 2 Install.NET 2003 or 2005 NET 2005 is better than NET 2003 and very...

1

Chapter 1

C# Data type

2

Install .NET 2003 or 2005

NET 2005 is better than NET 2003 and very friendly for programmer. However, NET 2005 needs NET platform 2 and NET 2003 only needs NET platform 1. The current XP system is NET platform 1 from PC manufacturer. So NET 2003 program application can directly run in current XP system. On the PC update to NET platform 2, NTE 2005 application can run.

So in many case, I wrote programs in 2005. When its done, I recompile with 2003. Then the user can use my program immediately.

3

Major C# Data Type

Most of them are same as in C++

Type Meaning

bool true or false

byte 8 bits long

sbyte signed byte

char Character

int 4 bytes integer number

short 2 bytes integer number

long 8 bytes integer number

uint unsigned integer

ulong unsigned long integer

float 4 bytes decimal number

double 8 bytes decimal number

4

What is C#?• C# is simple C++ and the easy C++.• C# is interpret program language or call manaded language.• C# has the version 7 and 8 following Visual studio 6. • C# is the future default language for window programming. • In most case, we do not use pointer in C#, which means we

do not directly access the memory. However, in some case, in order to speed program, we can access the memory too, such as manage picture data. This call unsafe mode.

• In C#, like in Java, it has system garbage collection to handle the memory block s which is no longer used by programs. However, we still can call Dispose() method to remove object data.

• In C#, we still use reference, the key word is ref.• C# is similar to VB NET, but looks more clear.

5

Class Definition in C++class rectangle {private:

double length; double width;public: rectangle() { length=0; width=0 ;} rectangle(double len, double wide) {length=len; width=wide; } ~rectangle() {} double getLength() { return length; } double getWidth() { return width; } double getArea() { return length * width; } void set(double len, double wide) {length = len, width = wide;}

};

6

RemarksEvery class has 3 parts :• constructors and destructor constructors could be more than one (overloaded

constructors) however, destructor only has one • member functions (or call methods)• member variablesconstructors and destructor has no typeUsually functions are public and variables are private.By default variables and functions are private.

7

Class Definition in C#class rectangle {private double length; private double width;

public rectangle() { length=0; width=0 ;}public rectangle(double len, double wide) {length=len; width=wide; }public double getLength() { return length; }public double getWidth() { return width; }public double getArea() { return length * width; }public void set(double len, double wide) {length = len, width = wide;}

};

8

class stringClass String or string represents text as a series of characters.

Constructors and methodsstring msg = new string("hello");

string msg = "hello";Char c = msg.Char(2);

int n = msg.Length;string str = string.Empty; string str= "";string stringCopy(str) int CompareTo(str)int IndexOf(str)int LastIndexOf(str)ToLower(), ToUpper(), Trim()string msg = "Good" +" Morning"; (use +)

string msg = “12” + 34; =“1234” string msg = “” +(12+34); =“36”

9

Standard Input & output

Console.Read(); // read one key inputConsole.ReadLine(); // read line to enter or 255 keysConsole.Write(); // write & stay on lineConsole.WriteLine(); // write and go to next lineConsole.Clear(); // clear buffer;

10

First C# program

using System;using System.Collections.Generic;using System.Text;

namespace ConsoleApplication1{ class Program { static void Main(string[] args) {

Console.Write("Hello"); } }}

11

String Split function

string charStr = " ,.:"; char [] charArray = charStr.ToCharArray(); string words = "one two,three:four."; string [] split = words.Split(charArray);

Basic usage is

public string[] Split(params char[]);

Then we can use foreach() to read this string array

foreach (string s in split)

{ Console.WriteLine(s);}

12

Type converting

String to integer uses int32.Parse(str);

String str = "1234";

try

{

int n = Int32.Parse(str);

}

catch(FormatException e)

{

Console.WriteLine(e.Message);

}

String to double uses Double.Parse(str)

13

Array declaration and initialization

An integer Array must be defined like:int [] myArray = new int[50]; string [] strs = {"Mike", "John", "Kathy"};

However declarations int myArray [] ; string strs [];

are wrong!

It means that [] must be before the variable of array.

int [,] Box = new int [3, 2];

Loop operator foreach

foreach(int n in myArray){ }

foreach(string s in strs){ }

is special for array.

14

Switch operator can use stringsstring [] array = {"Mike", "John", "Kathy"};

foreach(string one in array)

{

switch(one)

{

case "Mike": Console.write(one);

break;

case "John": Console.write(one);

break;

case "Kathy": Console.write(one);

break;

default: Console.write("Not found");

}

}

15

Modify1

using System;using System.Collections.Generic;using System.Text;

namespace ConsoleApplication1{ class Program { static void Main(string[] args) {

static string str = "Hello"; Console.Write(str);

} }}

16

Modify2

using System;using System.Collections.Generic;using System.Text;

namespace ConsoleApplication1{ class Program { static void Main(string[] args) {

if (args.Length>0) Console.Write(args[0]); else Console.Write("Hello");

} }}

17

Some C# Math functionsFunction Meaning

Math.Abs(x) Absolute value of x : |x|

Math.Sqrt(x) Square root of x

Math.Exp(x) Exponential value ex

Math.Pow(x, n) Power value xn

Math.Log(x) Ln(x): Natural logarithm of x

Math.Log10(x) Log10(x): logarithm of x in base of 10

Math.Ceiling(x) The smallest integer bigger or equal to x

Math.Floor(x) The largest integer less or equal to x

Math.Round(x) Round up integer of x

Math.Sin(x) sin(x) similar for cos(x) and tan(x)

Math::PI = 3.14159…..

Math.Max(x,y) Maximum of x and y

Math.Min(x,y) Minimum of x and y

Math.Sign(x) Sign of x

No Math.Random() function

18

Random class

Random class object is used to generate random integer, random floating number or random bytes.

Random rnd = new Random(); // Random object rnd

int n = rnd.Next(); // Random integer

int k = rnd.Next()%7; // Random integer 0-6

double d = rnd.NextDouble()

// Random double number between 0.0 and 1.0

Byte[] bArray = new Byte[10];

rnd.NextBytes(bArray);

// Now bArray is filled with 10 Random bytes

19

Most operators in C++ are good for C#

• =, +=, -=, *=, /= //assignment operators• ==, != // compare operators• <, <=, >, >=• +, - //signed operators• +, -, *, /, % // math operation• ++, --• <<, >> //shift operators• &, |, ^ // bitwise AND, OR, XOR

The following are new operators• Console.Readline() // standard input• Console.WriteLine() // standard output

20

Most Branch operators in C++ are also good for C#

• if(x>1 && y<2){ }• if(a<2 || b>3){ }• for loop• while loop• do while loop• switch • break in the loop• continue in the loop

All those operators are exactly same as in C++ or Java

Be careful that C# is case sensitive

21

MessageBox.ShowMessageBox.Show(

"Missing data input", // message string"input Error", // title caption stringMessageBoxButtons.OK, // button typeMessageBoxIcon.Exclamation // icon

);

Other buttons:MessageBoxButtons.AbortRetryIgnore MessageBoxButtons.OK MessageBoxButtons.OKCancel MessageBoxButtons.RetryCancel MessageBoxButtons.YesNo MessageBoxButtons.YesNoCancel

22

Other icons:MessageBoxIcon.Asterisk MessageBoxIcon.ErrorMessageBoxIcon.Exclamation MessageBoxIcon.Hand MessageBoxIcon.InformationMessageBoxIcon.None MessageBoxIcon.Question MessageBoxIcon.Stop

MessageBoxIcon.Warning

23

Return value of MessageBox

The return value type of MessageBox.Show() isDialogResult

which has the following values:DialogResult.Abort DialogResult.Cancel DialogResult.Ignore DialogResult.No DialogResult.None DialogResult.OK DialogResult.Retry DialogResult.Yes

24

Type converting

String to integer uses Int32.Parse(str);

String str = "1234";

try

{

int n = Int32.Parse(str);

}

catch(FormatException e)

{

Console.WriteLine(e.Message);

}

String to double uses Double.Parse(str)