Switching to C Sharp from VB.NET

Here is a collection of handy snippets for VB developers who may be in the process of transitioning to C#.

Comments

Single line

1
//Comment

Multi-line comments

1
2
/* This section
is commented */

XML Comments

1
/// My XML Comment

C# Data Types

  • byte
  • sbyte
  • int
  • uint
  • short
  • ushort
  • long
  • ulong
  • float
  • double
  • decimal
  • bool
  • char
  • string
  • object

C# Variable Declaration

public | protected internal | protected | internal | private type variable-name

Example

1
private string str_MyVar = "My Value";

C# Arrays

Single Dimension

<type>[] <name> = new <type>[ArraySize];

Example

1
string[] str_Array = new string[2];

Multi-dimensional

<type>[,] <name> = new <type>[ArraySize,ArraySize];

Example

1
string[,] str_MultiArray = new string[5,4];

ArrayList

ArrayList resizes dynamically. As elements are added, it grows in capacity to accommodate them. It stores a collection of elements of type object; therefore casting is necessary. You also need to reference System.Collections.

Example

1
2
3
4
ArrayList list = new ArrayList();
list.Add("One");
list.Add("Two");
list.Add("Three");

Initialize Array

<type>[] <name> = new <type>[ArraySize] {<value1>, <value2>, … , <valueN>};

Example

1
int[] int_MyValues = { 1, 2, 3, 4, 5 };

Change Size of Array

<type>[] <name> = new <type>[ArraySize];

Example

1
Array.Resize(ref int_MyValues, 10);

Operators

Arithmetic

+ (Addition), – (Subtraction), * (Multiplication), / (Division), % (Modulus)

String Manipulation

  • Concatenation: str_WelcomeText = “My name is ” + “Fred Blogs”;
  • .Substring(<start>,[<length>])
  • .Trim() <trims from beginning & end of string>
  • .TrimEnd([<char array>])
  • .TrimStart([char array])
  • .ToLower() <to lower case>
  • .ToUpper() <to upper case>
  • .Replace(<find>,<replace>)
  • .Equals(<expression>) <6 available overloads>
  • .Contains(<string>)
  • .Join(<seperator>,<value>,[<count>])
  • .Compare(<string1>,<string2>,[<ignore case>]) <7 overloads available>
  • .Copy(<string>)
  • \’ – single quote, needed for character literals
  • \” – double quote, needed for string literals
  • \\ – backslash
  • \0 – Unicode character 0
  • \a – Alert (character 7)
  • \b – Backspace (character 8)
  • \f – Form feed (character 12)
  • \n – New line (character 10)
  • \r – Carriage return (character 13)
  • \t – Horizontal tab (character 9)
  • \v – Vertical quote (character 11)
  • \uxxxx – Unicode escape sequence for character with hex value xxxx
  • \xn[n][n][n] – Unicode escape sequence for character with hex value nnnn (variable length version of \uxxxx)
  • \Uxxxxxxxx – Unicode escape sequence for character with hex value xxxxxxxx (for generating surrogates)

String Escape Characters

Assignment

  • = (Equals)
  • += (Addition)
  • -= (Subtraction)
  • *= (Multiplication)
  • /= (Division)
  • %= (Modulus)
  • &= (And)
  • |= (OR)
  • ^= (Exclusive OR)
  • >>= (Right Shift)
  • <<= (Left Shift)
  • == (Equal To)
  • ! = (Not Equal To)
  • < (Less Than)
  • > (Greater Than)
  • <= (Less Than or Equal To)
  • >= (Greater Than or Equal To)
  • is
  • as

Comparison

1
2
3
4
5
6
7
8
if (person is Employee)
{
   // Do employee stuff
}
else if (person is Customer)
{
   // Do customer stuff
}

Logical

  • & (And)
  • | (Or)
  • ^ (Xor)
  • && (AndAlso)
  • || (OrElse)

Error Handling

try
{
//<statements that may cause an error>;
}
catch(Exception ex)
{
//<statements to use when an error occurs>;
}
finally
{
//<statements to use no matter what happens>
}

Example (from MSDN)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
try
{
   myCommand.Connection.Open();
}
// Catch the exception as e and pass it to the ShowErrors routine.
catch (SqlCeException e)
{
   ShowErrors(e);
}

// Error handling routine that generates an error message
public static void ShowErrors(SqlCeException e)
{
   SqlCeErrorCollection errorCollection = e.Errors;

   StringBuilder bld = new StringBuilder();

   Exception inner = e.InnerException;

   if (null != inner)
   {
      MessageBox.Show("Inner Exception: " + inner.ToString());
   }

   // Enumerate the errors to a message box.
   foreach (SqlCeError err in errorCollection)
   {
      bld.Append("\n Error Code: " + err.HResult.ToString("X"));
      bld.Append("\n Message   : " + err.Message);
      bld.Append("\n Minor Err.: " + err.NativeError);
      bld.Append("\n Source    : " + err.Source);

      // Enumerate each numeric parameter for the error.
      foreach (int numPar in err.NumericErrorParameters)
      {
         if (0 != numPar) bld.Append("\n Num. Par. : " + numPar);
      }

      // Enumerate each string parameter for the error.
      foreach (string errPar in err.ErrorParameters)
      {
         if (String.Empty != errPar) bld.Append("\n Err. Par. : " + errPar);
      }

      MessageBox.Show(bld.ToString());
      bld.Remove(0, bld.Length);
   }      
}

Conditional Branching

If Else

1
2
3
4
5
6
7
8
if(expression)
{
   <statement 1>;
}
else
{
   <statement 2>;
}

C# version of IIF()

1
variable == ?true:false;

For Loop

1
2
3
4
for(statement)
{
   <statement>;
}

For Each Loop

1
2
3
4
5
6
7
foreach(<variable> In <object>)
{
   <statements>;

   [break];
   [continue];
}

While Loop

1
2
3
4
while(<expression>)
{
   <statement>;
}

Do-While Loop

1
2
3
4
do
{
   <statement>;
} while <expression>;

Select Case Statement

1
2
3
4
5
6
7
8
9
10
11
12
switch(<expression>)
{
   case <literal or type>:
      <statement>;
      <break>;
   case <literal or type>:
      <statement>;
      <break>;
   default:
      <statement>;
      <break>;
}

Else If

1
2
3
4
5
6
7
8
9
10
11
12
if (Condition_1)
{
   // Statement_1;
}
else if (Condition_2)
{
   // Statement_2;
}
else
{
   // Statement_n;
}

Functions & Sub Routines

Function Structure

1
2
3
4
5
<private, public, protected, internal> [static] <ReturnType> <Function_Name>;([Parameters])
{
   //body of the function;
   return <ReturnType>;
}

Sub Routine Structure

1
2
3
4
<private, public, protected, internal> void  <method_name>([Parameters])
{
   //body of the procedure;
}

Control Functions

1
2
3
4
5
6
7
void MyButton_Click (Object sender, EventArgs e)
{
   // When the button is clicked do stuff
}

<asp:Button id="MyButton" Text="Click Me" OnClick="MyButton_Click" 
runat="server" />

Class Structure

1
2
3
4
public class <Class_Name>
{
   //body of class
}

Base Class Idea
http://www.4guysfromrolla.com/articles/041305-1.aspx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class MyBaseClass : System.Web.UI.Page
{
   protected override void OnLoad(EventArgs e)
   {
      // ... add custom logic here ...
      // Be sure to call the base class's OnLoad method!
      base.OnLoad(e);
   }
}

public class WebForm1 : MyBaseClass
{
   private void Page_Load(object sender, System.EventArgs e)
   {
      // Put user code to initialize the page here
   }
   ...
}

Good Example of Inheritance

http://www.4guysfromrolla.com/webtech/022001-1.shtml

General Items

Getting Item from AppSettings

1
Str_AppSettingValue = ConfigurationManager.AppSettings["app setting name"];

Getting current date and time as a string

1
Str_DateTimeExample = DateTime.Now.ToString("yyyy-MM-dd HH:mm tt");

Format Operators

  • d – Numeric day of the month without a leading zero.
  • dd – Numeric day of the month with a leading zero.
  • ddd – Abbreviated name of the day of the week.
  • dddd – Full name of the day of the week.
  • f,ff,fff,ffff,fffff,ffffff,fffffff -
  • Fraction of a second. The more Fs the higher the precision.
  • h – 12 Hour clock, no leading zero.
  • hh – 12 Hour clock with leading zero.
  • H – 24 Hour clock, no leading zero.
  • HH – 24 Hour clock with leading zero.
  • m – Minutes with no leading zero.
  • mm – Minutes with leading zero.
  • M – Numeric month with no leading zero.
  • MM – Numeric month with a leading zero.
  • MMM – Abbreviated name of month.
  • MMMM – Full month name.
  • s – Seconds with no leading zero.
  • ss – Seconds with leading zero.
  • t – AM/PM but only the first letter.
  • tt – AM/PM ( a.m. / p.m.)
  • y – Year with out century and leading zero.
  • yy – Year with out century, with leading zero.
  • yyyy – Year with century.
  • zz – Time zone off set with +/-.

Examples of best practice guidelines

http://www.codeproject.com/Articles/118853/Some-Best-Practices-for-C-Application-Development

Class Design Patterns (Gang of Four)
http://www.dofactory.com/Patterns/Patterns.aspx

Tags: , , ,