Escolar Documentos
Profissional Documentos
Cultura Documentos
VB.NET
Program Structure C#
Imports System using System;
VB.NET Comments C#
' Single line only // Single line
REM Single line only /* Multiple
''' <summary>XML comments</summary> line */
/// <summary>XML comments on single
line</summary>
/** <summary>XML comments on multiple
lines</summary> */
VB.NET Data Types C#
Value Types Value Types
Boolean bool
Byte, SByte byte, sbyte
Char char
Short, UShort, Integer, UInteger, Long, short, ushort, int, uint, long, ulong
ULong float, double
Single, Double decimal
Decimal DateTime (not a built-in C# type)
Date (alias of System.DateTime)
Reference Types
Reference Types object
Object string
String
Initializing
Initializing bool correct = true;
Dim correct As Boolean = True byte b = 0x2A; // hex
Dim b As Byte = &H2A 'hex or &O52 for object person = null;
octal string name = "Dwight";
Dim person As Object = Nothing char grade = 'B';
Dim name As String = "Dwight" DateTime today = DateTime.Parse("12/31/2007
Dim grade As Char = "B"c 12:15:00");
Dim today As Date = #12/31/2007 decimal amount = 35.99m;
12:15:00 PM# float gpa = 2.9f;
Dim amount As Decimal = 35.99@ double pi = 3.14159265;
Dim gpa As Single = 2.9! long lTotal = 123456L;
Dim pi As Double = 3.14159265 short sTotal = 123;
Dim lTotal As Long = 123456L ushort usTotal = 123;
Dim sTotal As Short = 123S uint uiTotal = 123;
Dim usTotal As UShort = 123US ulong ulTotal = 123;
Dim uiTotal As UInteger = 123UI
Dim ulTotal As ULong = 123UL Implicitly Typed Local Variables
var s = "Hello!";
Implicitly Typed Local Variables var nums = new int[] { 1, 2, 3 };
Dim s = "Hello!" var hero = new SuperHero() { Name = "Batman" };
Dim nums = New Integer() {1, 2, 3}
Dim hero = New SuperHero With {.Name Type Information
= "Batman"} int x;
Console.WriteLine(x.GetType()); // Prints
Type Information System.Int32
Dim x As Integer Console.WriteLine(typeof(int)); // Prints
Console.WriteLine(x.GetType()) System.Int32
' Prints System.Int32 Console.WriteLine(x.GetType().Name); // prints
Console.WriteLine(GetType(Integer)) ' Int32
Prints System.Int32
Console.WriteLine(TypeName(x)) ' Circle c = new Circle();
Prints Integer if (c is Shape)
Console.WriteLine("c is a Shape");
Dim c as New Circle
If TypeOf c Is Shape Then _ Type Conversion / Casting
Console.WriteLine("c is a Shape") float d = 3.5f;
i = Convert.ToInt32(d); // Set to 4 (rounds)
Type Conversion / Casting int i = (int)d; // set to 3 (truncates decimal)
Dim d As Single = 3.5
Dim i As Integer = CType(d, Integer) '
set to 4 (Banker's rounding) object o = 2;
i = CInt(d) ' same result as CType int i = (int)o; // Throws InvalidCastException if
i = Int(d) ' set to 3 (Int function truncates type cast fails
the decimal)
Shape s = new Shape();
Dim o As Object = 2 Circle c = s as Circle; // Returns null if type cast fails
i = DirectCast(o, Integer) ' Throws
InvalidCastException if type cast fails
Arithmetic Arithmetic
+ - * / + - * /
Mod % (mod)
\ (integer division) / (integer division if both operands are ints)
^ (raise to a power) Math.Pow(x, y)
Assignment Assignment
= += -= *= /= \= ^= <<= >>= &= = += -= *= /= %= &= |= ^= <<= >>= ++ --
Bitwise Bitwise
And Or Xor Not << >> & | ^ ~ << >>
Logical Logical
AndAlso OrElse And Or Xor Not && || & | ^ !
Note: AndAlso and OrElse perform short- Note: && and || perform short-circuit logical
circuit logical evaluations evaluations
' Preferred
If x <> 100 AndAlso y < 5 Then
x *= 5 No need for _ or : since ; is used to terminate each
y *= 2 statement.
End If
' 4 is the index of the last element, so it // 5 is the size of the array
holds 5 elements string[] names = new string[5];
Dim names(4) As String names[0] = "David";
names(0) = "David" names[5] = "Bobby"; // Throws
names(5) = "Bobby" ' Throws System.IndexOutOfRangeException
System.IndexOutOfRangeException
' Resize the array, keeping the existing // C# can't dynamically resize an array. Just copy
values (Preserve is optional) into new array.
ReDim Preserve names(6) string[] names2 = new string[7];
Array.Copy(names, names2, names.Length); // or
names.CopyTo(names2, 0);
Dim twoD(rows-1, cols-1) As Single
twoD(2, 0) = 4.5 float[,] twoD = new float[rows, cols];
twoD[2,0] = 4.5f;
Dim jagged()() As Integer = { _
New Integer(4) {}, New Integer(1) {}, int[][] jagged = new int[3][] {
New Integer(2) {} } new int[5], new int[2], new int[3] };
jagged(0)(4) = 5 jagged[0][4] = 5;
VB.NET Functions C#
' Pass by value (in, default), reference // Pass by value (in, default), reference (in/out),
(in/out), and reference (out) and reference (out)
Sub TestFunc(ByVal x As Integer, ByRef void TestFunc(int x, ref int y, out int z) {
y As Integer, ByRef z As Integer) x++;
x += 1 y++;
y += 1 z = 5;
z=5 }
End Sub
int a = 1, b = 1, c; // c doesn't need initializing
Dim a = 1, b = 1, c As Integer ' c set to TestFunc(a, ref b, out c);
zero by default Console.WriteLine("{0} {1} {2}", a, b, c); // 1 2 5
TestFunc(a, b, c)
Console.WriteLine("{0} {1} {2}", a, b, c) // Accept variable number of arguments
' 1 2 5 int Sum(params int[] nums) {
int sum = 0;
' Accept variable number of arguments foreach (int i in nums)
Function Sum(ByVal ParamArray nums sum += i;
As Integer()) As Integer return sum;
Sum = 0 }
For Each i As Integer In nums
Sum += i int total = Sum(4, 3, 2, 1); // returns 10
Next
End Function ' Or use Return statement /* C# 4.0 supports optional parameters. Previous
like C# versions required function overloading. */
void SayHello(string name, string prefix = "") {
Dim total As Integer = Sum(4, 3, 2, 1) ' Console.WriteLine("Greetings, " + prefix + " " +
returns 10 name);
}
' Optional parameters must be listed
last and must have a default value SayHello("Strangelove", "Dr.");
Sub SayHello(ByVal name As String, SayHello("Mom");
Optional ByVal prefix As String = "")
Console.WriteLine("Greetings, " & prefix
& " " & name)
End Sub
SayHello("Strangelove", "Dr.")
SayHello("Mom")
VB.NET Strings C#
Special character constants (all also Escape sequences
accessible from ControlChars class) \r // carriage-return
vbCrLf, vbCr, vbLf, vbNewLine \n // line-feed
vbNullString \t // tab
vbTab \\ // backslash
vbBack \" // quote
vbFormFeed
vbVerticalTab
"" // String concatenation
string school = "Harding\t";
' String concatenation (use & or +) school = school + "University"; // school is
Dim school As String = "Harding" & "Harding (tab) University"
vbTab
school = school & "University" ' school is // Chars
"Harding (tab) University" char letter = school[0]; // letter is H
letter = 'Z'; // letter is Z
' Chars letter = Convert.ToChar(65); // letter is A
Dim letter As Char = school.Chars(0) ' letter = (char)65; // same thing
letter is H char[] word = school.ToCharArray(); // word holds
letter = "Z"c ' Harding
letter is Z
letter = Convert.ToChar(65) ' // String literal
letter is A string msg = @"File is c:\temp\x.dat";
letter = Chr(65) ' same // same as
thing string msg = "File is c:\\temp\\x.dat";
Dim word() As Char =
school.ToCharArray() ' word holds // String comparison
Harding string mascot = "Bisons";
if (mascot == "Bisons") // true
' No string literal operator if (mascot.Equals("Bisons")) // true
Dim msg As String = "File is if (mascot.ToUpper().Equals("BISONS")) // true
c:\temp\x.dat" if (mascot.CompareTo("Bisons") == 0) // true
' or // or
Dim hero2 As SuperHero = hero ' Both SuperHero hero2 = hero; // Both reference the same
reference the same object object
hero2.Name = "WormWoman" hero2.Name = "WormWoman";
Console.WriteLine(hero.Name) ' Prints Console.WriteLine(hero.Name); // Prints
WormWoman WormWoman
hero = Nothing ' Free the object hero = null ; // Free the object
Public Sub New(ByVal name As String, public StudentRecord(string name, float gpa) {
ByVal gpa As Single) this.name = name;
Me.name = name this.gpa = gpa;
Me.gpa = gpa }
End Sub }
End Structure StudentRecord stu = new StudentRecord("Bob", 3.5f);
StudentRecord stu2 = stu;
Dim stu As StudentRecord = New
StudentRecord("Bob", 3.5) stu2.name = "Sue";
Dim stu2 As StudentRecord = stu Console.WriteLine(stu.name); // Prints Bob
Console.WriteLine(stu2.name); // Prints Sue
stu2.name = "Sue"
Console.WriteLine(stu.name) ' Prints
Bob
Console.WriteLine(stu2.name) ' Prints Sue
VB.NET Properties C#
' Auto-implemented properties are new to // Auto-implemented properties
VB10 public string Name { get; set; }
Public Property Name As String public int Size { get; protected set; } // Set default
Public Property Size As Integer = -1 ' value in constructor
Default value, Get and Set both Public
' Traditional property implementation // Traditional property implementation
Private mName As String private string name;
Public Property Name() As String public string Name {
Get get {
Return mName return name;
End Get }
Set(ByVal value As String) set {
mName = value name = value;
End Set }
End Property }
' Read all lines from text file // Read all lines from text file
Dim reader As StreamReader = StreamReader reader =
File.OpenText("c:\myfile.txt") File.OpenText("c:\\myfile.txt");
Dim line As String = reader.ReadLine() string line = reader.ReadLine();
While Not line Is Nothing while (line != null) {
Console.WriteLine(line) Console.WriteLine(line);
line = reader.ReadLine() line = reader.ReadLine();
End While }
reader.Close() reader.Close();
Home