Core C# and Asp.net Quick reference cheat sheet

0

Core C# and Asp.net Quick reference cheat sheet

cheat sheet

Here is the quick reference guide for c# and asp.net developers.

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

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);

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; // +,-,>,<,==, !=

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

cheat-sheet-c

Example: CultureInfo ci = new CultureInfo(“de-DE”); // German culture
string curdt = String.Format(ci,”{0:M}”,DateTime.Now); // 29 June

cheat-sheet-c1

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

cheat-sheet-c2

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

  • /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);
for (initializer;
termination condition;
iteration;)
{ // statements }

 

for (int i=0;i<8;i++)
{
tot += i;
}

 

foreach (type identifier in
collection)
{ // statements }

 

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:

  • By default, parameters are passed by value.
  • 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
}

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) {

cheat-sheet-c312. 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)

cheat sheet c#

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CommentLuv badge