23
The C# Language C# Language Basics Variables and Data Types Array, ArrayList, Enumerations Operator & Math Functions Type Conversions The DateTime and TimeSpan Types Conditional Logic • Loops Methods & Method Overloading Parameters (Optional & Named) • Delegates

C# basics

Embed Size (px)

Citation preview

Page 1: C# basics

The C# Language• C# Language Basics

• Variables and Data Types

• Array, ArrayList, Enumerations

• Operator & Math Functions

• Type Conversions

• The DateTime and TimeSpan Types

• Conditional Logic

• Loops

• Methods & Method Overloading

• Parameters (Optional & Named)

• Delegates

Page 2: C# basics

C# Language Basics• Case Sensitivity• Commenting

// A single-line C# comment./* A multiple-lineC# comment. */

• Statement Termination • Blocks

{// Code statements go here.}

• Declaration, Assignment & Initializersint errorCode;string myName;

errorCode = 10;myName = "Matthew";

int errorCode = 10;string myName ="Matthew";

Page 3: C# basics

Variables and Data Types

C# Type

VB Type

.Net System

type

Signed?

Bytes Occupied

Possible Values

sbytebyte

SByteByte

SByteByte

YesNo

11

-128 to 1270 to 255

short Short Int16 Yes 2 -32768 to 32767

int Integer Int32 Yes 4 -2147483648 to 2147483647

long Long Int64 Yes 8 -9223372036854775808 to

9223372036854775807

ushort UShort Uint16 No 2 0 to 65535

uint UInteger

UInt32 No 4 0 to 4294967295

ulong ULong Uint64 No 8 0 to 18446744073709551615

Page 4: C# basics

Variables and Data Types

C# Type

VB Type

.Net System

Type

Signed?

Bytes Occupie

d

Possible Values

float Float Single Yes 4 Approx. ±1.5 x 10-45 to ±3.4 x 1038 with 7 significant figures

double Double Double Yes 8 Approx. ±5.0 x 10-324 to ±1.7 x 10308 with 15 or 16 significant

figures

decimal

Decimal Decimal Yes 12 Approx. ±1.0 x 10-28 to ±7.9 x 1028 with 28 or 29 significant

figures

char Char Char N/A 2 Any Unicode character (16 bit)

bool Boolean Boolean N/A 1 / 2 true or false

Page 5: C# basics

Escaped Characters

• \" (double quote)• \n (new line)• \t (horizontal tab)• \\ (backward slash)

// A C# variable holding the// c:\MyApp\MyFiles path.path = "c:\\MyApp\\MyFiles";

Alternatively, you can turn off C# escaping by preceding a string with an @ symbol, as shown here:path = @"c:\MyApp\MyFiles";

Page 6: C# basics

ArraysArrays allow you to store a series of values that have the same data type.

// Create an array with four strings (from index 0 to index 3).// You need to initialize the array with the new keyword in order to use it.

string[] stringArray = new string[4];

// Create a 2x4 grid array (with a total of eight integers).int[,] intArray = new int[2, 4];

// Create an array with four strings, one for each number from 1 to 4.string[] stringArray = {"1", "2", "3", "4"};

// Create a 4x2 array (a grid with four rows and two columns).int[,] intArray = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};

Page 7: C# basics

ArrayList

ArrayList dynamicList = new ArrayList();// Add several strings to the list. The ArrayList is not strongly typed, so you can add any data type

dynamicList.Add("one");dynamicList.Add(2);dynamicList.Add(true);

// Retrieve the first string. Notice that the object must be converted to a// string, because there's no way for .NET to be certain what it is.

string item = Convert.ToString(dynamicList[0]);

Page 8: C# basics

Enumeration

An enumeration is a group of related constants, each of which is given a descriptive name. Each value in an enumeration corresponds to a preset integer.

enum UserType{Admin,Guest,Invalid}

Page 9: C# basics

Operators & Math functions+, -, *, / ,% are basic operators

To use the math operations, you invoke the methods of the System.Math class.

myValue = Math.Round(42.889, 2); // myValue = 42.89myValue = Math.Abs(-10); // myValue = 10.0myValue = Math.Log(24.212); // myValue = 3.18.. (and so on)myValue = Math.PI; // myValue = 3.14.. (and so on)

Page 10: C# basics

Type ConversionsConverting information from one data type to anotherConversions are of two types: widening and narrowing. Widening conversions always succeed. For example, you can always convert a 32-bit integer into a 64-bit integer.int mySmallValue;long myLargeValue;

mySmallValue = Int32.MaxValue;myLargeValue = mySmallValue;Or mySmallValue = (int)myLargeValue;

int myInt=1000;short count;count=(short)myInt;

Page 11: C# basics

Type ConversionsConverting information from one data type to another

String myString;int myInteger=100;

myString=myInteger.ToString();

String countString=“10”;int count=Convert.ToInt32(countString);

or

int count=Int32.Parse(countString);

Page 12: C# basics

String Functions

Length() : myString.Length()ToUpper(), ToLower() myString.ToUpper()

Trim() myString.Trim()Substring()

myString.SubString(0,2)StartsWith(), EndsWith()

myString.StartsWith(“pre”)PadLeft(), PadRight()

myString.PadLeft(5,”*”)Insert()

myString.Insert(1,”pre)Remove()

myString.Remove(0,2)Split() myString.Split(“,”)Join()

myString1.Join(myString2)Replace()

myString.Replace(“a”,”b”)

Page 13: C# basics

DateTime and TimeSpan TypesDateTime and Timespane data types have built-in methods and properties

Methods & Properties of DateTime :NowTodayYear, Date, Month ,Hour, Minute, Second, and Millisecond Add() and Subtract()AddYears(), AddMonths(), AddDays(), AddHours, AddMinutes()DaysIn Month()

Methods and Properties of TimeSpan:Days, Hours, Minutes, Seconds, MillisecondsTotalDays, TotalHours, TotalMinutes, TotalSeconds, TotalMillisecondsAdd() and Subtract()FromDays(), FromHours(), From Minutes(), FromSeconds()

Page 14: C# basics

DateTime and TimeSpan TypesDateTime myDate = DateTime.Now;myDate = myDate.AddDays(100);DateTime myDate2 = DateTime.Now.AddHours(3000);

TimeSpan difference;difference = myDate2.Subtract(myDate1);double numberOfMinutes;numberOfMinutes = difference.TotalMinutes;

// Adding a TimeSpan to a DateTime creates a new DateTime.DateTime myDate1 = DateTime.Now;TimeSpan interval = TimeSpan.FromHours(3000);DateTime myDate2 = myDate1 + interval;// Subtracting one DateTime object from another produces a TimeSpan.TimeSpan difference;difference = myDate2 - myDate1;

Page 15: C# basics

Conditional Logic

All conditional logic starts with a condition: a simple expression that can be evaluated to true or false. Your code can then make a decision to execute different logic depending on the outcome of the condition. To build a condition, you can use any combination of literal values or variables along with logical operators

== Equal to!= Not Equal to< Less than> Greater than<= Less than or equal to>= Greater than or equal to&& Logical and|| Logical or

Page 16: C# basics

Conditional Logic

The if Statement

if (myNumber > 10){// Do something.}else if (myString == "hello"){// Do something.}else{// Do something

The switch Statement

switch (myNumber){case 1:// Do something.break;case 2:// Do something.break;default:// Do something.break;}

Page 17: C# basics

LoopsLoops allow you to repeat a segment of code multiple times. C# has three basic types of loops• You can loop a set number of times with a for loop.• You can loop through all the items in a collection of

data using a foreach loop.• You can loop while a certain condition holds true

with a while or do…while loop.

THE FOR LOOPstring[] stringArray = {"one", "two", "three"};

for (int i = 0; i < stringArray.Length; i++){System.Diagnostics.Debug.Write(stringArray[i] );}THE FOREACH LOOPforeach (string element in stringArray){System.Diagnostics.Debug.Write(element );}

Page 18: C# basics

LoopsTHE WHILE LOOPint i = 0;while (i < 10){i += 1;// This code executes ten times.}

You can also place the condition at the end of the loop using the do…while syntax. In this case, thecondition is tested at the end of each pass through the loop:THE DO WHILE LOOPint i = 0;do{i += 1;// This code executes ten times.}while (i < 10);

Page 19: C# basics

MethodsA method also known as function is a named grouping of one or more lines of code. Each method will perform a distinct, logical task.

By breaking your code down into methods, you not only simplify your life, but you also make it easier to organize your code into classes// This method doesn't return any information.void MyMethodNoReturnedData(){// Code goes here.}// This method returns an integer.int MyMethodReturnedData(){// As an example, return the number 10.return 10;}

Page 20: C# basics

ParameterOptional Parameter

private string GetUserName(int ID, bool useShortForm = false){ // Code here.}name = GetUserName(401, true);name = GetUserName(401);

Use Named parameter for multiple optional parameters:

private decimal GetSalesTotalForRegion(int regionID, decimal minSale = 0,decimal maxSale = Decimal.MaxValue, bool includeTax = false){ // Code here.}

total = GetSalesTotalForRegion(523, maxSale: 5000);

Page 21: C# basics

DelegatesDelegates allow you to create a variable that “points” to a method.

private string TranslateEnglishToFrench();{}

private delegate string translateLanguage(string inputString);translateLanguage translate;

translate=TranslateEnglishToFrench;string frenchString;frenchString=translate(“Hello”);

You can make delegate point to any other function also if it has same signature

Page 22: C# basics

Delegatesprivate string TranslateEnglishToSpanish();{}

translate=TranslateEnglishToSpanish;string spanishString;spanishString=translate(“Hello”);

private string TranslateEnglishToGerman();{}

translate=TranslateEnglishToGerman;string germanString;germanString=translate(“Hello”);

Page 23: C# basics

Summary

It’s impossible to do justice to an entire language in a single chapter. However, if you’ve programmed before, you’ll find that this chapter provides all the information you need to get started with the C# language. As you work through the full ASP.NET examples in the following chapters, you can refer to this chapter to clear up any language issues.

In the next chapter, you’ll learn about more important language concepts and the object-oriented nature of .NET.