SlideShare a Scribd company logo
Core C# and .NET
Quick Reference
1. Data Types
Primitive Size Example
string 2 bytes/char s = “reference”;
bool b = true;
char 2 bytes ch = ‘a’;
byte 1 byte b = 0x78;
short 2 bytes Ival = 54;
int 4 bytes Ival = 540;
long 8 bytes ival = 5400;
float 4 bytes val = 54.0F;
double 8 bytes val = 54.0D;
decimal 16 bytes val = 54.0M;
2. Arrays
Declaration
int[] numArray = {1903, 1907, 1910};
int[] numArray = new int[3];
// 3 rows and 2 columns
int[ , ] nums = {{1907, 1990}, {1904, 1986}, {1910, 1980}};
Array Operations
Array.Sort(numArray); // sort ascending
// Sort begins at element 4 and sorts 10 elements
Array.Sort(numArray, 4,10);
// Use one array as a key and sort two arrays
string[] values = {“Cary”, “Gary”, “Barbara”};
string[] keys = {“Grant”, “Cooper”, “Stanwyck”};
Array.Sort(keys, values);
// Clear elements in array (array, 1st
element, # elements)
Array.Clear(numArray, 0, numArray.Length);
// Copy elements from one array to another
Array.Copy(src, target, numelements);
3. String Operations
Method Description
Compare String.Compare(stra, strb, case, ci)
bool case – true for case insensitive
ci – new CultureInfo(“en-US”)
returns: <0 if a<b, 0 if a=b, 1 if a>b
IndexOf str.IndexOf(val, start, num)
val – string to search for
start – where to begin in string
num – number of chars to search
returns (–1) if no match.
LastIndexOf Search from end of string.
Replace newstr= oldstr.Replace(“old”,”new”);
Split Char[] delim= {‘ ‘, ‘,’};
string w = “Kim, Joanna Leslie”;
// create array with three names
string[] names= w.Split(delim);
6. Formatting Numeric and Date Values
Format Item Syntax: {index[,alignment] [:format string]}
index – Specifies element in list of values to which format is applied.
alignment – Indicates minimum width (in characters) to display value.
format string – Contains the code that specifies the format of the displayed value.
Example: String.Format(“Price is: {0:C2}”, 49.95); // output: Price is: $ 49.95
a. Numeric Formatting
Format
Specifier
Pattern Value Description
C or c {0:C2}, 1388.55 $ 1388.55 Currency.
D or d {0:D5}, 45 00045 Must be integer value.
E or e {0,9:E2}, 1388.55 1.39+E003 Must be floating point.
F or f {0,9:F2}, 1388.55 1388.55 Fixed Point representation.
N or n {0,9:N1}, 1388.55 1,388.6 Insert commas
P or p {0,9:P3}, .7865 78.650% Converts to percent.
R or r {0,9:R}, 3.14159 3.14159 Retains all decimal places.
X or x {0,9:X4}, 31 001f Converts to Hex
Example: CultureInfo ci = new CultureInfo("de-DE"); // German culture
string curdt = String.Format(ci,"{0:M}",DateTime.Now); // 29 Juni
b. DateTime Formatting: (January 19, 2005 16:05:20) en-US
Format Value Displayed Format Value Displayed
d 1/19/2005 Y or y January, 2005
D Wednesday, January
19, 2005
t 4:05 PM
f Wednesday, January
19, 2005 4:05:20 PM
T 4:05:20 PM
F Wednesday, January
19, 2005 4:05 PM
s 2005-01-19T16:05:20
g 1/19/2005 4:05 PM u 2005-01-19 16:05:20Z
G 1/19/2005 4:05:20 PM U Wednesday, January
19, 2005 21:05:20PM
M or m January 19
7. Using the System.Text.RegularExpressions.Regex class
string zipexp = @"d{5}((-|s)?d{4})?$";
string addr="W.44th St, New York, NY 10017-0233";
Match m = Regex.Match(addr,zipexp); // Static method
Regex zipRegex= new Regex(zipexp);
m= zipRegex.Match(addr); // Use Regex Object
Console.WriteLine(m.Value); // 10017-0233
Pattern Description Example
+ Match one or more occurrence ab+c matches abc, abbc
* Match zero or more occurrences ab*c matches ac, abbc
? Matches zero or one occurrence ab?c matches ac, abc
d D Match decimal digit or non-digit (D) dd matches 01, 55
w W Match any word character or non-char w equals [a-zA-Z0-9_]
s S Match whitespace or non-whitespace d*sd+ matches 246 98
[ ] Match any character in set [aeiou]n matches in, on
[^ ] Match any character not in set [^aeiou] matches r or 2
a | b Either a or b jpg|jpeg|gif matches .jpg
n r t New line, carriage return, tab
Method Description
Substring mystring.Substring(ndx, len)
string alpha = “abcdef”;
// returns “cdef”
string s= alpha.Substring(2);
// returns “de”
s = alpha.Substring(3,2);
ToCharArray Places selected characters in a string
in a char array:
String vowel = “aeiou”;
// create array of 5 vowels
char[] c = vowel.ToCharArray();
// create array of ‘i’ and ‘o’.
char[] c = vowel.ToCharArray(2,2);
4. System.Text.StringBuilder
Constructor
StringBuilder sb = new StringBuilder();
StringBuilder sb = new StringBuilder(mystring);
StringBuilder sb = new StringBuilder(mystring,capacity);
mystring – Initial value of StringBuilder object
capacity – Initial size (characters) of buffer.
Using StringBuilderMembers
decimal bmi = 22.2M;
int wt=168;
StringBuilder sb = new StringBuilder(“My weight is ”);
sb = sb.Append(wt); // can append number
sb= sb.Append(“ and my bmi is ”).Append(bmi);
// my weight is 168 and my bmi is 22.2
sb= sb.Replace(“22.2”,”22.4”);
string s = sb.ToString();
// Clear and set to new value
sb.Length=0;
sb.Append(“Xanadu”);
5. DateTime and TimeSpan
DateTime Constructor
DateTime(yr, mo, day)
DateTime(yr, mo, day, hr, min, sec)
DateTime bday = new DateTime(1964,12,20,11,2,0);
DateTime newyr= DateTime.Parse(“1/1/2005”);
DateTime currdt = DateTime.Now;
// also AddHours, AddMonths, AddYears
DateTime tomorrow = currdt.AddDays(1);
TimeSpan diff = currdt.Subtract(bday);
// 14795 days from 12/20/64 to 6/24/05
Console.WriteLine(“{0}”, diff.Days);
// TimeSpan(hrs, min, sec)
TimeSpan ts = new TimeSpan(6, 30, 10);
// also FromMinutes, FromHours, FromDays
TimeSpan ts = TimeSpan.FromSeconds(120);
TimeSpan ts = ts2 – ts1; // +,-,>,<,==, !=
8. Using the C# Compiler at the Command Line
C:>csc /t:library /out:reslib.dll mysource.cs
csc /t:winexe /r:ctls1.dll /r:ctls2.dll winapp.cs
csc /keyfile:strongkey.snk secure.cs
Option Description
/addmodule Import metadata from a file that does
not contain a manifest.
/debug Tells compiler to emit debugging info.
/doc Specifies an XML documentation file
to be created during compilation.
/keyfile Specifies file containing key used to
create a strong named assembly.
/lib Specifies directory to search for
external referenced assemblies.
/out Name of compiled output file.
/reference (/r) Reference to an external assembly.
/resource Resource file to embed in output.
/target (/t) /t:exe /t:library /t:module /t:winexe
9. C# Language Fundamentals
Control Flow Statements
switch (expression)
{ case expression:
// statements
break / goto / return()
case ...
default:
// statements
break / goto / return()
}
expression may be
integer, string, or enum.
switch (genre)
{
case “vhs”:
price= 10.00M;
break;
case “dvd”:
price=16.00M;
break;
default:
price=12.00M:
break;
}
if (condition) {
// statements
} else {
// statements
}
if (genre==”vhs”)
price=10.00M;
else if (genre==”dvd”)
price=16.00M;
else price=12.00M;
Loop Constructs
while (condition)
{ body }
do { body }
while (condition);
while ( ct < 8)
{ tot += ct; ct++; }
do { tot += ct; ct++;}
while (ct < 8);
11. Delegates and Events
Delegates
[modifiers] delegate result-type delegate name ([parameter list]);
// (1) Define a delegate that calls method(s) having a single string parameter
public delegate void StringPrinter(string s);
// (2) Register methods to be called by delegate
StringPrinter prt = new StringPrinter(PrintLower);
prt += new StringPrinter(PrintUpper);
prt(“Copyright was obtained in 2005”); / / execute PrintLower and PrintUpper
Using Anonymous Methods with a Delegate
Rather than calling a method, a delegate encapsulates code that is executed:
prt = delegate(string s) { Console.WriteLine(s.ToLower()); };
prt += delegate(string s) { Console.WriteLine(s.ToUpper()); };
prt(“Print this in lower and upper case.”);
Events
// class.event += new delegate(event handler method);
Button Total = new Button();
Total.Click += new EventHandler(GetTotal);
// Event Handler method must have signature specified by delegate
private void GetTotal( object sender, EventArgs e) {
Commonly used Control Events
Event Delegate
Click, MouseEnter
DoubleClick, MouseLeave
EventHandler( object sender, EventArgs e)
MouseDown, Mouseup,
MouseMove
MouseEventHandler(object sender,
MouseEventArgs e)
e.X, e.Y – x and y coordinates
e.Button – MouseButton.Left, Middle, Right
KeyUp, KeyDown KeyEventHandler(object sndr, KeyEventArgs e)
e.Handled – Indicates whether event is handled.
e.KeyCode – Keys enumeration, e.g., Keys.V
e.Modifiers – Indicates if Alt, Ctrl, or Shift key.
KeyPress KeyPressEventHandler(object sender,
KeyPressEventArgs e)
12. struct
[attribute][modifier] struct name [:interfaces] { struct-body}
Differences from class:
• is a value type • cannot inherit from a class or be inherited
• fields cannot have initializer • explicit constructor must have a parameter
13. enum (Enumerated Type)
enum enum Operations
enum Fabric: int {
cotton = 1,
silk = 2,
wool = 4,
rayon = 8
}
int cotNum = (int) Fabric.cotton; // 1
string cotName = Fabric.cotton.ToString(); // cotton
string s = Enum.GetName(typeof(Fabric),2); // silk
// Create instance of wool enum if it is valid
if(Enum.IsDefined(typeof(Fabric), “wool”) Fabric woolFab
= (Fabric)Enum.Parse(typeof(Fabric),”wool”);
Loop Constructs (Continued)
for (initializer;
termination condition;
iteration;)
{ // statements }
foreach (type identifier in
collection)
{ // statements }
for (int i=0;i<8;i++)
{
tot += i;
}
int[] ages = {27, 33, 44};
foreach(int age in ages)
{ tot += age; }
10. C# Class Definition
Class
[public | protected | internal | private]
[abstract | sealed | static]
class class name [:class/interfaces inherited from]
Constructor
[access modifier] class name (parameters) [:initializer]
initializer – base calls constructor in base class.
this calls constructor within class.
public class Shirt: Apparel {
public Shirt(decimal p, string v) : base(p,v)
{ constructor body }
Method
[access modifier]
[static | virtual | override | new | sealed | abstract ]
method name (parameter list) { body }
virtual – method can be overridden in subclass.
override – overrides virtual method in base class.
new – hides non-virtual method in base class.
sealed – prevents derived class from inheriting.
abstract – must be implemented by subclass.
Passing Parameters:
a. By default, parameters are passed by value.
b. Passing by reference: ref and out modifiers
string id= “gm”; // caller initializes ref
int weight; // called method initializes
GetFactor(ref id, out weight);
// ... other code here
static void GetFactor(ref string id, out int wt)
{
if (id==”gm”) wt = 454; else wt=1;
return;
}
Property
[modifier] <datatype> property name {
public string VendorName
{
get { return vendorName; }
set { vendorName = value; } // note value keyword
}
Ad

More Related Content

What's hot (20)

Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
 
Declarative Type System Specification with Statix
Declarative Type System Specification with StatixDeclarative Type System Specification with Statix
Declarative Type System Specification with Statix
Eelco Visser
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
Han Lee
 
Cbse question-paper-computer-science-2009
Cbse question-paper-computer-science-2009Cbse question-paper-computer-science-2009
Cbse question-paper-computer-science-2009
Deepak Singh
 
Fp201 unit5 1
Fp201 unit5 1Fp201 unit5 1
Fp201 unit5 1
rohassanie
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New Game
John De Goes
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paper
Deepak Singh
 
C Prog - Pointers
C Prog - PointersC Prog - Pointers
C Prog - Pointers
vinay arora
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
rohassanie
 
Programming with GUTs
Programming with GUTsProgramming with GUTs
Programming with GUTs
Kevlin Henney
 
TypeScript by Howard
TypeScript by HowardTypeScript by Howard
TypeScript by Howard
LearningTech
 
Hadoop Pig
Hadoop PigHadoop Pig
Hadoop Pig
Mathias Herberts
 
Type script by Howard
Type script by HowardType script by Howard
Type script by Howard
LearningTech
 
C tech questions
C tech questionsC tech questions
C tech questions
vijay00791
 
Arrays
ArraysArrays
Arrays
AnaraAlam
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in Python
Siddhi
 
Strings in C
Strings in CStrings in C
Strings in C
Aditya Nihal Kumar Singh
 
Advanced python
Advanced pythonAdvanced python
Advanced python
EU Edge
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
ssuserd6b1fd
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
Warui Maina
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Chris Adamson
 
Declarative Type System Specification with Statix
Declarative Type System Specification with StatixDeclarative Type System Specification with Statix
Declarative Type System Specification with Statix
Eelco Visser
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
Han Lee
 
Cbse question-paper-computer-science-2009
Cbse question-paper-computer-science-2009Cbse question-paper-computer-science-2009
Cbse question-paper-computer-science-2009
Deepak Singh
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New GameScalaz 8: A Whole New Game
Scalaz 8: A Whole New Game
John De Goes
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paper
Deepak Singh
 
C Prog - Pointers
C Prog - PointersC Prog - Pointers
C Prog - Pointers
vinay arora
 
FP 201 - Unit 6
FP 201 - Unit 6FP 201 - Unit 6
FP 201 - Unit 6
rohassanie
 
Programming with GUTs
Programming with GUTsProgramming with GUTs
Programming with GUTs
Kevlin Henney
 
TypeScript by Howard
TypeScript by HowardTypeScript by Howard
TypeScript by Howard
LearningTech
 
Type script by Howard
Type script by HowardType script by Howard
Type script by Howard
LearningTech
 
C tech questions
C tech questionsC tech questions
C tech questions
vijay00791
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in Python
Siddhi
 
Advanced python
Advanced pythonAdvanced python
Advanced python
EU Edge
 
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
ssuserd6b1fd
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
Warui Maina
 

Viewers also liked (16)

__StefanieAmbrois_A5
__StefanieAmbrois_A5__StefanieAmbrois_A5
__StefanieAmbrois_A5
Stefanie Ambrois
 
Felicidades(sf)
Felicidades(sf)Felicidades(sf)
Felicidades(sf)
Jacinta Torres
 
Android development, Android
Android development, AndroidAndroid development, Android
Android development, Android
NetConnectWeb
 
Curso online de Transporte Pediátrico y Neonatal
Curso online de Transporte Pediátrico y NeonatalCurso online de Transporte Pediátrico y Neonatal
Curso online de Transporte Pediátrico y Neonatal
spars
 
Marketing relacional
Marketing relacionalMarketing relacional
Marketing relacional
kevinver92
 
Informe sobre detenciones arbitrarias y otros abusos cometidos en cuba en sep...
Informe sobre detenciones arbitrarias y otros abusos cometidos en cuba en sep...Informe sobre detenciones arbitrarias y otros abusos cometidos en cuba en sep...
Informe sobre detenciones arbitrarias y otros abusos cometidos en cuba en sep...
Roberto Guerra
 
An investigation of diachronic change in hypotaxis and parataxis in German th...
An investigation of diachronic change in hypotaxis and parataxis in German th...An investigation of diachronic change in hypotaxis and parataxis in German th...
An investigation of diachronic change in hypotaxis and parataxis in German th...
Mario Bisiada
 
Pio
PioPio
Pio
Monina Gallegos
 
Nombramientos
NombramientosNombramientos
Nombramientos
Francisco Navarro Garcia
 
рейтинговая система отбора (1)
рейтинговая система отбора (1)рейтинговая система отбора (1)
рейтинговая система отбора (1)
Titenko1
 
Folleto Juan Rulfo
Folleto Juan RulfoFolleto Juan Rulfo
Folleto Juan Rulfo
Javiera Ossandón Vadivia
 
History of ELT in bangladesh
History of ELT in bangladeshHistory of ELT in bangladesh
History of ELT in bangladesh
Myno Uddin
 
Logo Designing In India| Creative Designing in Raipur
Logo Designing In India| Creative Designing in RaipurLogo Designing In India| Creative Designing in Raipur
Logo Designing In India| Creative Designing in Raipur
Aakaash sharma
 
Big Data Analytics in Healthcare
Big Data Analytics in HealthcareBig Data Analytics in Healthcare
Big Data Analytics in Healthcare
Altoros
 
Словник емоційно-образних визначень музики
Словник емоційно-образних визначень музикиСловник емоційно-образних визначень музики
Словник емоційно-образних визначень музики
nataliyu roschina
 
Cookie Directive - IdealObserver
Cookie Directive - IdealObserverCookie Directive - IdealObserver
Cookie Directive - IdealObserver
IdealObserver
 
Android development, Android
Android development, AndroidAndroid development, Android
Android development, Android
NetConnectWeb
 
Curso online de Transporte Pediátrico y Neonatal
Curso online de Transporte Pediátrico y NeonatalCurso online de Transporte Pediátrico y Neonatal
Curso online de Transporte Pediátrico y Neonatal
spars
 
Marketing relacional
Marketing relacionalMarketing relacional
Marketing relacional
kevinver92
 
Informe sobre detenciones arbitrarias y otros abusos cometidos en cuba en sep...
Informe sobre detenciones arbitrarias y otros abusos cometidos en cuba en sep...Informe sobre detenciones arbitrarias y otros abusos cometidos en cuba en sep...
Informe sobre detenciones arbitrarias y otros abusos cometidos en cuba en sep...
Roberto Guerra
 
An investigation of diachronic change in hypotaxis and parataxis in German th...
An investigation of diachronic change in hypotaxis and parataxis in German th...An investigation of diachronic change in hypotaxis and parataxis in German th...
An investigation of diachronic change in hypotaxis and parataxis in German th...
Mario Bisiada
 
рейтинговая система отбора (1)
рейтинговая система отбора (1)рейтинговая система отбора (1)
рейтинговая система отбора (1)
Titenko1
 
History of ELT in bangladesh
History of ELT in bangladeshHistory of ELT in bangladesh
History of ELT in bangladesh
Myno Uddin
 
Logo Designing In India| Creative Designing in Raipur
Logo Designing In India| Creative Designing in RaipurLogo Designing In India| Creative Designing in Raipur
Logo Designing In India| Creative Designing in Raipur
Aakaash sharma
 
Big Data Analytics in Healthcare
Big Data Analytics in HealthcareBig Data Analytics in Healthcare
Big Data Analytics in Healthcare
Altoros
 
Словник емоційно-образних визначень музики
Словник емоційно-образних визначень музикиСловник емоційно-образних визначень музики
Словник емоційно-образних визначень музики
nataliyu roschina
 
Cookie Directive - IdealObserver
Cookie Directive - IdealObserverCookie Directive - IdealObserver
Cookie Directive - IdealObserver
IdealObserver
 
Ad

Similar to Core c sharp and .net quick reference (20)

C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
Saifur Rahman
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
rajatryadav22
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
BAINIDA
 
19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.ppt19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.ppt
AqeelAbbas94
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogram
princepavan
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogram
princepavan
 
Arrays
ArraysArrays
Arrays
Chukka Nikhil Chakravarthy
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
GlobalLogic Ukraine
 
PPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdf
PPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdfPPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdf
PPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdf
YashShekhar6
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScript
Aleš Najmann
 
C language first program
C language first programC language first program
C language first program
NIKHIL KRISHNA
 
Tut1
Tut1Tut1
Tut1
Still Abir
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
Mohamed Krar
 
Unit 3 arrays and_string
Unit 3 arrays and_stringUnit 3 arrays and_string
Unit 3 arrays and_string
kirthika jeyenth
 
PPS 4.4ARRAYS ARRAY DECLARATION & INITIALIZATION, BOUND CHECKING ARRAYS (1-D...
PPS 4.4ARRAYS  ARRAY DECLARATION & INITIALIZATION, BOUND CHECKING ARRAYS (1-D...PPS 4.4ARRAYS  ARRAY DECLARATION & INITIALIZATION, BOUND CHECKING ARRAYS (1-D...
PPS 4.4ARRAYS ARRAY DECLARATION & INITIALIZATION, BOUND CHECKING ARRAYS (1-D...
Sitamarhi Institute of Technology
 
Array
ArrayArray
Array
Vivian Chia En Chiang
 
unit-5 String Math Date Time AI presentation
unit-5 String Math Date Time AI presentationunit-5 String Math Date Time AI presentation
unit-5 String Math Date Time AI presentation
MukeshTheLioner
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
AmIt Prasad
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
Intro C# Book
 
C Programming Unit-3
C Programming Unit-3C Programming Unit-3
C Programming Unit-3
Vikram Nandini
 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
Saifur Rahman
 
The best every notes on c language is here check it out
The best every notes on c language is here check it outThe best every notes on c language is here check it out
The best every notes on c language is here check it out
rajatryadav22
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
BAINIDA
 
19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.ppt19-Lec - Multidimensional Arrays.ppt
19-Lec - Multidimensional Arrays.ppt
AqeelAbbas94
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogram
princepavan
 
T02 a firstcprogram
T02 a firstcprogramT02 a firstcprogram
T02 a firstcprogram
princepavan
 
PPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdf
PPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdfPPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdf
PPS SSSSHHEHESHSHEHHEHAKAKHEHE12131415.pdf
YashShekhar6
 
Back to the Future with TypeScript
Back to the Future with TypeScriptBack to the Future with TypeScript
Back to the Future with TypeScript
Aleš Najmann
 
C language first program
C language first programC language first program
C language first program
NIKHIL KRISHNA
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
Mohamed Krar
 
PPS 4.4ARRAYS ARRAY DECLARATION & INITIALIZATION, BOUND CHECKING ARRAYS (1-D...
PPS 4.4ARRAYS  ARRAY DECLARATION & INITIALIZATION, BOUND CHECKING ARRAYS (1-D...PPS 4.4ARRAYS  ARRAY DECLARATION & INITIALIZATION, BOUND CHECKING ARRAYS (1-D...
PPS 4.4ARRAYS ARRAY DECLARATION & INITIALIZATION, BOUND CHECKING ARRAYS (1-D...
Sitamarhi Institute of Technology
 
unit-5 String Math Date Time AI presentation
unit-5 String Math Date Time AI presentationunit-5 String Math Date Time AI presentation
unit-5 String Math Date Time AI presentation
MukeshTheLioner
 
46630497 fun-pointer-1
46630497 fun-pointer-146630497 fun-pointer-1
46630497 fun-pointer-1
AmIt Prasad
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
Intro C# Book
 
Ad

More from Arduino Aficionado (15)

Garagino doc
Garagino docGaragino doc
Garagino doc
Arduino Aficionado
 
Netfx4
Netfx4Netfx4
Netfx4
Arduino Aficionado
 
Ubunturef
UbunturefUbunturef
Ubunturef
Arduino Aficionado
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
Arduino Aficionado
 
Xm lquickref
Xm lquickrefXm lquickref
Xm lquickref
Arduino Aficionado
 
Html xhtml tag-sheet
Html xhtml tag-sheetHtml xhtml tag-sheet
Html xhtml tag-sheet
Arduino Aficionado
 
Unix command quickref
Unix command quickrefUnix command quickref
Unix command quickref
Arduino Aficionado
 
Ruby on rails_cheat_sheet
Ruby on rails_cheat_sheetRuby on rails_cheat_sheet
Ruby on rails_cheat_sheet
Arduino Aficionado
 
Pqrc 2.4-a4-latest
Pqrc 2.4-a4-latestPqrc 2.4-a4-latest
Pqrc 2.4-a4-latest
Arduino Aficionado
 
Nmap5.cheatsheet.eng.v1
Nmap5.cheatsheet.eng.v1Nmap5.cheatsheet.eng.v1
Nmap5.cheatsheet.eng.v1
Arduino Aficionado
 
Matlab quickref
Matlab quickrefMatlab quickref
Matlab quickref
Arduino Aficionado
 
Java quickref
Java quickrefJava quickref
Java quickref
Arduino Aficionado
 
Eclipse emacskeybindings 3_1
Eclipse emacskeybindings 3_1Eclipse emacskeybindings 3_1
Eclipse emacskeybindings 3_1
Arduino Aficionado
 
Refcard en-a4
Refcard en-a4Refcard en-a4
Refcard en-a4
Arduino Aficionado
 
Cpp reference sheet
Cpp reference sheetCpp reference sheet
Cpp reference sheet
Arduino Aficionado
 

Recently uploaded (20)

Play It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google CertificatePlay It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google Certificate
VICTOR MAESTRE RAMIREZ
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
AI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdfAI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdf
Precisely
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Financial Services Technology Summit 2025
Financial Services Technology Summit 2025Financial Services Technology Summit 2025
Financial Services Technology Summit 2025
Ray Bugg
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and MLGyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
Gyrus AI
 
Connect and Protect: Networks and Network Security
Connect and Protect: Networks and Network SecurityConnect and Protect: Networks and Network Security
Connect and Protect: Networks and Network Security
VICTOR MAESTRE RAMIREZ
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
TrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token ListingTrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token Listing
Trs Labs
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
Play It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google CertificatePlay It Safe: Manage Security Risks - Google Certificate
Play It Safe: Manage Security Risks - Google Certificate
VICTOR MAESTRE RAMIREZ
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
AI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdfAI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdf
Precisely
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Financial Services Technology Summit 2025
Financial Services Technology Summit 2025Financial Services Technology Summit 2025
Financial Services Technology Summit 2025
Ray Bugg
 
Generative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in BusinessGenerative Artificial Intelligence (GenAI) in Business
Generative Artificial Intelligence (GenAI) in Business
Dr. Tathagat Varma
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and MLGyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
GyrusAI - Broadcasting & Streaming Applications Driven by AI and ML
Gyrus AI
 
Connect and Protect: Networks and Network Security
Connect and Protect: Networks and Network SecurityConnect and Protect: Networks and Network Security
Connect and Protect: Networks and Network Security
VICTOR MAESTRE RAMIREZ
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
TrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token ListingTrsLabs Consultants - DeFi, WEb3, Token Listing
TrsLabs Consultants - DeFi, WEb3, Token Listing
Trs Labs
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 

Core c sharp and .net quick reference

  • 1. Core C# and .NET Quick Reference 1. Data Types Primitive Size Example string 2 bytes/char s = “reference”; bool b = true; char 2 bytes ch = ‘a’; byte 1 byte b = 0x78; short 2 bytes Ival = 54; int 4 bytes Ival = 540; long 8 bytes ival = 5400; float 4 bytes val = 54.0F; double 8 bytes val = 54.0D; decimal 16 bytes val = 54.0M; 2. Arrays Declaration int[] numArray = {1903, 1907, 1910}; int[] numArray = new int[3]; // 3 rows and 2 columns int[ , ] nums = {{1907, 1990}, {1904, 1986}, {1910, 1980}}; Array Operations Array.Sort(numArray); // sort ascending // Sort begins at element 4 and sorts 10 elements Array.Sort(numArray, 4,10); // Use one array as a key and sort two arrays string[] values = {“Cary”, “Gary”, “Barbara”}; string[] keys = {“Grant”, “Cooper”, “Stanwyck”}; Array.Sort(keys, values); // Clear elements in array (array, 1st element, # elements) Array.Clear(numArray, 0, numArray.Length); // Copy elements from one array to another Array.Copy(src, target, numelements); 3. String Operations Method Description Compare String.Compare(stra, strb, case, ci) bool case – true for case insensitive ci – new CultureInfo(“en-US”) returns: <0 if a<b, 0 if a=b, 1 if a>b IndexOf str.IndexOf(val, start, num) val – string to search for start – where to begin in string num – number of chars to search returns (–1) if no match. LastIndexOf Search from end of string. Replace newstr= oldstr.Replace(“old”,”new”); Split Char[] delim= {‘ ‘, ‘,’}; string w = “Kim, Joanna Leslie”; // create array with three names string[] names= w.Split(delim); 6. Formatting Numeric and Date Values Format Item Syntax: {index[,alignment] [:format string]} index – Specifies element in list of values to which format is applied. alignment – Indicates minimum width (in characters) to display value. format string – Contains the code that specifies the format of the displayed value. Example: String.Format(“Price is: {0:C2}”, 49.95); // output: Price is: $ 49.95 a. Numeric Formatting Format Specifier Pattern Value Description C or c {0:C2}, 1388.55 $ 1388.55 Currency. D or d {0:D5}, 45 00045 Must be integer value. E or e {0,9:E2}, 1388.55 1.39+E003 Must be floating point. F or f {0,9:F2}, 1388.55 1388.55 Fixed Point representation. N or n {0,9:N1}, 1388.55 1,388.6 Insert commas P or p {0,9:P3}, .7865 78.650% Converts to percent. R or r {0,9:R}, 3.14159 3.14159 Retains all decimal places. X or x {0,9:X4}, 31 001f Converts to Hex Example: CultureInfo ci = new CultureInfo("de-DE"); // German culture string curdt = String.Format(ci,"{0:M}",DateTime.Now); // 29 Juni b. DateTime Formatting: (January 19, 2005 16:05:20) en-US Format Value Displayed Format Value Displayed d 1/19/2005 Y or y January, 2005 D Wednesday, January 19, 2005 t 4:05 PM f Wednesday, January 19, 2005 4:05:20 PM T 4:05:20 PM F Wednesday, January 19, 2005 4:05 PM s 2005-01-19T16:05:20 g 1/19/2005 4:05 PM u 2005-01-19 16:05:20Z G 1/19/2005 4:05:20 PM U Wednesday, January 19, 2005 21:05:20PM M or m January 19 7. Using the System.Text.RegularExpressions.Regex class string zipexp = @"d{5}((-|s)?d{4})?$"; string addr="W.44th St, New York, NY 10017-0233"; Match m = Regex.Match(addr,zipexp); // Static method Regex zipRegex= new Regex(zipexp); m= zipRegex.Match(addr); // Use Regex Object Console.WriteLine(m.Value); // 10017-0233 Pattern Description Example + Match one or more occurrence ab+c matches abc, abbc * Match zero or more occurrences ab*c matches ac, abbc ? Matches zero or one occurrence ab?c matches ac, abc d D Match decimal digit or non-digit (D) dd matches 01, 55 w W Match any word character or non-char w equals [a-zA-Z0-9_] s S Match whitespace or non-whitespace d*sd+ matches 246 98 [ ] Match any character in set [aeiou]n matches in, on [^ ] Match any character not in set [^aeiou] matches r or 2 a | b Either a or b jpg|jpeg|gif matches .jpg n r t New line, carriage return, tab Method Description Substring mystring.Substring(ndx, len) string alpha = “abcdef”; // returns “cdef” string s= alpha.Substring(2); // returns “de” s = alpha.Substring(3,2); ToCharArray Places selected characters in a string in a char array: String vowel = “aeiou”; // create array of 5 vowels char[] c = vowel.ToCharArray(); // create array of ‘i’ and ‘o’. char[] c = vowel.ToCharArray(2,2); 4. System.Text.StringBuilder Constructor StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder(mystring); StringBuilder sb = new StringBuilder(mystring,capacity); mystring – Initial value of StringBuilder object capacity – Initial size (characters) of buffer. Using StringBuilderMembers decimal bmi = 22.2M; int wt=168; StringBuilder sb = new StringBuilder(“My weight is ”); sb = sb.Append(wt); // can append number sb= sb.Append(“ and my bmi is ”).Append(bmi); // my weight is 168 and my bmi is 22.2 sb= sb.Replace(“22.2”,”22.4”); string s = sb.ToString(); // Clear and set to new value sb.Length=0; sb.Append(“Xanadu”); 5. DateTime and TimeSpan DateTime Constructor DateTime(yr, mo, day) DateTime(yr, mo, day, hr, min, sec) DateTime bday = new DateTime(1964,12,20,11,2,0); DateTime newyr= DateTime.Parse(“1/1/2005”); DateTime currdt = DateTime.Now; // also AddHours, AddMonths, AddYears DateTime tomorrow = currdt.AddDays(1); TimeSpan diff = currdt.Subtract(bday); // 14795 days from 12/20/64 to 6/24/05 Console.WriteLine(“{0}”, diff.Days); // TimeSpan(hrs, min, sec) TimeSpan ts = new TimeSpan(6, 30, 10); // also FromMinutes, FromHours, FromDays TimeSpan ts = TimeSpan.FromSeconds(120); TimeSpan ts = ts2 – ts1; // +,-,>,<,==, !=
  • 2. 8. Using the C# Compiler at the Command Line C:>csc /t:library /out:reslib.dll mysource.cs csc /t:winexe /r:ctls1.dll /r:ctls2.dll winapp.cs csc /keyfile:strongkey.snk secure.cs Option Description /addmodule Import metadata from a file that does not contain a manifest. /debug Tells compiler to emit debugging info. /doc Specifies an XML documentation file to be created during compilation. /keyfile Specifies file containing key used to create a strong named assembly. /lib Specifies directory to search for external referenced assemblies. /out Name of compiled output file. /reference (/r) Reference to an external assembly. /resource Resource file to embed in output. /target (/t) /t:exe /t:library /t:module /t:winexe 9. C# Language Fundamentals Control Flow Statements switch (expression) { case expression: // statements break / goto / return() case ... default: // statements break / goto / return() } expression may be integer, string, or enum. switch (genre) { case “vhs”: price= 10.00M; break; case “dvd”: price=16.00M; break; default: price=12.00M: break; } if (condition) { // statements } else { // statements } if (genre==”vhs”) price=10.00M; else if (genre==”dvd”) price=16.00M; else price=12.00M; Loop Constructs while (condition) { body } do { body } while (condition); while ( ct < 8) { tot += ct; ct++; } do { tot += ct; ct++;} while (ct < 8); 11. Delegates and Events Delegates [modifiers] delegate result-type delegate name ([parameter list]); // (1) Define a delegate that calls method(s) having a single string parameter public delegate void StringPrinter(string s); // (2) Register methods to be called by delegate StringPrinter prt = new StringPrinter(PrintLower); prt += new StringPrinter(PrintUpper); prt(“Copyright was obtained in 2005”); / / execute PrintLower and PrintUpper Using Anonymous Methods with a Delegate Rather than calling a method, a delegate encapsulates code that is executed: prt = delegate(string s) { Console.WriteLine(s.ToLower()); }; prt += delegate(string s) { Console.WriteLine(s.ToUpper()); }; prt(“Print this in lower and upper case.”); Events // class.event += new delegate(event handler method); Button Total = new Button(); Total.Click += new EventHandler(GetTotal); // Event Handler method must have signature specified by delegate private void GetTotal( object sender, EventArgs e) { Commonly used Control Events Event Delegate Click, MouseEnter DoubleClick, MouseLeave EventHandler( object sender, EventArgs e) MouseDown, Mouseup, MouseMove MouseEventHandler(object sender, MouseEventArgs e) e.X, e.Y – x and y coordinates e.Button – MouseButton.Left, Middle, Right KeyUp, KeyDown KeyEventHandler(object sndr, KeyEventArgs e) e.Handled – Indicates whether event is handled. e.KeyCode – Keys enumeration, e.g., Keys.V e.Modifiers – Indicates if Alt, Ctrl, or Shift key. KeyPress KeyPressEventHandler(object sender, KeyPressEventArgs e) 12. struct [attribute][modifier] struct name [:interfaces] { struct-body} Differences from class: • is a value type • cannot inherit from a class or be inherited • fields cannot have initializer • explicit constructor must have a parameter 13. enum (Enumerated Type) enum enum Operations enum Fabric: int { cotton = 1, silk = 2, wool = 4, rayon = 8 } int cotNum = (int) Fabric.cotton; // 1 string cotName = Fabric.cotton.ToString(); // cotton string s = Enum.GetName(typeof(Fabric),2); // silk // Create instance of wool enum if it is valid if(Enum.IsDefined(typeof(Fabric), “wool”) Fabric woolFab = (Fabric)Enum.Parse(typeof(Fabric),”wool”); Loop Constructs (Continued) for (initializer; termination condition; iteration;) { // statements } foreach (type identifier in collection) { // statements } for (int i=0;i<8;i++) { tot += i; } int[] ages = {27, 33, 44}; foreach(int age in ages) { tot += age; } 10. C# Class Definition Class [public | protected | internal | private] [abstract | sealed | static] class class name [:class/interfaces inherited from] Constructor [access modifier] class name (parameters) [:initializer] initializer – base calls constructor in base class. this calls constructor within class. public class Shirt: Apparel { public Shirt(decimal p, string v) : base(p,v) { constructor body } Method [access modifier] [static | virtual | override | new | sealed | abstract ] method name (parameter list) { body } virtual – method can be overridden in subclass. override – overrides virtual method in base class. new – hides non-virtual method in base class. sealed – prevents derived class from inheriting. abstract – must be implemented by subclass. Passing Parameters: a. By default, parameters are passed by value. b. Passing by reference: ref and out modifiers string id= “gm”; // caller initializes ref int weight; // called method initializes GetFactor(ref id, out weight); // ... other code here static void GetFactor(ref string id, out int wt) { if (id==”gm”) wt = 454; else wt=1; return; } Property [modifier] <datatype> property name { public string VendorName { get { return vendorName; } set { vendorName = value; } // note value keyword }