Friday, May 24, 2013

Learn to Program with Csharp From a Gaming Perspective

Hello and welcome to Lesson 11 of Learn to Program with C#: From a Gaming Perspective

This lesson is a carry over from our previous lesson.  We're still working with our RpgTutorial game and hopefully you tried making 3 new methods.  One to print our choices, one to process the choices and one to do the damage.

3 new Methods
So your methods may differ greatly from mine.  That's quite alright.  Depending on how you figure damage should be calculated, when things should happen, you'll get different answers.  I'll go ahead and list mine now.
        string userchoice;
        int damage;

        Random rand;

First I added 3 new variables to our class.
        string PrintChoice()
        {
            string choice;
            Console.WriteLine();
            Console.Write(@"
_____________________
Please choose an action:
(A)ttack:
(D)efend:
_____________________");
            Console.WriteLine();
            choice = Console.ReadLine();
            return choice;
        }
Now we have our PrintChoice() method.  I made it return a string at the same time to keep our battle loop clean.  The WriteLines() just keep our output looking nice.
        void ProcessChoice(string choice,Hero hero, Monster monster)
        {
            switch (choice)
            {
                case "A":
                case "a":
                    Console.WriteLine();
                    Console.WriteLine("{0} attacks!",hero.Identifier);//print what it is
                    DealDamage(hero, monster);//send it to our damage method
                    monster.CurrentHealth -= damage;//take it from the monster
                    Console.WriteLine("{0} hits the {1} for {2}hp of damage"
                        , hero.Identifier, monster.Identifier, damage);//show result
                    break;
                case "D":
                case "d":
                    Console.WriteLine();
                    Console.WriteLine("{0} defends!", hero.Identifier);
                    //we will make defending more beneficial later
                    //Many times you will see this shown like below:
                    //To Do: Add logic to make defending beneficial
                    break;
                default:
                    Console.WriteLine("I'm sorry, I didn't recognize that.");
                    Console.WriteLine();//if the choice isn't valid
                    choice = PrintChoice();//the we'll keep asking till
                    Console.WriteLine();//they get it right
                    ProcessChoice(choice,hero,monster);
                    break;
            }
        }
Here our ProcessChoice() method uses the userchoice string and translates it into an action.  As noted Defend just outputs a string right now.  Default will keep looping till we get a valid choice.  Attack shows us attacking, calls the DealDamage() method, and subtracts the health from the monster.  We are feeding this method a string, and our two characters.  Mainly so that we can pass them onto the DealDamage() method.
        int DealDamage(Hero hero, Monster monster)
        {
            int max;
            int min;
            rand = new Random();
            max = hero.AttackDamage - monster.Defense;
            if (max <= 0)
            {
                max = 1;//right now this isn't a concern, but this is a bit
                //of future proofing our damage mechanism
            }
            min = (int)(hero.AttackDamage * .8) - monster.Defense;//**I'll explain this one**
            if (min <= 0)
            {
                min = 1;
            }
            damage = rand.Next(min, max);//calculate the damage
            return damage;//send it on back
        }
So our DealDamage method takes both characters and uses the hero's attackdamage and the monster's defense to figure out how much damage should be done.  max and min are just local variables, so there's no need to have them anywhere but inside of our method.  This line however:
min = (int)(hero.AttackDamage * .8) - monster.Defense;
might be confusing to you.  Without the (int) in front of this, we would get an error.  Why?  because the compiler doesn't know for sure wether we want to keep min an int or wether we are trying to make it a double (not a valid option by the way).  This is what is known as a cast.  The goal here is to use 80% of the attack damage (rounded down of course because that's how int's roll) so that we have a good min and max to work with. 

All of this boils down to design choice though.  You could use 90% or calculate it some other way entirely.  This is the kind of stuff that makes or breaks your game.  Does it make sense this way?  Is it more fun another way?  Do we want to have a method to determine if the hero misses or not, depending on agility?  This is the kind of thing that gives your game it's character.

If you add these methods to our game and put PrintChoice and ProcessChoice into the do loop like below the game will run, albeit one sided.

                PrintStatus(hero, monster);               
                userchoice = PrintChoice();
                Console.WriteLine();
                ProcessChoice(userchoice, hero, monster);
                Console.ReadLine();
                Console.Clear();//This clears our screen so the next turn is a fresh screen
           

What's missing?
There's still a lot of things we can add.  We can add spells (make some new classes for them, with new options and a new print out menu), we can add a hit/miss method, we can make defend more beneficial, but what do we need?  Well first we need a new method to determine if isAlive is false, and then we need some AI or else our game is just a bully beating up a helpless monster so before we tackle AI let's make a method that takes health and decides if the character is alive or not.  Let's make this one more universal and just pass it an int and return a bool.  Try it on your own first and compare.
        bool CheckHealth(int health)
        {
            bool alive;
            if (health > 0)
            {
                alive = true;
            }
            else
            {
                alive = false;
            }
            return alive;
        }

So that's a pretty simple method which is useable by either the hero or the monster which is ideal.  When we add it to our loop the whole thing looks like this:
namespace RpgTutorial
{
    class Battle
    {
        string userchoice;
        int damage;

        Random rand;

        public Battle(Hero hero, Monster monster)
        {
            Console.WriteLine("{0} is facing a {1}.", hero.Identifier, monster.Identifier);
            BattleLoop(hero, monster);
        }

        public void BattleLoop(Hero hero, Monster monster)
        {
            do
            {
                PrintStatus(hero, monster);               
                userchoice = PrintChoice();
                Console.WriteLine();
                ProcessChoice(userchoice, hero, monster);
                monster.isAlive = CheckHealth(monster.CurrentHealth);
                Console.ReadLine();
                Console.Clear();//This clears our screen so the next turn is a fresh screen
            }
            while (hero.isAlive == true && monster.isAlive == true);
        }

        void PrintStatus(Hero hero, Monster monster)
        {
            Console.Write(@"
********************************
         HP/MaxHP   MP/MaxMP
{0}:   {1}/{2}hp    {3}/{4}mp
{5}: {6}/{7}hp      {8}/{9}mp
********************************
", hero.Identifier, hero.CurrentHealth, hero.MaxHealth, hero.CurrentMagic, hero.MaxMagic,
 monster.Identifier, monster.CurrentHealth, monster.MaxHealth, monster.CurrentMagic, monster.MaxMagic);
        }

        string PrintChoice()
        {
            string choice;
            Console.WriteLine();
            Console.Write(@"
_____________________
Please choose an action:
(A)ttack:
(D)efend:
_____________________");
            Console.WriteLine();
            choice = Console.ReadLine();
            return choice;
        }
        void ProcessChoice(string choice,Hero hero, Monster monster)
        {
            switch (choice)
            {
                case "A":
                case "a":
                    Console.WriteLine();
                    Console.WriteLine("{0} attacks!",hero.Identifier);//print what it is
                    DealDamage(hero, monster);//send it to our damage method
                    monster.CurrentHealth -= damage;//take it from the monster
                    Console.WriteLine("{0} hits the {1} for {2}hp of damage"
                        , hero.Identifier, monster.Identifier, damage);//show result
                    break;
                case "D":
                case "d":
                    Console.WriteLine();
                    Console.WriteLine("{0} defends!", hero.Identifier);
                    //we will make defending more beneficial later
                    //Many times you will see this shown like below:
                    //To Do: Add logic to make defending beneficial
                    break;
                default:
                    Console.WriteLine("I'm sorry, I didn't recognize that.");
                    Console.WriteLine();//if the choice isn't valid
                    choice = PrintChoice();//the we'll keep asking till
                    Console.WriteLine();//they get it right
                    ProcessChoice(choice,hero,monster);
                    break;
            }
        }
        int DealDamage(Hero hero, Monster monster)
        {
            int max;
            int min;
            rand = new Random();
            max = hero.AttackDamage - monster.Defense;
            if (max <= 0)
            {
                max = 1;//right now this isn't a concern, but this is a bit
                //of future proofing our damage mechanism
            }
            min = (int)(hero.AttackDamage * .8) - monster.Defense;//**I'll explain this one**
            if (min <= 0)
            {
                min = 1;
            }
            damage = rand.Next(min, max);//calculate the damage
            return damage;//send it on back
        }
        bool CheckHealth(int health)
        {
            bool alive;
            if (health > 0)
            {
                alive = true;
            }
            else
            {
                alive = false;
            }
            return alive;
        }
    }
}



Csharp anD Visual Basic.net Graphic Keywords

You Can use The Perameter By importing system.drawing
in form load option Put This command
g = me.creategraphics()
or Any Where ELse
g.(All command Name Below)

DrawArc Draws an arc from the specified ellipse.
DrawBezier Draws a cubic bezier curve.
DrawBeziers Draws a series of cubic Bezier curves.
DrawClosedCurve Draws a closed curve defined by an array of points.
DrawCurve Draws a curve defined by an array of points.
DrawEllipse Draws an ellipse.
DrawImage Draws an image.
DrawLine Draws a line.
DrawPath Draws the lines and curves defined by a GraphicsPath.
DrawPie Draws the outline of a pie section.
DrawPolygon Draws the outline of a polygon.
DrawRectangle Draws the outline of a rectangle.
DrawString Draws a string.
FillEllipse Fills the interior of an ellipse defined by a bounding rectangle.
FillPath Fills the interior of a path.
FillPie Fills the interior of a pie section.
FillPolygon Fills the interior of a polygon defined by an array of points.
FillRectangle Fills the interior of a rectangle with a Brush.
FillRectangles Fills the interiors of a series of rectangles with a Brush.
FillRegion Fills the interior of a Region.

Thursday, May 23, 2013

Control Data Binding

Control Data Binding
want to visually deal with records of a database from a Windows application, you may simply want to view the data. Although Microsoft Visual Studio 2005 provides various effective means of binding data to Windows controls, sometimes, you may want to manually bind the controls. To do this, you can use a DataSet object.
The DataSet class allows you to access any type of information from a table. These include table's object name, the columns (and their properties), and the records. This means that you should be able to locate a record, retrieve its value, and assign it to a control. Probably the only real problem is to make sure your DataSet object can get the necessary records. The records could come from a database (Microsoft SQL Server, Oracle, Microsoft Access, Paradox, etc).
Here is an example of binding data to two text boxes to the records of a Microsoft SQL Server table:
Imports System.Data.SqlClient

Public Class Central

    Private Sub btnLoad_Click(ByVal sender As System.Object, _
                              ByVal e As System.EventArgs) _
                              Handles btnLoad.Click
        Dim conDatabase As SqlConnection = _
        New SqlConnection("Data Source=(local);Database='bcr1';" & _
              "Integrated Security=true")
        Dim cmdDatabase As SqlCommand = _
  New SqlCommand("SELECT * FROM dbo.Employees;", conDatabase)

        Dim dsEmployees As DataSet = New DataSet("EmployeesSet")
        Dim sda As SqlDataAdapter = New SqlDataAdapter
        sda.SelectCommand = cmdDatabase
        sda.Fill(dsEmployees)

        Dim recEmployee As DataRow = dsEmployees.Tables(0).Rows(0)

        txtFirstName.Text = CStr(recEmployee("FirstName"))
        txtLastName.Text = CStr(recEmployee("LastName"))

        conDatabase.Close()
    End Sub
End Class

Visual Basic.net Defining Subs Tutorial

As we mentioned in the previous chapter, Sub procedures are procedures that do not return any value. We have been using the Sub procedure Main in all our examples. We have been writing console applications so far, in these tutorials. When these applications start, the control goes to the Main Sub procedure, and it in turn, runs any other statements constituting the body of the program.

Defining Sub Procedures

The Sub statement is used to declare the name, parameter and the body of a sub procedure. The syntax for the Sub statement is:
[Modifiers] Sub SubName [(ParameterList)] 
    [Statements]
End Sub
Where,
  • Modifiers: specifiy the access level of the procedure; possible values are: Public, Private, Protected, Friend, Protected Friend and information regarding overloading, overriding, sharing, and shadowing.
  • SubName: indicates the name of the Sub
  • ParameterList: specifies the list of the parameters

Example

The following example demonstrates a Sub procedure CalculatePay that takes two parameters hours and wages and displays the total pay of an employee:
Module mysub
   Sub CalculatePay(ByVal hours As Double, ByVal wage As Decimal)
      'local variable declaration
      Dim pay As Double
      pay = hours * wage
      Console.WriteLine("Total Pay: {0:C}", pay)
   End Sub
   Sub Main()
      'calling the CalculatePay Sub Procedure
      CalculatePay(25, 10)
      CalculatePay(40, 20)
      CalculatePay(30, 27.5)
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Total Pay: $250.00
Total Pay: $800.00
Total Pay: $825.00

Passing Parameters by Value

This is the default mechanism for passing parameters to a method. In this mechanism, when a method is called, a new storage location is created for each value parameter. The values of the actual parameters are copied into them. So, the changes made to the parameter inside the method have no effect on the argument.
In VB.Net, you declare the reference parameters using the ByVal keyword. The following example demonstrates the concept:
Module paramByval
   Sub swap(ByVal x As Integer, ByVal y As Integer)
      Dim temp As Integer
      temp = x ' save the value of x 
      x = y    ' put y into x 
      y = temp 'put temp into y 
   End Sub
   Sub Main()
      ' local variable definition 
      Dim a As Integer = 100
      Dim b As Integer = 200
      Console.WriteLine("Before swap, value of a : {0}", a)
      Console.WriteLine("Before swap, value of b : {0}", b)
      ' calling a function to swap the values '
      swap(a, b)
      Console.WriteLine("After swap, value of a : {0}", a)
      Console.WriteLine("After swap, value of b : {0}", b)
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
It shows that there is no change in the values though they had been changed inside the function.

Passing Parameters by Reference

A reference parameter is a reference to a memory location of a variable. When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method.
In VB.Net, you declare the reference parameters using the ByRef keyword. The following example demonstrates this:
Module paramByref
   Sub swap(ByRef x As Integer, ByRef y As Integer)
      Dim temp As Integer
      temp = x ' save the value of x 
      x = y    ' put y into x 
      y = temp 'put temp into y 
   End Sub
   Sub Main()
      ' local variable definition 
      Dim a As Integer = 100
      Dim b As Integer = 200
      Console.WriteLine("Before swap, value of a : {0}", a)
      Console.WriteLine("Before swap, value of b : {0}", b)
      ' calling a function to swap the values '
      swap(a, b)
      Console.WriteLine("After swap, value of a : {0}", a)
      Console.WriteLine("After swap, value of b : {0}", b)
      Console.ReadLine()
   End Sub
End Module
When the above code is compiled and executed, it produces following result:
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100

Tuesday, May 21, 2013

Compiler Opt

Deployment in c#

Deployment in c#

Visual Studio 2012
2 out of 2 rated this helpful - Rate this topic

After you have completed building your C# application, the next step is to distribute it. C# is a .NET language; therefore, distributing any C# executables to other machines requires the .NET Framework to be installed on each execution machine (and possibly other dependencies specific to your application). You have a variety of options available for distributing the .NET Framework. For an overview, see Deployment Guide for Developers.
Moving completed applications to other computers is generally referred to as deployment. The Microsoft development environment provides mechanisms for deployment; for more information, see Deploying Applications and Components.
If you build and distribute mainly from the command line, you might need to consider other methods of deployment and redistributing dependencies.

Visual Basic.NET and Csharp DIfference

Keyword Differences

Purpose VB.NET C#
Declare a variable Private, Public, Friend, Protected, Static1, Shared, Dim declarators (keywords include user-defined types and built-in types)
Declare a named constant Const const
Create a new object New, CreateObject() new
Function/method does not return a value Sub void
Overload a function or method (Visual Basic: overload a procedure or method) Overloads (No language keyword required for this purpose)
Refer to the current object Me this
Make a nonvirtual call to a virtual method of the current object MyClass n/a
Retrieve character from a string GetChar Function []
Declare a compound data type (Visual Basic: Structure) Structure <members> End Structure struct, class, interface
Initialize an object (constructors) Sub New() Constructors, or system default type constructors
Terminate an object directly n/a n/a
Method called by the system just before garbage collection reclaims an object7 Finalize destructor
Initialize a variable where it is declared
Dim x As Long = 2
Dim c As New _
   Car(FuelTypeEnum.Gas)
// initialize to a value:
int x = 123;
// or use default 
// constructor:
int x = new int();
Take the address of a function AddressOf (For class members, this operator returns a reference to a function in the form of a delegate instance) delegate
Declare that an object can be modified asynchronously n/a volatile
Force explicit declaration of variables Option Explicit n/a. (All variables must be declared prior to use)
Test for an object variable that does not refer to an object obj = Nothing obj == null
Value of an object variable that does not refer to an object Nothing null
Test for a database null expression IsDbNull n/a
Test whether a Variant variable has been initialized n/a n/a
Define a default property Default by using indexers
Refer to a base class MyBase base
Declare an interface Interface interface
Specify an interface to be implemented Implements (statement) class C1 : I1
Declare a class Class <implementation> class
Specify that a class can only be inherited. An instance of the class cannot be created. MustInherit abstract
Specify that a class cannot be inherited NotInheritable sealed
Declare an enumerated type Enum <members> End Enum enum
Declare a class constant Const const (Applied to a field declaration)
Derive a class from a base class Inherits C2 class C1 : C2
Override a method Overrides override
Declare a method that must be implemented in a deriving class MustOverride abstract
Declare a method that can't be overridden NotOverridable (Methods are not overridable by default.) sealed
Declare a virtual method, property (Visual Basic), or property accessor (C#, C++) Overridable virtual
Hide a base class member in a derived class Shadowing n/a
Declare a typesafe reference to a class method Delegate delegate
Specify that a variable can contain an object whose events you wish to handle WithEvents (Write code - no specific keyword)
Specify the events for which an event procedure will be called Handles (Event procedures can still be associated with a WithEvents variable by naming pattern.) n/a
Evaluate an object expression once, in order to access multiple members
With objExpr 
  <.member>
  <.member> 
End With
n/a
Structured exception handling
Try <attempt>
Catch
<handle errors>
Finally
<always execute>
End Try
try, catch, finally, throw
Decision structure (selection) Select Case ..., Case, Case Else, End Select switch, case, default, goto, break
Decision structure (if ... then) If ... Then, ElseIf ... Then, Else, End If if, else
Loop structure (conditional) While, Do [While, Until] ..., Loop [While, Until] do, while, continue
Loop structure (iteration) For ..., [Exit For], Next
For Each ..., [Exit For,] Next
for, foreach
Declare an array
Dim a() As Long
int[] x = new int[5];
Initialize an array
Dim a() As Long = {3, 4, 5}

int[] x = new int[5] {
        1, 2, 3, 4, 5};
Reallocate array Redim n/a
Visible outside the project or assembly Public public
Invisible outside the assembly (C#/Visual Basic) or within the package (Visual J#, JScript) Friend internal
Visible only within the project (for nested classes, within the enclosing class) Private private
Accessible outside class and project or module Public public
Accessible outside the class, but within the project Friend internal
Only accessible within class or module Private private
Only accessible to current and derived classes Protected protected
Preserve procedure's local variables Static n/a
Shared by all instances of a class Shared static
Comment code '
Rem
//, /* */ for multi-line comments
/// for XML comments
Case-sensitive? No Yes
Call Windows API Declare <API> use Platform Invoke
Declare and raise an event Event, RaiseEvent event
Threading primitives SyncLock lock
Go to Goto goto

Data types Differences

Purpose/Size VB.NET C#
Decimal Decimal decimal
Date Date DateTime
(varies) String string
1 byte Byte byte
2 bytes Boolean bool
2 bytes Short, Char (Unicode character) short, char (Unicode character)
4 bytes Integer int
8 bytes Long long
4 bytes Single float
8 bytes Double double

Operators Differences

Purpose VB.NET C#
Integer division \ /
Modulus (division returning only the remainder) Mod %
Exponentiation ^ n/a
Integer division Assignment \= /=
Concatenate &= NEW +=
Modulus n/a %=
Bitwise-AND n/a &=
Bitwise-exclusive-OR n/a ^=
Bitwise-inclusive-OR n/a |=
Equal = ==
Not equal <> !=
Compare two object reference variables Is ==
Compare object reference type TypeOf x Is Class1 x is Class1
Concatenate strings & +
Shortcircuited Boolean AND AndAlso &&
Shortcircuited Boolean OR OrElse ||
Scope resolution . . and base
Array element () [ ]
Type cast Cint, CDbl, ..., CType (type)
Postfix increment n/a ++
Postfix decrement n/a --
Indirection n/a * (unsafe mode only)
Address of AddressOf & (unsafe mode only; also see fixed)
Logical-NOT Not !
One's complement Not ~
Prefix increment n/a ++
Prefix decrement n/a --
Size of type n/a sizeof
Bitwise-AND And &
Bitwise-exclusive-OR Xor ^
Bitwise-inclusive-OR Or |
Logical-AND And &&
Logical-OR Or ||
Conditional If Function () ?:
Pointer to member n/a . (Unsafe mode only)

Programming Difference

Purpose VB.NET C#
Declaring Variables
Dim x As Integer
Public x As Integer = 10
int x;
int x = 10;
Comments
' comment
x = 1  ' comment
Rem comment
// comment
/* multiline
 comment */
Assignment Statements
nVal = 7
nVal = 7;
Conditional Statements
If nCnt <= nMax Then
   ' Same as nTotal = 
   ' nTotal + nCnt.
   nTotal += nCnt  
   ' Same as nCnt = nCnt + 1.
   nCnt += 1       
Else
   nTotal += nCnt
   nCnt -= 1       
End If
if (nCnt <= nMax)
{
   nTotal += nCnt;
   nCnt++;
}
else
{
   nTotal +=nCnt;
   nCnt--;
}
Selection Statements
Select Case n
   Case 0
      MsgBox ("Zero")  
     ' Visual Basic .NET exits
     ' the Select at 
     ' the end of a Case.
   Case 1
      MsgBox ("One")
   Case 2 
      MsgBox ("Two")
   Case Else
      MsgBox ("Default")
End Select



switch(n) 
{
   case 0:
      Console.WriteLine("Zero");
      break;
   case 1:
      Console.WriteLine("One");
      break;
   case 2:
      Console.WriteLine("Two");
      break;
   default:
      Console.WriteLine("?");
      break;
}

FOR Loops
For n = 1 To 10 
   MsgBox("The number is " & n)
Next

For Each prop In obj
    prop = 42
Next prop
for (int i = 1; i <= 10; i++) 
   Console.WriteLine(
      "The number is {0}", i);
foreach(prop current in obj)
{
   current=42;
}
Hiding Base Class Members
Public Class BaseCls
   ' The element to be shadowed
   Public Z As Integer = 100   
   public Sub Test()
      System.Console.WriteLine( _
        "Test in BaseCls")
   End Sub
End Class

Public Class DervCls
   Inherits BaseCls
   ' The shadowing element.
   Public Shadows Z As String = "*"
   public Shadows Sub Test()
      System.Console.WriteLine( _
          "Test in DervCls")
   End Sub
End Class

Public Class UseClasses
  ' DervCls widens to BaseCls. 
  Dim BObj As BaseCls = 
          New DervCls()
  ' Access through derived 
  ' class.
  Dim DObj As DervCls = 
       New DervCls()

  Public Sub ShowZ()
    System.Console.WriteLine( _
     "Accessed through base "&_
     "class: "  & BObj.Z)
    System.Console.WriteLine(_
    "Accessed through derived "&_
    "class: " & DObj.Z)
    BObj.Test()
    DObj.Test()
  End Sub 
End Class




public class BaseCls
{
   // The element to be hidden
   public int Z = 100;   
   public void Test()
   {
      System.Console.WriteLine(
        "Test in BaseCls");
   }
}

public class DervCls : BaseCls
{
  // The hiding element
  public new string Z = "*";   
  public new void Test()
  {
    System.Console.WriteLine(
      "Test in DervCls");
  }
}

public class UseClasses
{
  // DervCls widens to BaseCls
  BaseCls BObj = new DervCls();  
   // Access through derived 
   //class 
  DervCls DObj = new DervCls();  
  public void ShowZ()
  {
    System.Console.WriteLine(
    "Accessed through " +
      "base class: {0}", 
      BObj.Z);
    System.Console.WriteLine(
    "Accessed through" +
      " derived class:{0}",
      DObj.Z);
    BObj.Test();
    DObj.Test();
   }
}
WHILE Loops
' Test at start of loop
While n < 100 .
   ' Same as n = n + 1.
   n += 1     
End While '
while (n < 100)
   n++;
  

 
Parameter Passing by Value
' The argument Y is 
'passed by value.
Public Sub ABC( _
  ByVal y As Long) 
'If ABC changes y, the
' changes do not affect x.
End Sub
   
ABC(x) ' Call the procedure.
' You can force parameters to 
' be passed by value, 
' regardless of how 
' they are declared, 
' by enclosing 
' the parameters in 
' extra parentheses.
ABC((x))
/* Note that there is 
no way to pass reference 
types (objects) strictly 
by value. You can choose 
to either pass the reference 
(essentially a pointer), or 
a reference to the reference 
(a pointer to a pointer).*/
// The method:
void ABC(int x)
{
   ...
}
// Calling the method:
ABC(i);
Parameter Passing by Reference
Public Sub ABC(ByRef y As Long) 
' The parameter y is declared 
'by referece:
' If ABC changes y, the changes are
' made to the value of x.
End Sub

ABC(x) ' Call the procedure.












/* Note that there is no
 way to pass reference types 
 (objects)  strictly by value.
 You can choose to  either 
 pass the reference 
 (essentially  a pointer), 
 or a reference to the 
 reference (a pointer to a 
 pointer).*/
// Note also that unsafe C# 
//methods can take pointers 
//just like C++ methods. For 
//details, see unsafe.
// The method:
void ABC(ref int x)
{
   ...
}
// Calling the method:
ABC(ref i);
Structured Exception Handling
Try
   If x = 0 Then
      Throw New Exception( _
         "x equals zero")
   Else
      Throw New Exception( _
        "x does not equal zero")
   End If
Catch err As System.Exception
   MsgBox( _
   "Error: " & Err.Description)
Finally
   MsgBox( _
   "Executing finally block.")
End Try








// try-catch-finally
try
{
  if (x == 0)
   throw new System.Exception(
     "x equals zero");
  else
   throw new System.Exception(
     "x does not equal zero");
}
catch (System.Exception err)
{
  System.Console.WriteLine(
              err.Message);
}
finally
{
  System.Console.WriteLine(
   "executing finally block");
}



Set an Object Reference to Nothing
o = Nothing
o = null;
Initializing Value Types
Dim dt as New System.DateTime( _
  2001, 4, 12, 22, 16, 49, 844)


System.DateTime dt = 
 new System.DateTime(
 2001, 4, 12, 22, 16, 
      49, 844);

New Features of both languages in 2005 version

VB.NET C#
Visual Basic 2005 has many new and improved language features -- such as inheritance, interfaces, overriding, shared members, and overloading -- that make it a powerful object-oriented programming language. As a Visual Basic developer, you can now create multithreaded, scalable applications using explicit multithreading. This language has following new features,
  1. Continue Statement, which immediately skips to the next iteration of a Do, For, or While loop.
  2. IsNot operator, which you can avoid using the Not and Is operators in an awkward order.
  3. 3. Using...End. Using statement block ensures disposal of a system resource when your code leaves the block for any reason
    Public Sub setbigbold( _
        ByVal c As Control)
    Using nf As New _
      System.Drawing.Font("Arial",_
      12.0F, FontStyle.Bold)
      c.Font = nf
      c.Text = "This is" &_
      "12-point Arial bold"
    End Using
    End Sub
  4. Explicit Zero Lower Bound on an Array, Visual Basic now permits an array declaration to specify the lower bound (0) of each dimension along with the upper bound.
  5. Unsigned Types, Visual Basic now supports unsigned integer data types (UShort, UInteger, and ULong) as well as the signed type SByte.
  6. Operator Overloading, Visual Basic now allows you to define a standard operator (such as +, &, Not, or Mod) on a class or structure you have defined.
  7. Partial Types, to separate generated code from your authored code into separate source files.
  8. Visual Basic now supports type parameters on generic classes, structures, interfaces, procedures, and delegates. A corresponding type argument specifies at compilation time the data type of one of the elements in the generic type.
  9. Custom Events. You can declare custom events by using the Custom keyword as a modifier for the Event statement. In a custom event, you specify exactly what happens when code adds or removes an event handler to or from the event, or when code raises the event.
  10. Compiler Checking Options, The /nowarn and /warnaserror options provide more control over how warnings are handled. Each one of these compiler options now takes a list of warning IDs as an optional parameter, to specify to which warnings the option applies.
  11. There are eight new command-line compiler options:
    1. The /codepage option specifies which codepage to use when opening source files.
    2. The /doc option generates an XML documentation file based on comments within your code.
    3. The /errorreport option provides a convenient way to report a Visual Basic internal compiler error to Microsoft.
    4. The /filealign option specifies the size of sections in your output file.
    5. The /noconfig option causes the compiler to ignore the Vbc.rsp file.
    6. The /nostdlib option prevents the import of mscorlib.dll, which defines the entire System namespace.
    7. The /platform option specifies the processor to be targeted by the output file, in those situations where it is necessary to explicitly specify it.
    8. The /unify option suppresses warnings resulting from a mismatch between the versions of directly and indirectly referenced assemblies.
With the release of Visual Studio 2005, the C# language has been updated to version 2.0. This language has following new features:
  1. Generics types are added to the language to enable programmers to achieve a high level of code reuse and enhanced performance for collection classes. Generic types can differ only by arity. Parameters can also be forced to be specific types.
  2. Iterators make it easier to dictate how a for each loop will iterate over a collection's contents.
    // Iterator Example
    public class NumChar
    {
    string[] saNum = { 
      "One", "Two", "Three", 
      "Four", "Five", "Six", 
      "Seven", "Eight", "Nine", 
      "Zero"};
    public 
     System.Collections.IEnumerator 
     GetEnumerator()
    {
    foreach (string num in saNum)
    yield return num;
    }
    }
    // Create an instance of 
    // the collection class
    NumChar oNumChar = new NumChar();
    // Iterate through it with foreach
    foreach (string num in oNumChar)
    Console.WriteLine(num);
    
  3. Partial type definitions allow a single type, such as a class, to be split into multiple files. The Visual Studio designer uses this feature to separate its generated code from user code.
  4. Nullable types allow a variable to contain a value that is undefined.
  5. Anonymous Method is now possible to pass a block of code as a parameter. Anywhere a delegate is expected, a code block can be used instead: There is no need to define a new method.
    button1.Click += 
     delegate { MessageBox.Show( 
     "Click!") };
  6. . The namespace alias qualifier (::) provides more control over accessing namespace members. The global :: alias allows to access the root namespace that may be hidden by an entity in your code.
  7. Static classes are a safe and convenient way of declaring a class containing static methods that cannot be instantiated. In C# v1.2 you would have defined the class constructor as private to prevent the class being instantiated.
  8. 8. There are eight new compiler options:
    1. /langversion option: Can be used to specify compatibility with a specific version of the language.
    2. /platform option: Enables you to target IPF (IA64 or Itanium) and AMD64 architectures.
    3. #pragma warning: Used to disable and enable individual warnings in code.
    4. /linkresource option: Contains additional options.
    5. /errorreport option: Can be used to report internal compiler errors to Microsoft over the Internet.
    6. /keycontainer and /keyfile: Support specifying cryptographic keys.