(Notes) Notes (2019)

Kotlin Syntax





VB.NET (2005), (2010), (2015), (2017), (2020) C# (2020) Java Kotlin
Program Structure
   1:  Imports System
   2:   
   3:  Namespace Hello
   4:     Class HelloWorld
   5:        Overloads Shared Sub Main(ByVal args() As String)
   6:           Dim name As String = "VB.NET"
   7:   
   8:           'See if an argument was passed from the command line
   9:            If args.Length = 1 Then name = args(0)
  10:   
  11:            Console.WriteLine("Hello, " & name & "!")
  12:        End Sub
  13:     End Class
  14:  End Namespace 
   1:  using System;
   2:   
   3:  namespace Hello {
   4:     public class HelloWorld {
   5:        public static void Main(string[] args) {
   6:           string name = "C#";
   7:   
   8:           // See if an argument was passed from the command line
   9:           if (args.Length == 1)
  10:              name = args[0];
  11:           Console.WriteLine("Hello, " + name + "!");
  12:        }
  13:     }
  14:  } 
   1:  package hello;
   2:   public class HelloWorld
   3:   {
   4:      public static void main(String[] args)
   5:      {
   6:         String name = "Java";
   7:         // See if an argument was passed from the command line
   8:         if (args.length == 1)
   9:         {
  10:            name = args[0];
  11:         }
  12:         System.out.println("Hello, " + name + "!");
  13:      }
  14:   }
   1:  package hello
   2:  object HelloWorld {
   3:    @JvmStatic fun main(args:Array<String>) {
   4:      val name = "Kotlin"
   5:      // See if an argument was passed from the command line
   6:      if (args.size == 1)
   7:      {
   8:        name = args[0]
   9:      }
  10:      println("Hello, " + name + "!")
  11:    }
  12:  }
Comments
   1:  ' Single line only
   2:   
   3:  REM Single line only
   4:   
   5:  ''' <summary>XML comments</summary>
   1:  // Single line
   2:  /* Multiple
   3:      line  */
   4:  /// <summary>XML comments on single line</summary>
   5:  /** <summary>XML comments on multiple lines</summary> */
   1:  // Single line
   2:  /* Multiple
   3:      line  */
   1:  // Single line
   2:  /* Multiple
   3:      line  */
Data Types
   1:  'Value Types
   2:  Boolean
   3:  Byte, SByte
   4:  Char
   5:  Short, UShort, Integer, UInteger, Long, ULong
   6:  Single, Double
   7:  Decimal
   8:  Date   (alias of System.DateTime)
   9:  structures
  10:  enumerations
  11:   
  12:  'Reference Types
  13:  objects
  14:  String
  15:  arrays
  16:  delegates
  17:   
  18:  'Initializing
  19:  Dim correct As Boolean = True
  20:  Dim b As Byte = &H2A   'hex or &O52 for octal
  21:  Dim person As Object = Nothing
  22:  Dim name As String = "Dwight"
  23:  Dim grade As Char = "B"c
  24:  Dim today As Date = #12/31/2010 12:15:00 PM#
  25:  Dim amount As Decimal = 35.99@
  26:  Dim gpa As Single = 2.9!
  27:  Dim pi As Double = 3.14159265
  28:  Dim lTotal As Long = 123456L
  29:  Dim sTotal As Short = 123S
  30:  Dim usTotal As UShort = 123US
  31:  Dim uiTotal As UInteger = 123UI
  32:  Dim ulTotal As ULong = 123UL
  33:   
  34:  'Nullable Types
  35:  Dim x? As Integer = Nothing
  36:   
  37:  'Anonymous Types
  38:  Dim stu = New With {.Name = "Sue", .Gpa = 3.4}
  39:  Dim stu2 = New With {Key .Name = "Bob", .Gpa = 2.9}
  40:   
  41:  'Implicitly Typed Local Variables
  42:  Dim s = "Hello!"
  43:  Dim nums = New Integer() {1, 2, 3}
  44:  Dim hero = New SuperHero With {.Name = "Batman"}
  45:   
  46:  'Type Information
  47:  Dim x As Integer
  48:  Console.WriteLine(x.GetType())          ' System.Int32
  49:  Console.WriteLine(GetType(Integer))   ' System.Int32
  50:  Console.WriteLine(TypeName(x))        ' Integer
  51:   
  52:  Dim c as New Circle
  53:  isShape = TypeOf c Is Shape   ' True if c is a Shape
  54:  isSame = o1 Is o2   // True if o1 and o2 reference same object
  55:   
  56:  'Type Conversion / Casting
  57:  Dim d As Single = 3.5
  58:  Dim i As Integer = CType(d, Integer)   ' set to 4 (Banker's rounding)
  59:  i = CInt(d)  ' same result as CType
  60:  i = Int(d)    ' set to 3 (Int function truncates the decimal)
  61:   
  62:  Dim s As New Shape
  63:  Dim c As Circle = TryCast(s, Circle)   ' Returns Nothing if type cast fails
  64:  c = DirectCast(s, Circle)   ' Throws InvalidCastException if type cast fails 
   1:  //Value Types
   2:  bool
   3:  byte, sbyte
   4:  char
   5:  short, ushort, int, uint, long, ulong
   6:  float, double
   7:  decimal
   8:  DateTime   (not a built-in C# type)
   9:  structs
  10:  enumerations
  11:   
  12:  //Reference Types
  13:  objects
  14:  string
  15:  arrays
  16:  delegates
  17:   
  18:  //Initializing
  19:  bool correct = true;
  20:  byte b = 0x2A;   // hex
  21:  object person = null;
  22:  string name = "Dwight";
  23:  char grade = 'B';
  24:  DateTime today = DateTime.Parse("12/31/2010 12:15:00 PM");
  25:  decimal amount = 35.99m;
  26:  float gpa = 2.9f;
  27:  double pi = 3.14159265;   // or 3.14159265D
  28:  long lTotal = 123456L;
  29:  short sTotal = 123;
  30:  ushort usTotal = 123;
  31:  uint uiTotal = 123;   // or 123U
  32:  ulong ulTotal = 123;   // or 123UL
  33:   
  34:  //Nullable Types
  35:  int? x = null;
  36:   
  37:  //Anonymous Types
  38:  var stu = new {Name = "Sue", Gpa = 3.5};
  39:  var stu2 = new {Name = "Bob", Gpa = 2.9};   // no Key equivalent
  40:   
  41:  //Implicitly Typed Local Variables
  42:  var s = "Hello!";
  43:  var nums = new int[] { 1, 2, 3 };
  44:  var hero = new SuperHero() { Name = "Batman" };
  45:   
  46:  //Type Information
  47:  int x;
  48:  Console.WriteLine(x.GetType());              // System.Int32
  49:  Console.WriteLine(typeof(int));               // System.Int32
  50:  Console.WriteLine(x.GetType().Name);   // Int32
  51:   
  52:  Circle c = new Circle();
  53:  isShape = c is Shape;   // true if c is a Shape    
  54:   
  55:  isSame = Object.ReferenceEquals(o1, o2)   // true if o1 and o2 reference same object
  56:   
  57:  //Type Conversion / Casting
  58:  float d = 3.5f;
  59:  i = Convert.ToInt32(d);     // Set to 4 (rounds)
  60:  int i = (int)d;     // set to 3 (truncates decimal)    
  61:   
  62:  Shape s = new Shape();
  63:  Circle c = s as Circle;   // Returns null if type cast fails
  64:  c = (Circle)s;   // Throws InvalidCastException if type cast fails
   1:  /* in Java all objects and enums are reference types,  and all primitives are value types
   2:  byte     1 byte     
   3:  short     2 bytes 
   4:  int     4 bytes 
   5:  long     8 bytes 
   6:  float     4 bytes 
   7:  double     8 bytes 
   8:  boolean 1 bit 
   9:  char     2 bytes */
  10:   
  11:   
  12:   
  13:   
  14:   
  15:   
  16:   
  17:   
  18:  //Initializing
  19:  boolean correct = true;
  20:  //NET TO JAVA: Unsigned integer types have no direct equivalent in Java:
  21:  byte b = 0x2A; // hex
  22:  Object person = null;
  23:  String name = "Dwight";
  24:  char grade = 'B';
  25:  LocalDateTime today = LocalDateTime.parse("12/31/2010 12:15:00 PM");
  26:  BigDecimal amount = new BigDecimal(35.99);
  27:  float gpa = 2.9f;
  28:  double pi = 3.14159265; // or 3.14159265D
  29:  long lTotal = 123456L;
  30:  short sTotal = 123;
  31:  //NET TO JAVA: Unsigned integer types have no direct equivalent in Java:
  32:  short usTotal = 123;
  33:  //NET TO JAVA: Unsigned integer types have no direct equivalent in Java:
  34:  int uiTotal = 123; // or 123U
  35:  //NET TO JAVA: Unsigned integer types have no direct equivalent in Java:
  36:  
  37:  long ulTotal = 123; // or 123UL
  38:  
  29:  //Nullable Types
  40:  Integer x = null;
  41:   
  42:  //Anonymous Types
  43:  class AnonymousType
  44:  {
  45:       public String Name;
  46:       public double Gpa;
  47:   
  48:       public AnonymousType(String _Name, double _Gpa)
  49:       {
  50:            Name = _Name;
  51:            Gpa = _Gpa;
  52:       }
  53:  }
  54:  AnonymousType stu = new AnonymousType("Sue", 3.5);
  55:  class AnonymousType2
  56:  {
  57:       public String Name;
  58:       public double Gpa;
  59:   
  60:       public AnonymousType2(String _Name, double _Gpa)
  61:       {
  62:            Name = _Name;
  63:            Gpa = _Gpa;
  64:       }
  65:  }
  66:  AnonymousType2 stu2 = new AnonymousType2("Bob", 2.9); // no Key equivalent
  67:   
  68:  //Implicitly Typed Local Variables
  69:  String s = "Hello!";
  70:  int[] nums = new int[] {1, 2, 3};
  71:  SuperHero hero = new SuperHero();
  72:  hero.Name = "Batman";
  73:   
  74:  //Type Information
  75:  int x;
  76:  System.out.println((new Integer(x)).getClass()); // System.Int32
  77:  System.out.println(Integer.class); // System.Int32
  78:  System.out.println((new Integer(x)).getClass().getSimpleName()); // Int32
  79:   
  80:  Circle c = new Circle();
  81:  isShape = c instanceof Shape; // true if c is a Shape
  82:   
  83:  isSame = o1 == o2 float d = 3.5f;
  84:  i = (int)d; // Set to 4 (rounds)
  85:  int i = (int)d; // set to 3 (truncates decimal)
  86:   
  87:  Shape s = new Shape();
  88:  Circle c = s instanceof Circle ? (Circle)s : null; // Returns null if type cast fails
  89:  c = (Circle)s; // Throws InvalidCastException if type cast fails
   1:   
   2:   
   3:   
   4:   
   5:   
   6:   
   7:   
   8:   
   9:   
  10:   
  11:   
  12:   
  13:   
  14:   
  15:   
  16:   
  17:   
  18:  //Initializing
  19:  val correct = true
  20:  //NET TO JAVA: Unsigned integer types have no direct equivalent in Java:
  21:  val b:Byte = 0x2A // hex
  22:  val person:Any = null
  23:  val name = "Dwight"
  24:  val grade = 'B'
  25:  val today = LocalDateTime.parse("12/31/2010 12:15:00 PM")
  26:  val amount = BigDecimal(35.99)
  27:  val gpa = 2.9f
  28:  val pi = 3.14159265 // or 3.14159265D
  29:  val lTotal = 123456L
  30:  val sTotal:Short = 123
  31:  //NET TO JAVA: Unsigned integer types have no direct equivalent in Java:
  32:  val usTotal:Short = 123
  33:  //NET TO JAVA: Unsigned integer types have no direct equivalent in Java:
  34:  val uiTotal = 123 // or 123U
  35:  //NET TO JAVA: Unsigned integer types have no direct equivalent in Java:
  36:  val ulTotal:Long = 123 // or 123UL
  37:  //Nullable Types
  38:  val x:Int = null
  39:  
  40:   
  41:   
  42:  //Anonymous Types
  43:  class AnonymousType(_Name:String, _Gpa:Double) {
  44:     var Name:String
  45:     var Gpa:Double = 0.toDouble()
  46:        init{
  47:          Name = _Name
  48:          Gpa = _Gpa
  49:     }
  50:  }
  51:   
  52:   
  53:   
  54:   val stu = AnonymousType("Sue", 3.5)
  55:     class AnonymousType2(_Name:String, _Gpa:Double) {
  56:     var Name:String
  57:     var Gpa:Double = 0.toDouble()
  58:     init{
  59:       Name = _Name
  60:       Gpa = _Gpa
  61:     }
  62:   }
  63:   
  64:   
  65:   val stu2 = AnonymousType2("Bob", 2.9) // no Key equivalent
  66:   
  67:      //Implicitly Typed Local Variables
  68:      val s = "Hello!"
  69:      val nums = intArrayOf(1, 2, 3)
  70:      val hero = SuperHero()
  71:      hero.Name = "Batman"
  72:   
  73:   //Type Information
  74:   val x:Int
  75:   println((x).javaClass) // System.Int32
  76:   println(Int::class.java) // System.Int32
  77:   println((x).javaClass.getSimpleName()) // Int32
  78:   
  79:   val c = Circle()
  80:   isShape = c is Shape // true if c is a Shape
  81:   
  82:   isSame = o1 === o2
  83:   val d = 3.5f
  84:   i = d.toInt() // Set to 4 (rounds)
  85:   val i = d.toInt() // set to 3 (truncates decimal)
  86:   
  87:   val s = Shape()
  88:   val c = if (s is Circle) s as Circle else null // Returns null if type cast fails
  89:   c = s as Circle // Throws InvalidCastException if type cast fails
Constants
   1:  Const MAX_STUDENTS As Integer = 25
   2:   
   3:  ' Can set to a const or var; may be initialized in a constructor
   4:  ReadOnly MIN_DIAMETER As Single = 4.93 
   1:  const int MAX_STUDENTS = 25;
   2:   
   3:  // Can set to a const or var; may be initialized in a constructor
   4:  readonly float MIN_DIAMETER = 4.93f; 
   1:  final int MAX_STUDENTS = 25;
   2:   
   3:  // Can set to a const or var; may be initialized in a constructor
   4:  readonly float MIN_DIAMETER = 4.93f;
   1:  val MAX_STUDENTS = 25
   2:  // Can set to a const or var; may be initialized in a constructor
   3:  readonly
   4:  val MIN_DIAMETER = 4.93f
Enumerations
   1:  Enum Action
   2:    Start 
   3:    [Stop]   ' Stop is a reserved word
   4:    Rewind
   5:    Forward
   6:  End Enum
   7:   
   8:  Enum Status
   9:    Flunk = 50
  10:    Pass = 70
  11:    Excel = 90
  12:  End Enum
  13:   
  14:  Dim a As Action = Action.Stop
  15:  If a <> Action.Start Then _
  16:     Console.WriteLine(a.ToString & " is " & a)     ' "Stop is 1"
  17:   
  18:  Console.WriteLine(Status.Pass)     ' 70
  19:  Console.WriteLine(Status.Pass.ToString)     ' Pass
   1:  enum Action {Start, Stop, Rewind, Forward};
   2:  enum Status {Flunk = 50, Pass = 70, Excel = 90};
   3:   
   4:  Action a = Action.Stop;
   5:  if (a != Action.Start)
   6:    Console.WriteLine(a + " is " + (int) a);    // "Stop is 1"
   7:   
   8:  Console.WriteLine((int) Status.Pass);    // 70
   9:  Console.WriteLine(Status.Pass);      // Pass
   1:  enum tangible.Action0Param
   2:  {
   3:      Start, Stop, Rewind, Forward
   4:  };
   5:  enum Status
   6:  {
   7:      Flunk = 50, Pass = 70, Excel = 90
   8:  };
   9:   
  10:  tangible.Action0Param a = tangible.Action0Param::Stop;
  11:  if (a != tangible.Action0Param.Start)
  12:  {
  13:    System.out.println(a + " is " + (int) a); // "Stop is 1"
  14:  }
  15:   
  16:  System.out.println((int) Status.Pass); // 70
  17:  System.out.println(Status.Pass); // Pass
   1:  enum class tangible
   2:  Action0Param
   3:  run({ Start
   4:       Stop
   5:       Rewind
   6:       Forward })
   7:  enum class Status {
   8:    Flunk
   9:  }
  10:  val a = tangible.Action0Param({ tangible.Action0Param.Stop() })
  11:  if (a !== tangible.Action0Param.Start)
  12:  {
  13:    println(a + " is " + a as Int) // "Stop is 1"
  14:  }
  15:  }-
  16:  println(Status.Pass as Int) // 70
  17:  System.out.println(Status.Pass) // Pass
Operators
   1:  'Comparison
   2:  =  <  >  <=  >=  <>
   3:   
   4:  'Arithmetic
   5:  +  -  *  /
   6:  Mod
   7:  \  (integer division)
   8:  ^  (raise to a power)
   9:   
  10:  'Assignment
  11:  =  +=  -=  *=  /=  \=  ^=  <<=  >>=  &=
  12:   
  13:  'Bitwise
  14:  And   Or   Xor   Not   <<   >>
  15:   
  16:  'Logical
  17:  AndAlso   OrElse   And   Or   Xor   Not
  18:   
  19:  'Note: AndAlso and OrElse perform short-circuit logical evaluations
  20:   
  21:  'String Concatenation
  22:  & 
   1:  //Comparison
   2:  ==  <  >  <=  >=  !=
   3:   
   4:  //Arithmetic
   5:  +  -  *  /
   6:  %  (mod)
   7:  /  (integer division if both operands are ints)
   8:  Math.Pow(x, y)
   9:   
  10:  //Assignment
  11:  =  +=  -=  *=  /=   %=  &=  |=  ^=  <<=  >>=  ++  --
  12:   
  13:  //Bitwise
  14:  &   |   ^   ~   <<   >>
  15:   
  16:  //Logical
  17:  &&   ||   &   |   ^   !
  18:   
  19:  //Note: && and || perform short-circuit logical evaluations
  20:   
  21:  //String Concatenation
  22:  +
Java
Kotlin
Choices
   1:  ' Null-coalescing operator if called with 2 arguments
   2:  x = If(y, 5)   ' if y is not Nothing then x = y, else x = 5
   3:   
   4:  ' Ternary/Conditional operator (IIf evaluates 2nd and 3rd expressions)
   5:  greeting = If(age < 20, "What's up?", "Hello")
   6:   
   7:  ' One line doesn't require "End If"
   8:  If age < 20 Then greeting = "What's up?"
   9:  If age < 20 Then greeting = "What's up?" Else greeting = "Hello"
  10:   
  11:  ' Use : to put two commands on same line
  12:  If x <> 100 AndAlso y < 5 Then x *= 5 : y *= 2  
  13:   
  14:  ' Preferred
  15:  If x <> 100 AndAlso y < 5 Then
  16:    x *= 5
  17:    y *= 2
  18:  End If
  19:   
  20:  ' Use _ to break up long single line or use implicit line break
  21:  If whenYouHaveAReally < longLine And
  22:    itNeedsToBeBrokenInto2 > Lines Then _
  23:    UseTheUnderscore(charToBreakItUp)
  24:   
  25:  If x > 5 Then
  26:    x *= y
  27:  ElseIf x = 5 OrElse y Mod 2 = 0 Then
  28:    x += y
  29:  ElseIf x < 10 Then
  30:    x -= y
  31:  Else
  32:    x /= y
  33:  End If
  34:   
  35:  Select Case color   ' Must be a primitive data type
  36:    Case "pink", "red"
  37:      r += 1
  38:    Case "blue"
  39:      b += 1
  40:    Case "green"
  41:      g += 1
  42:    Case Else
  43:      other += 1
  44:  End Select 
   1:  // Null-coalescing operator
   2:  x = y ?? 5;   // if y != null then x = y, else x = 5
   3:   
   4:  // Ternary/Conditional operator
   5:  greeting = age < 20 ? "What's up?" : "Hello";
   6:   
   7:  if (age < 20)
   8:    greeting = "What's up?";
   9:  else
  10:    greeting = "Hello";
  11:   
  12:  // Multiple statements must be enclosed in {}
  13:  if (x != 100 && y < 5) {   
  14:    x *= 5;
  15:    y *= 2;
  16:  }
  17:   
  18:   
  19:  No need for _ or : since ; is used to terminate each statement.
  20:   
  21:   
  22:   
  23:  if (x > 5)
  24:    x *= y;
  25:  else if (x == 5 || y % 2 == 0)
  26:    x += y;
  27:  else if (x < 10)
  28:    x -= y;
  29:  else
  30:    x /= y;
  31:   
  32:   
  33:   
  34:  // Every case must end with break or goto case
  35:  switch (color) {                          // Must be integer or string
  36:    case "pink":
  37:    case "red":    r++;    break;
  38:    case "blue":   b++;   break;
  39:    case "green": g++;   break;
  40:    default:    other++;   break;       // break necessary on default
  41:  } 
   1:  // Null-coalescing operator
   2:  x = y != null ? y : 5; // if y != null then x = y, else x = 5
   3:   
   4:  // Ternary/Conditional operator
   5:  greeting = age < System.Nullable < 20 > "What's up?" if (age < 20) greeting = "What's up?";
   6:  else
   7:    greeting = "Hello";
   8:   
   9:  // Multiple statements must be enclosed in {}
  10:  if (x != 100 && y < 5)
  11:  {
  12:    x *= 5;
  13:    y *= 2;
  14:  }
  15:   
  16:   
  17:   
  18:   
  19:   
  20:   
  21:   
  22:   
  23:  if (x > 5) x *= y;
  24:  else if (x == 5 || y % 2 == 0)
  25:    x += y;
  26:  else if (x < 10)
  27:    x -= y;
  28:  else
  29:    x /= y;
  30:   
  31:   
  32:   
  33:   
  34:   
  35:  switch (color)
  36:  { // Must be integer or string
  37:       case "pink":
  38:       case "red":
  39:           r++; break;
  40:       case "blue":
  41:           b++; break;
  42:       case "green":
  43:           g++; break;
  44:       default:
  45:           other++; break; // break necessary on default
  46:  }
   1:  x = if (y != null) y
   2:  greeting = age < System.Nullable < 20 > "What's up?"
   3:  if (age < 20)
   4:  greeting = "What's up?"
   5:  else
   6:  greeting = "Hello"
   7:   
   8:   
   9:   
  10:   
  11:   
  12:   
  13:   
  14:   
  15:   
  16:   
  17:   
  18:   
  19:   
  20:   
  21:   
  22:   
  23:  if (x !== 100 && y < 5)
  24:  {
  25:    x *= 5
  26:    y *= 2
  27:  }
  28:  if (x > 5)
  29:  x *= y
  30:  else if (x === 5 || y % 2 === 0)
  31:  x += y
  32:  else if (x < 10)
  33:  x -= y
  34:  else
  35:  x /= y
  36:  when (color) {
  37:    // Must be integer or string
  38:    "pink", "red" -> r++
  39:    "blue" -> b++
  40:    "green" -> g++
  41:    else -> other++
  42:  }// break necessary on default
Loops
   1:  'Pre-test Loops:
   2:  While c < 10
   3:    c += 1
   4:  End While     
   5:   
   6:  Do Until c = 10 
   7:    c += 1
   8:  Loop
   9:   
  10:  Do While c < 10
  11:    c += 1
  12:  Loop     
  13:   
  14:  For c = 2 To 10 Step 2
  15:    Console.WriteLine(c)
  16:  Next
  17:   
  18:  'Post-test Loops:
  19:  Do 
  20:    c += 1
  21:  Loop While c < 10     
  22:   
  23:  Do 
  24:    c += 1
  25:  Loop Until c = 10
  26:   
  27:  '  Array or collection looping
  28:  Dim names As String() = {"Fred", "Sue", "Barney"}
  29:  For Each s As String In names
  30:    Console.WriteLine(s)
  31:  Next
  32:   
  33:  ' Breaking out of loops
  34:  Dim i As Integer = 0
  35:  While (True)
  36:    If (i = 5) Then Exit While
  37:    i += 1
  38:  End While
  39:   
  40:  ' Continue to next iteration
  41:  For i = 0 To 4
  42:    If i < 4 Then Continue For
  43:    Console.WriteLine(i)   ' Only prints 4
  44:  Next 
   1:  //Pre-test Loops:  
   2:   
   3:  // no "until" keyword
   4:  while (c < 10)
   5:    c++;
   6:   
   7:   
   8:  for (c = 2; c <= 10; c += 2)
   9:    Console.WriteLine(c);
  10:   
  11:   
  12:   
  13:   
  14:   
  15:   
  16:   
  17:   
  18:  //Post-test Loop:
  19:   
  20:  do
  21:    c++;
  22:  while (c < 10);
  23:   
  24:   
  25:  // Array or collection looping
  26:  string[] names = {"Fred", "Sue", "Barney"};
  27:  foreach (string s in names)
  28:    Console.WriteLine(s);
  29:   
  30:   
  31:  // Breaking out of loops
  32:  int i = 0;
  33:  while (true) {
  34:    if (i == 5)
  35:      break;
  36:    i++;
  37:  }
  38:   
  39:  // Continue to next iteration
  40:  for (i = 0; i <= 4; i++) {
  41:    if (i < 4)
  42:      continue;
  43:    Console.WriteLine(i);   // Only prints 4
  44:  } 
   1:  //Pre-test Loops
   2:   
   3:  // no "until" keyword
   4:  while (c < 10)
   5:  {
   6:    c++;
   7:  }
   8:   
   9:   
  10:  for (c = 2; c <= 10; c += 2)
  11:  {
  12:    System.out.println(c);
  13:  }
  14:   
  15:   
  16:   
  17:   
  18:  //Post-test Loop
  19:   
  20:  do
  21:  {
  22:    c++;
  23:  } while (c < 10);
  24:   
  25:   
  26:  // Array or collection looping
  27:  String[] names = {"Fred", "Sue", "Barney"};
  28:  for (String s : names)
  29:  {
  30:    System.out.println(s);
  31:  }
  32:   
  33:   
  34:  // Breaking out of loops
  35:  int i = 0;
  36:  while (true)
  37:  {
  38:    if (i == 5)
  39:    {
  40:      break;
  41:    }
  42:    i++;
  43:  }
  44:   
  45:  // Continue to next iteration
  46:  for (i = 0; i <= 4; i++)
  47:    {
  48:      if (i < 4)
  49:      {
  50:        continue;
  51:      }
  52:      System.out.println(i); // Only prints 4
  53:    }
   1:    //Pre-test Loops
   2:   
   3:   
   4:  while (c < 10)
   5:  {
   6:    c++
   7:  }
   8:   
   9:   
  10:  c = 2
  11:  while (c <= 10)
  12:  {
  13:    System.out.println(c)
  14:    c += 2
  15:  }
  16:   
  17:   
  18:  //Post-test Loop
  19:   
  20:  do
  21:  {
  22:    c++
  23:  }
  24:  while (c < 10)
  25:   
  26:  // Array or collection looping
  27:  val names = arrayOf<String>("Fred", "Sue", "Barney")
  28:  for (s in names)
  29:  {
  30:    println(s)
  31:  }
  32:   
  33:   
  34:   // Breaking out of loops
  35:  val i = 0
  36:  while (true)
  37:  {
  38:    if (i == 5)
  39:    {
  40:      break
  41:    }
  42:    i++
  43:  }
  44:   
  45:  // Continue to next iteration
  46:  i = 0
  47:  while (i <= 4)
  48:  {
  49:    if (i < 4)
  50:    {
  51:      i++
  52:      continue
  53:    }
  54:    println(i) // Only prints 4
  55:    i++
  56:  }
Arrays
   1:  Dim nums() As Integer = {1, 2, 3} 
   2:  For i As Integer = 0 To nums.Length - 1
   3:    Console.WriteLine(nums(i))
   4:  Next
   5:   
   6:  ' 4 is the index of the last element, so it holds 5 elements
   7:  Dim names(4) As String
   8:  names(0) = "David"
   9:  names(5) = "Bobby"  ' Throws System.IndexOutOfRangeException
  10:   
  11:  ' Resize the array, keeping the existing values (Preserve is optional)
  12:  ReDim Preserve names(6)
  13:   
  14:  Dim twoD(rows-1, cols-1) As Single
  15:  twoD(2, 0) = 4.5
  16:   
  17:  Dim jagged()() As Integer = { _
  18:    New Integer(4) {}, New Integer(1) {}, New Integer(2) {} }
  19:  jagged(0)(4) = 5 
   1:  int[] nums = {1, 2, 3};
   2:  for (int i = 0; i < nums.Length; i++)
   3:    Console.WriteLine(nums[i]);
   4:   
   5:   
   6:  // 5 is the size of the array
   7:  string[] names = new string[5];
   8:  names[0] = "David";
   9:  names[5] = "Bobby";   // Throws System.IndexOutOfRangeException
  10:   
  11:  // Add two elements, keeping the existing values
  12:  Array.Resize(ref names, 7);
  13:   
  14:  float[,] twoD = new float[rows, cols];
  15:  twoD[2,0] = 4.5f; 
  16:   
  17:  int[][] jagged = new int[3][] {
  18:    new int[5], new int[2], new int[3] };
  19:  jagged[0][4] = 5; 
   1:  int[] nums = {1, 2, 3};
   2:  for (int i = 0; i < nums.length; i++)
   3:  {
   4:    System.out.println(nums[i]);
   5:  }
   6:  // 5 is the size of the array
   7:  String[] names = new String[5];
   8:  names[0] = "David";
   9:  names[5] = "Bobby"; // Throws System.IndexOutOfRangeException
  10:   
  11:  // Add two elements, keeping the existing values
  12:  tangible.RefObject<T[]> tempRef_names = new tangible.RefObject<T[]>(names);
  13:  Array.Resize(tempRef_names, 7);
  14:  names = tempRef_names.refArgValue;
  15:   
  16:  float[][] twoD = new float[rows][cols];
  17:  twoD[2][0] = 4.5f;
  18:   
  19:  int[][] jagged = new int[][]
  20:  {
  21:      new int[5],
  22:      new int[2],
  23:      new int[3]
  24:  };
  25:  jagged[0][4] = 5;
  26:   
  27:  //Helper class added by C# to Java Converter:
  28:  package_Keyword tangible;
  29:   
  30:  FunctionalInterface public interface Action0Param
  31:  {
  32:      void invoke();
  33:  }
   1:  val nums = intArrayOf(1, 2, 3)
   2:  for (i in nums.indices)
   3:  {
   4:    println(nums[i])
   5:  }
   6:  // 5 is the size of the array
   7:  val names = arrayOfNulls<String>(5)
   8:  names[0] = "David"
   9:  names[5] = "Bobby" // Throws System.IndexOutOfRangeException
  10:   
  11:  // Add two elements, keeping the existing values
  12:  val tempRef_names = tangible.RefObject<Array<T>>(names)
  13:  Array.Resize(tempRef_names, 7)
  14:  names = tempRef_names.refArgValue
  15:   
  16:  val twoD = Array<FloatArray>(rows, {FloatArray(cols)})
  17:  twoD[2][0] = 4.5f
  18:   
  19:  val jagged = arrayOf<IntArray>(IntArray(5), IntArray(2), IntArray(3))
  20:  jagged[0][4] = 5
  21:   
  22:   
  23:   
  24:   
  25:   
  26:   
  27:  //Helper class added by C# to Java Converter:
  28:  private package_Keyword tangible;
  29:   
  30:  FunctionalInterface public interface Action0Param
  31:  {
   5:      void invoke();
   6:  }
Collections
   1:  ' Popular classes in System.Collections (stored as Object)
   2:  ArrayList
   3:  Hashtable
   4:  Queue
   5:  Stack
   6:   
   7:  'Popular classes in System.Collections.Generic (stored as type T)
   8:  List(Of T)
   9:  SortedList(Of TKey, TValue)
  10:  Dictionary(Of TKey, TValue)
  11:  Queue(Of T)
  12:  Stack(Of T)
  13:   
  14:  'Popular classes in System.Collections.Concurrent (thread safe)
  15:  BlockingCollection(Of T)
  16:  ConcurrentDictionary(Of TKey, TValue)
  17:  ConcurrentQueue(Of T)
  18:  ConcurrentStack(Of T)
  19:   
  20:  'Microsoft.VisualBasic (not recommended)
  21:  Collection
  22:   
  23:   
  24:  ' Store ID and name
  25:  Dim students As New Dictionary(Of Integer, String) From
  26:  {
  27:    {123, "Bob"},
  28:    {444, "Sue"},
  29:    {555, "Jane"}
  30:  }
  31:   
  32:  students.Add(987, "Gary")
  33:  Console.WriteLine(students(444))   ' Sue
  34:   
  35:  ' Display all
  36:  For Each stu In students
  37:    Console.WriteLine(stu.Key & " = " & stu.Value)
  38:  Next
  39:   
  40:  ' Method iterator for custom iteration over a collection
  41:  Iterator Function OddNumbers(ByVal lastNum As Integer) As System.Collections.IEnumerable
  42:    For num = 1 To lastNum
  43:      If num Mod 2 = 1 Then
  44:        Yield num
  45:      End If
  46:    Next
  47:  End Function
  48:   
  49:  ' 1 3 5 7
  50:  For Each num In OddNumbers(7)
  51:    Console.Write(num & " ")
  52:  Next
   1:  // Popular classes in System.Collections (stored as Object)
   2:  ArrayList
   3:  Hashtable
   4:  Queue
   5:  Stack
   6:   
   7:  //Popular classes in System.Collections.Generic (stored as type T)
   8:  List<T>
   9:  SortedList<TKey, TValue>
  10:  Dictionary<TKey, TValue>
  11:  Queue<T>
  12:  Stack<T>
  13:   
  14:  //Popular classes in System.Collections.Concurrent (thread safe)
  15:  BlockingCollection<T>
  16:  ConcurrentDictionary<TKey, TValue>
  17:  ConcurrentQueue<T>
  18:  ConcurrentStack<T>
  19:   
  20:  //No equivalent to Microsoft.VisualBasic.Collection
  21:   
  22:   
  23:  // Store ID and name
  24:  var students = new Dictionary<int, string>
  25:  {
  26:    { 123, "Bob" },
  27:    { 444, "Sue" },
  28:    { 555, "Jane" }
  29:  };
  30:   
  31:  students.Add(987, "Gary");
  32:  Console.WriteLine(students[444]);   // Sue
  33:   
  34:  // Display all
  35:  foreach (var stu in students) {
  36:    Console.WriteLine(stu.Key + " = " + stu.Value);
  37:  }
  38:   
  39:   
  40:  // Method iterator for custom iteration over a collection
  41:  static System.Collections.Generic.IEnumerable<int> OddNumbers(int lastNum)
  42:  {
  43:    for (var num = 1; num <= lastNum; num++)
  44:      if (num % 2 == 1)
  45:        yield return num;
  46:  }
  47:   
  48:  // 1 3 5 7
  49:  foreach (double num in OddNumbers(7))
  50:  {
  51:    Console.Write(num + " ");
  52:  }
   1:   
   2:   
   3:   
   4:   
   5:   
   6:   
   7:   
   8:   
   9:   
  10:   
  11:   
  12:   
  13:   
  14:   
  15:   
  16:   
  17:   
  18:   
  19:   
  20:   
  21:   
  22:   
  23:  // Store ID and name
  24:  HashMap<Integer, String> students = new HashMap<Integer, String>
  25:  (
  26:    Map.ofEntries(Map.entry(123, "Bob"), 
  27:    Map.entry(444, "Sue"), 
  28:    Map.entry(555, "Jane"))
  29:  );
  30:   
  31:  students.put(987, "Gary");
  32:  System.out.println(students.get(444)); // Sue
  33:   
  34:  // Display all
  35:  for (Map.Entry<Integer, String> stu : students.entrySet())
  36:  {
  37:      System.out.println(stu.getKey() + " = " + stu.getValue());
  38:  }
  39:   
  40:  // Method iterator for custom iteration over a collection
  41:  //C# TO JAVA TODO TASK: Local functions are not converted by C# to Java Converter:
  42:  //  static System.Collections.Generic.IEnumerable<int> OddNumbers(int lastNum)
  43:  //  {
  44:  //    for (var num = 1; num <= lastNum; num++)
  45:  //      if (num % 2 == 1)
  46:  //        yield return num;
  47:  //  }
  48:   
  49:  // 1 3 5 7
  50:  for (double num : OddNumbers(7))
  51:  {
  52:      System.out.print(num + " ");
  53:  }
   1:   
   2:   
   3:   
   4:   
   5:   
   6:   
   7:   
   8:   
   9:   
  10:   
  11:   
  12:   
  13:   
  14:   
  15:   
  16:   
  17:   
  18:   
  19:   
  20:   
  21:   
  22:   
  23:  // Store ID and name
  24:  var students = HashMap<Int, String>(
  25:    Map.ofEntries(Map.entry(123, "Bob"),
  26:                  Map.entry(444, "Sue"),
  27:                  Map.entry(555, "Jane")
  28:                 )
  29:  )
  30:   
  31:  students.put(987, "Gary")
  32:  System.out.println(students.get(444)) // Sue
  33:   
  34:  // Display all
  35:  for (stu in students.entrySet())
  36:  {
  37:    println(stu.getKey() + " = " + stu.getValue())
  38:  }
  39:   
  40:   
  41:   
  42:   
  43:   
  44:   
  45:   
  46:   
  47:   
  48:   
  49:   // 1 3 5 7
  50:  for (num in OddNumbers(7))
  51:  {
  52:    print(num + " ")
  53:  }
Functions
   1:  ' Pass by value (in, default), reference (in/out), and reference (out) 
   2:  Sub TestFunc(ByVal x As Integer, ByRef y As Integer, ByRef z As Integer)
   3:    x += 1
   4:    y += 1
   5:    z = 5
   6:  End Sub
   7:   
   8:  Dim a = 1, b = 1, c As Integer   ' c set to zero by default 
   9:  TestFunc(a, b, c)
  10:  Console.WriteLine("{0} {1} {2}", a, b, c)   ' 1 2 5
  11:   
  12:  ' Accept variable number of arguments
  13:  Function Sum(ByVal ParamArray nums As Integer()) As Integer
  14:    Sum = 0 
  15:    For Each i As Integer In nums
  16:      Sum += i
  17:    Next
  18:  End Function   ' Or use Return statement like C#
  19:   
  20:  Dim total As Integer = Sum(4, 3, 2, 1)   ' returns 10
  21:   
  22:  ' Optional parameters must be listed last and must have a default value
  23:  Sub SayHello(ByVal name As String, Optional ByVal prefix As String = "")
  24:    Console.WriteLine("Greetings, " & prefix & " " & name)
  25:  End Sub
  26:   
  27:  SayHello("Strangelove", "Dr.")
  28:  SayHello("Mom")
   1:  // Pass by value (in, default), reference (in/out), and reference (out)
   2:  void TestFunc(int x, ref int y, out int z) {
   3:    x++;  
   4:    y++;
   5:    z = 5;
   6:  }
   7:   
   8:  int a = 1, b = 1, c;  // c doesn't need initializing
   9:  TestFunc(a, ref b, out c);
  10:  Console.WriteLine("{0} {1} {2}", a, b, c);  // 1 2 5
  11:   
  12:  // Accept variable number of arguments
  13:  int Sum(params int[] nums) {
  14:    int sum = 0;
  15:    foreach (int i in nums)
  16:      sum += i;
  17:    return sum;
  18:  }
  19:   
  20:  int total = Sum(4, 3, 2, 1);   // returns 10
  21:   
  22:  /* C# 4.0 supports optional parameters. Previous versions required function overloading. */ 
  23:  void SayHello(string name, string prefix = "") {
  24:    Console.WriteLine("Greetings, " + prefix + " " + name);
  25:  } 
  26:   
  27:  SayHello("Strangelove", "Dr.");
  28:  SayHello("Mom"); 
   1:  // Pass by value (in, default), reference (in/out), and reference (out)
   2:  private void TestFunc(int x, tangible.RefObject<Integer> y, tangible.OutObject<Integer> z)
   3:  {
   4:    x++;
   5:    y.refArgValue++;
   6:    z.outArgValue = 5;
   7:  }
   8:  private int a = 1, b = 1, c; // c doesn't need initializing
   9:  tangible.RefObject<Integer> tempRef_b = new tangible.RefObject<Integer>(b);
  10:  tangible.OutObject<Integer> tempOut_c = new tangible.OutObject<Integer>();
  11:  TestFunc(a, tempRef_b, tempOut_c);
  12:  c = tempOut_c.outArgValue;
  13:  b = tempRef_b.refArgValue;
  14:  System.out.printf("%1$s %2$s %3$s" + "\r\n", a, b, c); // 1 2 5
  15:   
  16:  // Accept variable number of arguments
  17:  private int Sum(int... nums)
  18:  {
  19:    int sum = 0;
  20:    for (int i : nums)
  21:    {
  22:      sum += i;
  23:    }
  24:    return sum;
  25:  }
  26:  private int total = Sum(4, 3, 2, 1); // returns 10
  27:  /* C# 4.0 supports optional parameters. Previous versions required function overloading. */
  28:   
  29:  private void SayHello(String name)
  30:  {
  31:      SayHello(name, "");
  32:  }
  33:   
  34:  //C# TO JAVA NOTE: Java does not support optional parameters. Overloaded method(s) are created above:
  35:  //ORIGINAL LINE: void SayHello(string name, string prefix = "")
  36:  private void SayHello(String name, String prefix)
  37:  {
  38:    System.out.println("Greetings, " + prefix + " " + name);
  39:  }
  40:   
  41:  SayHello("Strangelove", "Dr.");
  42:  SayHello("Mom");
  43:   
  44:  //----------------------------------------------------------------------------------------
  45:  //Helper class is used to replicate the ability to pass arguments by reference in Java.
  46:  //----------------------------------------------------------------------------------------
  47:  public final class RefObject<T>
  48:  {
  49:      public T refArgValue;
  50:      public RefObject(T refArg)
  51:      {
  52:          refArgValue = refArg;
  53:      }
  54:  }
  55:   
  56:  //----------------------------------------------------------------------------------------
  57:  // Helper class is used to replicate the ability to have 'out' parameters in Java.
  58:  //----------------------------------------------------------------------------------------
  59:  public final class OutObject<T>
  60:  {
  61:      public T outArgValue;
  62:  }
Kotlin
Strings
   1:  'Special character constants (all also accessible from ControlChars class)
   2:  vbCrLf, vbCr, vbLf, vbNewLine
   3:  vbNullString
   4:  vbTab
   5:  vbBack
   6:  vbFormFeed
   7:  vbVerticalTab
   8:  ""
   9:   
  10:  ' String concatenation (use & or +)
  11:  Dim school As String = "Harding" & vbTab
  12:  school = school & "University"   ' school is "Harding (tab) University"
  13:  school &= "University"   ' Same thing (+= does the same)    
  14:   
  15:  ' Chars
  16:  Dim letter As Char = school.Chars(0)   ' letter is H
  17:  letter = "Z"c                                         ' letter is Z
  18:  letter = Convert.ToChar(65)                ' letter is A
  19:  letter = Chr(65)                                 ' same thing
  20:  Dim word() As Char = school.ToCharArray ' word holds Harding
  21:   
  22:  ' No string literal operator
  23:  Dim filename As String = "c:\temp\x.dat"
  24:   
  25:  ' String comparison
  26:  Dim mascot As String = "Bisons"
  27:  If (mascot = "Bisons") Then   ' true
  28:  If (mascot.Equals("Bisons")) Then   ' true
  29:  If (mascot.ToUpper().Equals("BISONS")) Then  ' true
  30:  If (mascot.CompareTo("Bisons") = 0) Then   ' true
  31:   
  32:  ' String matching with Like - Regex is more powerful
  33:  If ("John 3:16" Like "Jo[Hh]? #:*") Then   'true
  34:   
  35:  ' Substring
  36:  s = mascot.Substring(2, 3)) ' son
  37:  s = Mid("testing", 2, 3)   ' est
  38:   
  39:  ' Replacement
  40:  s = mascot.Replace("sons", "nomial")) ' s is "Binomial"
  41:   
  42:  ' Split
  43:  Dim names As String = "Michael,Dwight,Jim,Pam"
  44:  Dim parts() As String = names.Split(",".ToCharArray())   ' One name in each slot
  45:   
  46:  ' Date to string
  47:  Dim dt As New DateTime(1973, 10, 12)
  48:  Dim s As String = "My birthday: " & dt.ToString("MMM dd, yyyy")   ' Oct 12, 1973
  49:   
  50:  ' Integer to String
  51:  Dim x As Integer = 2
  52:  Dim y As String = x.ToString()     ' y is "2"
  53:   
  54:  ' String to Integer
  55:  Dim x As Integer = Convert.ToInt32("-5")     ' x is -5
  56:   
  57:  ' Mutable string
  58:  Dim buffer As New System.Text.StringBuilder("two ")
  59:  buffer.Append("three ")
  60:  buffer.Insert(0, "one ")
  61:  buffer.Replace("two", "TWO")
  62:  Console.WriteLine(buffer)         ' Prints "one TWO three" 
   1:  //Escape sequences
   2:  \r    // carriage-return
   3:  \n    // line-feed
   4:  \t    // tab
   5:  \\    // backslash
   6:  \"    // quote"
   7:   
   8:   
   9:  // String concatenation
  10:  string school = "Harding\t";
  11:  school = school + "University";   // school is "Harding (tab) University"
  12:  school += "University";   // Same thing
  13:   
  14:  // Chars
  15:  char letter = school[0];            // letter is H
  16:  letter = 'Z';                               // letter is Z
  17:  letter = Convert.ToChar(65);     // letter is A
  18:  letter = (char)65;                    // same thing
  19:  char[] word = school.ToCharArray();   // word holds Harding
  20:   
  21:  // String literal
  22:  string filename = @"c:\temp\x.dat";   // Same as "c:\\temp\\x.dat"
  23:   
  24:  // String comparison
  25:  string mascot = "Bisons";
  26:  if (mascot == "Bisons")    // true
  27:  if (mascot.Equals("Bisons"))   // true
  28:  if (mascot.ToUpper().Equals("BISONS"))   // true
  29:  if (mascot.CompareTo("Bisons") == 0)    // true
  30:   
  31:  // String matching - No Like equivalent, use Regex
  32:   
  33:   
  34:  // Substring
  35:  s = mascot.Substring(2, 3))     // son
  36:  s = "testing".Substring(1, 3);   // est (no Mid)
  37:   
  38:  // Replacement
  39:  s = mascot.Replace("sons", "nomial"))     // Binomial
  40:   
  41:  // Split
  42:  string names = "Michael,Dwight,Jim,Pam";
  43:  string[] parts = names.Split(",".ToCharArray());   // One name in each slot
  44:   
  45:  // Date to string
  46:  DateTime dt = new DateTime(1973, 10, 12);
  47:  string s = dt.ToString("MMM dd, yyyy");     // Oct 12, 1973
  48:   
  49:  // int to string
  50:  int x = 2;
  51:  string y = x.ToString();     // y is "2"
  52:  // string to int
  53:  int x = Convert.ToInt32("-5");     // x is -5
  54:   
  55:  // Mutable string
  56:  System.Text.StringBuilder buffer = new System.Text.StringBuilder("two ");
  57:  buffer.Append("three ");
  58:  buffer.Insert(0, "one ");
  59:  buffer.Replace("two", "TWO");
  60:  Console.WriteLine(buffer);     // Prints "one TWO three"
Java
Kotlin
Regular Expressions
   1:   Imports System.Text.RegularExpressions
   2:   
   3:  ' Match a string pattern
   4:  Dim r As New Regex("j[aeiou]h?. \d:*", RegexOptions.IgnoreCase Or _
   5:          RegexOptions.Compiled)
   6:  If (r.Match("John 3:16").Success) Then   'true
   7:      Console.WriteLine("Match")
   8:  End If
   9:   
  10:  ' Find and remember all matching patterns
  11:  Dim s As String = "My number is 305-1881, not 305-1818."
  12:  Dim r As New Regex("(\d+-\d+)")
  13:  Dim m As Match = r.Match(s)     ' Matches 305-1881 and 305-1818
  14:  While m.Success
  15:      Console.WriteLine("Found number: " & m.Groups(1).Value & " at position " _
  16:              & m.Groups(1).Index.ToString)
  17:      m = m.NextMatch()
  18:  End While
  19:   
  20:  ' Remeber multiple parts of matched pattern
  21:  Dim r As New Regex("(\d\d):(\d\d) (am|pm)")
  22:  Dim m As Match = r.Match("We left at 03:15 pm.")
  23:  If m.Success Then
  24:      Console.WriteLine("Hour: " & m.Groups(1).ToString)       ' 03
  25:      Console.WriteLine("Min: " & m.Groups(2).ToString)         ' 15
  26:      Console.WriteLine("Ending: " & m.Groups(3).ToString)   ' pm
  27:  End If
  28:   
  29:  ' Replace all occurrances of a pattern
  30:  Dim r As New Regex("h\w+?d", RegexOptions.IgnoreCase)
  31:  Dim s As String = r.Replace("I heard this was HARD!", "easy")   ' I easy this was easy!
  32:   
  33:  ' Replace matched patterns
  34:  Dim s As String = Regex.Replace("123 < 456", "(\d+) . (\d+)", "$2 > $1")   ' 456 > 123
  35:   
  36:  ' Split a string based on a pattern
  37:  Dim names As String = "Michael, Dwight, Jim, Pam"
  38:  Dim r As New Regex(",\s*")
  39:  Dim parts() As String = r.Split(names)   ' One name in each slot 
   1:  using System.Text.RegularExpressions;
   2:   
   3:  // Match a string pattern
   4:  Regex r = new Regex(@"j[aeiou]h?. \d:*", RegexOptions.IgnoreCase |
   5:          RegexOptions.Compiled);
   6:  if (r.Match("John 3:16").Success)   // true
   7:      Console.WriteLine("Match");
   8:   
   9:   
  10:  // Find and remember all matching patterns
  11:  string s = "My number is 305-1881, not 305-1818.";
  12:  Regex r = new Regex("(\\d+-\\d+)");
  13:  // Matches 305-1881 and 305-1818
  14:  for (Match m = r.Match(s); m.Success; m = m.NextMatch())
  15:      Console.WriteLine("Found number: " + m.Groups[1] + " at position " +
  16:          m.Groups[1].Index);
  17:   
  18:   
  19:   
  20:  // Remeber multiple parts of matched pattern
  21:  Regex r = new Regex("@(\d\d):(\d\d) (am|pm)");
  22:  Match m = r.Match("We left at 03:15 pm.");
  23:  if (m.Success) {
  24:      Console.WriteLine("Hour: " + m.Groups[1]);       // 03
  25:      Console.WriteLine("Min: " + m.Groups[2]);         // 15
  26:      Console.WriteLine("Ending: " + m.Groups[3]);   // pm
  27:  }
  28:   
  29:  // Replace all occurrances of a pattern
  30:  Regex r = new Regex("h\\w+?d", RegexOptions.IgnoreCase);
  31:  string s = r.Replace("I heard this was HARD!", "easy"));   // I easy this was easy!
  32:   
  33:  // Replace matched patterns
  34:  string s = Regex.Replace("123 < 456", @"(\d+) . (\d+)", "$2 > $1");   // 456 > 123
  35:   
  36:  // Split a string based on a pattern
  37:  string names = "Michael, Dwight, Jim, Pam";
  38:  Regex r = new Regex(@",\s*");
  39:  string[] parts = r.Split(names);   // One name in each slot 
Java
Kotlin
Exception Handling
   1:  ' Throw an exception
   2:  Dim ex As New Exception("Something is really wrong.")
   3:  Throw  ex 
   4:   
   5:  ' Catch an exception
   6:  Try 
   7:    y = 0
   8:    x = 10 / y
   9:  Catch ex As Exception When y = 0 ' Argument and When is optional
  10:    Console.WriteLine(ex.Message)
  11:  Finally
  12:    Beep()
  13:  End Try
  14:   
  15:  ' Deprecated unstructured error handling
  16:  On Error GoTo MyErrorHandler
  17:  ...
  18:  MyErrorHandler: Console.WriteLine(Err.Description)
   1:  Exception up = new Exception("Something is really wrong.");
   2:  throw up;  // ha ha
   3:   
   4:  // Catch an exception
   5:  try { 
   6:    y = 0;
   7:    x = 10 / y;
   8:  }
   9:  catch (Exception ex) {   // Argument is optional, no "When" keyword 
  10:    Console.WriteLine(ex.Message);
  11:  }
  12:  finally {
  13:    Microsoft.VisualBasic.Interaction.Beep();
  14:  } 
Java
Kotlin
Namespaces
   1:  Namespace Harding.Compsci.Graphics 
   2:    ...
   3:  End Namespace
   4:   
   5:  ' or
   6:   
   7:  Namespace Harding
   8:    Namespace Compsci
   9:      Namespace Graphics 
  10:        ...
  11:      End Namespace
  12:    End Namespace
  13:  End Namespace
  14:   
  15:  Imports Harding.Compsci.Graphics 
   1:  namespace Harding.Compsci.Graphics {
   2:    ...
   3:  }
   4:   
   5:  // or
   6:   
   7:  namespace Harding {
   8:    namespace Compsci {
   9:      namespace Graphics {
  10:        ...
  11:      }
  12:    }
  13:  }
  14:   
  15:  using Harding.Compsci.Graphics; 
Java
Kotlin
Attributes
   1:  ' Attribute can be applied to anything
   2:  Public Class IsTestedAttribute
   3:      Inherits Attribute
   4:  End Class
   5:   
   6:  ' Attribute can only be applied to classes or structs
   7:  <AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct)>
   8:  Public Class AuthorAttribute
   9:      Inherits Attribute
  10:   
  11:      Public Property Name As String
  12:      Public Property Version As Integer = 0
  13:   
  14:      Public Sub New(ByVal name As String)
  15:          Me.Name = name
  16:      End Sub
  17:  End Class
  18:   
  19:  <Author("Sue", Version:=3)>
  20:  Class Shape
  21:   
  22:      <IsTested()>
  23:      Sub Move()
  24:          ' Do something...
  25:      End Sub
  26:  End Class
   1:  // Attribute can be applied to anything
   2:  public class IsTestedAttribute : Attribute
   3:  {
   4:  }
   5:   
   6:  // Attribute can only be applied to classes or structs
   7:  [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
   8:  public class AuthorAttribute : Attribute {
   9:   
  10:      public string Name { get; set; }
  11:      public int Version { get; set; }
  12:   
  13:      public AuthorAttribute(string name) {
  14:          Name = name;
  15:          Version = 0;
  16:      }
  17:  }
  18:   
  19:  [Author("Sue", Version = 3)]
  20:  class Shape {
  21:   
  22:      [IsTested]
  23:      void Move() {
  24:          // Do something...
  25:      }
  26:  }
Java
Kotlin
Classes & Interfaces
   1:  'Access Modifiers
   2:  Public
   3:  Private
   4:  Friend
   5:  Protected
   6:  Protected Friend
   7:   
   8:  'Class Modifiers
   9:  MustInherit
  10:  NotInheritable
  11:   
  12:  'Method Modifiers
  13:  MustOverride
  14:  NotInheritable
  15:  Shared
  16:  Overridable
  17:   
  18:  ' All members are Shared
  19:  Module
  20:   
  21:  ' Partial classes
  22:  Partial Class Team
  23:    ...
  24:    Protected name As String
  25:    Public Overridable Sub DisplayName()
  26:      Console.WriteLine(name)
  27:    End Sub
  28:  End Class 
  29:   
  30:  ' Inheritance
  31:  Class FootballTeam
  32:    Inherits Team
  33:    ...
  34:    Public Overrides Sub DisplayName()
  35:      Console.WriteLine("** " + name + " **")
  36:    End Sub
  37:  End Class 
  38:   
  39:  ' Interface definition
  40:  Interface IAlarmClock
  41:    Sub Ring()
  42:    Property TriggerDateTime() As DateTime
  43:  End Interface
  44:   
  45:  ' Extending an interface
  46:  Interface IAlarmClock
  47:    Inherits IClock
  48:    ...
  49:  End Interface
  50:   
  51:  ' Interface implementation
  52:  Class WristWatch 
  53:    Implements IAlarmClock, ITimer
  54:   
  55:    Public Sub Ring() Implements IAlarmClock.Ring
  56:      Console.WriteLine("Wake up!")
  57:    End Sub
  58:   
  59:    Public Property TriggerDateTime As DateTime Implements IAlarmClock.TriggerDateTime
  60:    ...
  61:  End Class 
   1:  //Access Modifiers
   2:  public
   3:  private
   4:  internal
   5:  protected
   6:  protected internal
   7:   
   8:  //Class Modifiers
   9:  abstract
  10:  sealed
  11:  static
  12:   
  13:  //Method Modifiers
  14:  abstract
  15:  sealed
  16:  static
  17:  virtual
  18:   
  19:  //No Module equivalent - just use static class
  20:   
  21:  // Partial classes
  22:  partial class Team {
  23:    ...
  24:    protected string name;
  25:    public virtual void DislpayName() {
  26:      Console.WriteLine(name);
  27:  }
  28:   
  29:   
  30:  // Inheritance
  31:  class FootballTeam : Team {
  32:    ...
  33:    public override void DislpayName() {
  34:      Console.WriteLine("** " + name + " **");
  35:    }
  36:  }
  37:   
  38:   
  39:  // Interface definition
  40:  interface IAlarmClock {
  41:    void Ring();
  42:    DateTime CurrentDateTime { get; set; }
  43:  }
  44:   
  45:  // Extending an interface 
  46:  interface IAlarmClock : IClock {
  47:    ...
  48:  }
  49:   
  50:   
  51:  // Interface implementation
  52:  class WristWatch : IAlarmClock, ITimer {
  53:   
  54:    public void Ring() {
  55:      Console.WriteLine("Wake up!");
  56:    }
  57:   
  58:    public DateTime TriggerDateTime { get; set; }
  59:    ...
  60:  } 
Java
Kotlin
Constructors & Destructors
   1:  Class SuperHero
   2:    Inherits Person
   3:   
   4:    Private powerLevel As Integer
   5:    Private name As String
   6:   
   7:    ' Default constructor
   8:    Public Sub New()
   9:      powerLevel = 0
  10:      name = "Super Bison"
  11:    End Sub
  12:   
  13:    Public Sub New(ByVal powerLevel As Integer)
  14:      Me.New("Super Bison")   ' Call other constructor
  15:      Me.powerLevel = powerLevel
  16:    End Sub
  17:   
  18:    Public Sub New(ByVal name As String)
  19:      MyBase.New(name)   ' Call base classes' constructor
  20:      Me.name = name
  21:    End Sub
  22:   
  23:    Shared Sub New()
  24:      ' Shared constructor invoked before 1st instance is created
  25:    End Sub
  26:   
  27:    Protected Overrides Sub Finalize() 
  28:     ' Destructor to free unmanaged resources
  29:      MyBase.Finalize()
  30:    End Sub
  31:  End Class
   1:  class SuperHero : Person {
   2:   
   3:    private int powerLevel;
   4:    private string name;
   5:   
   6:   
   7:    // Default constructor
   8:    public SuperHero() {
   9:      powerLevel = 0;
  10:      name = "Super Bison";
  11:    }
  12:   
  13:    public SuperHero(int powerLevel)
  14:      : this("Super Bison") {   // Call other constructor
  15:      this.powerLevel = powerLevel; 
  16:    }
  17:   
  18:    public SuperHero(string name)
  19:      : base(name) {   // Call base classes' constructor
  20:      this.name = name;
  21:    }
  22:   
  23:    static SuperHero() {
  24:      // Static constructor invoked before 1st instance is created
  25:    }
  26:   
  27:    ~SuperHero() {
  28:      // Destructor implicitly creates a Finalize method
  29:    }
  30:   
  31:  }
Java
Kotlin
Using Objects
   1:  Dim hero As SuperHero = New SuperHero
   2:  ' or
   3:  Dim hero As New SuperHero
   4:   
   5:  With hero
   6:    .Name = "SpamMan"
   7:    .PowerLevel = 3
   8:  End With
   9:   
  10:  hero.Defend("Laura Jones")
  11:  hero.Rest()     ' Calling Shared method
  12:  ' or
  13:  SuperHero.Rest()
  14:   
  15:  Dim hero2 As SuperHero = hero  ' Both reference the same object
  16:  hero2.Name = "WormWoman"
  17:  Console.WriteLine(hero.Name)   ' Prints WormWoman
  18:   
  19:  hero = Nothing    ' Free the object
  20:   
  21:  If hero Is Nothing Then _
  22:    hero = New SuperHero
  23:   
  24:  Dim obj As Object = New SuperHero
  25:  If TypeOf obj Is SuperHero Then _
  26:    Console.WriteLine("Is a SuperHero object.")
  27:   
  28:  ' Mark object for quick disposal
  29:  Using reader As StreamReader = File.OpenText("test.txt")
  30:    Dim line As String = reader.ReadLine()
  31:    While Not line Is Nothing
  32:      Console.WriteLine(line)
  33:      line = reader.ReadLine()
  34:    End While
  35:  End Using 
   1:  SuperHero hero = new SuperHero();
   2:   
   3:   
   4:   
   5:  // No "With" but can use object initializers
   6:  SuperHero hero = new SuperHero() { Name = "SpamMan", PowerLevel = 3 };
   7:   
   8:  hero.Defend("Laura Jones");
   9:  SuperHero.Rest();   // Calling static method
  10:   
  11:   
  12:   
  13:  SuperHero hero2 = hero;   // Both reference the same object
  14:  hero2.Name = "WormWoman";
  15:  Console.WriteLine(hero.Name);   // Prints WormWoman
  16:   
  17:  hero = null ;   // Free the object
  18:   
  19:  if (hero == null)
  20:    hero = new SuperHero();
  21:   
  22:  Object obj = new SuperHero(); 
  23:  if (obj is SuperHero)
  24:    Console.WriteLine("Is a SuperHero object.");
  25:  // Mark object for quick disposal
  26:  using (StreamReader reader = File.OpenText("test.txt")) {
  27:    string line;
  28:    while ((line = reader.ReadLine()) != null)
  29:      Console.WriteLine(line);
  30:  } 
Java
Kotlin
Structs
   1:  Structure Student
   2:    Public name As String
   3:    Public gpa As Single
   4:   
   5:    Public Sub New(ByVal name As String, ByVal gpa As Single)
   6:      Me.name = name
   7:      Me.gpa = gpa
   8:    End Sub
   9:  End Structure
  10:   
  11:  Dim stu As Student = New Student("Bob", 3.5)
  12:  Dim stu2 As Student = stu  
  13:   
  14:  stu2.name = "Sue"
  15:  Console.WriteLine(stu.name)    ' Prints Bob
  16:  Console.WriteLine(stu2.name)  ' Prints Sue
   1:  struct Student {
   2:    public string name;
   3:    public float gpa;
   4:   
   5:    public Student(string name, float gpa) {
   6:      this.name = name;
   7:      this.gpa = gpa;
   8:    }
   9:  }
  10:   
  11:  Student stu = new Student("Bob", 3.5f);
  12:  Student stu2 = stu;  
  13:   
  14:  stu2.name = "Sue";
  15:  Console.WriteLine(stu.name);    // Prints Bob
  16:  Console.WriteLine(stu2.name);   // Prints Sue
Java
Kotlin
Properties
   1:  ' Auto-implemented properties are new to VB10
   2:  Public Property Name As String
   3:  Public Property Size As Integer = -1     ' Default value, Get and Set both Public
   4:   
   5:  ' Traditional property implementation
   6:  Private mName As String
   7:  Public Property Name() As String
   8:      Get
   9:          Return mName
  10:      End Get
  11:      Set(ByVal value As String)
  12:          mName = value
  13:      End Set
  14:  End Property
  15:   
  16:  ' Read-only property
  17:  Private mPowerLevel As Integer
  18:  Public ReadOnly Property PowerLevel() As Integer
  19:      Get
  20:          Return mPowerLevel
  21:      End Get
  22:  End Property
  23:   
  24:  ' Write-only property
  25:  Private mHeight As Double
  26:  Public WriteOnly Property Height() As Double
  27:      Set(ByVal value As Double)
  28:          mHeight = If(value < 0, mHeight = 0, mHeight = value)
  29:      End Set
  30:  End Property 
   1:   // Auto-implemented properties
   2:  public string Name { get; set; }
   3:  public int Size { get; protected set; }     // Set default value in constructor
   4:   
   5:  // Traditional property implementation
   6:  private string name;
   7:  public string Name {
   8:    get {
   9:      return name;
  10:    }
  11:    set {
  12:      name = value;
  13:    }
  14:  }
  15:   
  16:  // Read-only property
  17:  private int powerLevel;
  18:  public int PowerLevel {
  19:    get {
  20:      return powerLevel;
  21:    }
  22:  }
  23:   
  24:  // Write-only property
  25:  private double height;
  26:  public double Height {
  27:    set {
  28:      height = value < 0 ? 0 : value;
  29:    }
  30:  } 
Java
Kotlin
Generics
   1:   ' Enforce accepted data type at compile-time
   2:  Dim numbers As New List(Of Integer)
   3:  numbers.Add(2)
   4:  numbers.Add(4)
   5:  DisplayList(Of Integer)(numbers)
   6:   
   7:  ' Subroutine can display any type of List
   8:  Sub DisplayList(Of T)(ByVal list As List(Of T))
   9:      For Each item As T In list
  10:          Console.WriteLine(item)
  11:      Next
  12:  End Sub
  13:   
  14:  ' Class works on any data type
  15:  Class SillyList(Of T)
  16:      Private list(10) As T
  17:      Private rand As New Random
  18:   
  19:      Public Sub Add(ByVal item As T)
  20:          list(rand.Next(10)) = item
  21:      End Sub
  22:   
  23:      Public Function GetItem() As T
  24:          Return list(rand.Next(10))
  25:      End Function
  26:  End Class
  27:   
  28:  ' Limit T to only types that implement IComparable
  29:  Function Maximum(Of T As IComparable)(ByVal ParamArray items As T()) As T
  30:      Dim max As T = items(0)
  31:      For Each item As T In items
  32:          If item.CompareTo(max) > 0 Then max = item
  33:      Next
  34:      Return max
  35:  End Function
   1:   // Enforce accepted data type at compile-time
   2:  List<int> numbers = new List<int>();
   3:  numbers.Add(2);
   4:  numbers.Add(4);
   5:  DisplayList<int>(numbers);
   6:   
   7:  // Function can display any type of List
   8:  void DisplayList<T>(List<T> list) {
   9:      foreach (T item in list)
  10:          Console.WriteLine(item);
  11:  }
  12:   
  13:  // Class works on any data type
  14:  class SillyList<T> {
  15:      private T[] list = new T[10];
  16:      private Random rand = new Random();
  17:   
  18:      public void Add(T item) {
  19:          list[rand.Next(10)] = item;
  20:      }
  21:   
  22:      public T GetItem() {
  23:          return list[rand.Next(10)];
  24:      }
  25:  }
  26:   
  27:  // Limit T to only types that implement IComparable
  28:  T Maximum<T>(params T[] items) where T : IComparable<T> {
  29:      T max = items[0];
  30:      foreach (T item in items)
  31:          if (item.CompareTo(max) > 0)
  32:              max = item;
  33:      return max;
  34:  }
Java
Kotlin
Events
   1:  Delegate Sub MsgArrivedEventHandler(ByVal message As String)
   2:   
   3:  Event MsgArrivedEvent As MsgArrivedEventHandler
   4:   
   5:  ' or to define an event which declares a delegate implicitly
   6:  Event MsgArrivedEvent(ByVal message As String)
   7:   
   8:  AddHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback
   9:  ' Won't throw an exception if obj is Nothing
  10:  RaiseEvent MsgArrivedEvent("Test message")
  11:  RemoveHandler MsgArrivedEvent, AddressOf My_MsgArrivedCallback
  12:   
  13:  Imports System.Windows.Forms
  14:   
  15:  Dim WithEvents MyButton As Button   ' WithEvents can't be used on local variable
  16:  MyButton = New Button
  17:   
  18:  Sub MyButton_Click(ByVal sender As System.Object, _
  19:    ByVal e As System.EventArgs) Handles MyButton.Click
  20:    MessageBox.Show(Me, "Button was clicked", "Info", _
  21:      MessageBoxButtons.OK, MessageBoxIcon.Information)
  22:  End Sub
   1:  delegate void MsgArrivedEventHandler(string message);
   2:   
   3:  event MsgArrivedEventHandler MsgArrivedEvent;
   4:   
   5:  // Delegates must be used with events in C#
   6:   
   7:   
   8:  MsgArrivedEvent += new MsgArrivedEventHandler(My_MsgArrivedEventCallback);
   9:  MsgArrivedEvent("Test message");    // Throws exception if obj is null
  10:  MsgArrivedEvent -= new MsgArrivedEventHandler(My_MsgArrivedEventCallback);
  11:   
  12:   
  13:   
  14:  using System.Windows.Forms;
  15:   
  16:  Button MyButton = new Button(); 
  17:  MyButton.Click += new System.EventHandler(MyButton_Click);
  18:   
  19:  void MyButton_Click(object sender, System.EventArgs e) {
  20:    MessageBox.Show(this, "Button was clicked", "Info",
  21:      MessageBoxButtons.OK, MessageBoxIcon.Information);
  22:  }
Java
Kotlin
Delegates & Lambda Expressions
   1:   Delegate Sub HelloDelegate(ByVal s As String)
   2:   
   3:  Sub SayHello(ByVal s As String)
   4:    Console.WriteLine("Hello, " & s)
   5:  End Sub
   6:  ' Create delegate that calls SayHello
   7:  Dim hello As HelloDelegate = AddressOf SayHello
   8:  hello("World")   ' Or hello.Invoke("World")
   9:   
  10:  ' Use lambda expression (anonymous method) instead of a delegate
  11:  Dim hello2 = Sub(x) Console.WriteLine("Hello, " & x)
  12:  hello2("World")
  13:   
  14:   
  15:   
  16:   
  17:   
  18:   
  19:  ' Use Func(Of T, TResult) delegate to call Uppercase
  20:  Dim convert As Func(Of String, String) = AddressOf Uppercase
  21:  Console.WriteLine(convert("test"))
  22:   
  23:  Function Uppercase(s As String) As String
  24:    Return s.ToUpper
  25:  End Function
  26:   
  27:  ' Declare and invoke lambda expression
  28:  Console.WriteLine((Function(num As Integer) num + 1)(2))
  29:   
  30:  ' Pass lambda expression as an argument
  31:  TestValues(Function(x, y) x Mod y = 0)
  32:   
  33:  Sub TestValues(ByVal f As Func(Of Integer, Integer, Boolean))
  34:    If f(8, 4) Then
  35:      Console.WriteLine("true")
  36:    Else
  37:      Console.WriteLine("false")
  38:    End If
  39:  End Sub 
   1:   delegate void HelloDelegate(string s);
   2:   
   3:  void SayHello(string s) {
   4:    Console.WriteLine("Hello, " + s);
   5:  }
   6:   
   7:  // C# 1.0 delegate syntax with named method
   8:  HelloDelegate hello = new HelloDelegate(SayHello);
   9:  hello("World");   // Or hello.Invoke("World");
  10:   
  11:  // C# 2.0 delegate syntax with anonymous method
  12:  HelloDelegate hello2 = delegate(string s) {
  13:    Console.WriteLine("Hello, " + s);
  14:  };
  15:  hello2("World");
  16:   
  17:  // C# 3.0 delegate syntax with lambda expression
  18:  HelloDelegate hello3 = s => { Console.WriteLine("Hello, " + s); };
  19:  hello3("World");
  20:   
  21:  // Use Func<in T, out TResult> delegate to call Uppercase
  22:  Func<string, string> convert = Uppercase;
  23:  Console.WriteLine(convert("test"));
  24:   
  25:  string Uppercase(string s) {
  26:    return s.ToUpper();
  27:  }
  28:   
  29:  // Declare and invoke Func using a lambda expression
  30:  Console.WriteLine(new Func<int, int>(num => num + 1)(2));
  31:   
  32:  // Pass lamba expression as an argument
  33:  TestValues((x, y) => x % y == 0);
  34:   
  35:  void TestValues(Func<int, int, bool> f) {
  36:    if (f(8, 4))
  37:      Console.WriteLine("true");
  38:    else
  39:      Console.WriteLine("false");
  40:  } 
Java
Kotlin
Extension Methods
   1:   Imports System.Runtime.CompilerServices
   2:   
   3:  Module StringExtensions
   4:    <Extension()>
   5:    Public Function VowelCount(ByVal s As String) As Integer
   6:      Return s.Count(Function(c) "aeiou".Contains(Char.ToLower(c)))
   7:    End Function
   8:  End Module
   9:   
  10:  ' Using the extension method
  11:  Console.WriteLine("This is a test".VowelCount) 
   1:   public static class StringExtensions {
   2:    public static int VowelCount(this string s) {
   3:      return s.Count(c => "aeiou".Contains(Char.ToLower(c)));
   4:    }
   5:  }
   6:   
   7:   
   8:   
   9:  // Using the extension method
  10:  Console.WriteLine("This is a test".VowelCount()); 
Java
Kotlin
LINQ
   1:  Dim nums() As Integer = {5, 8, 2, 1, 6}
   2:   
   3:  ' Get all numbers in the array above 4
   4:  Dim results = From n In nums
   5:                    Where n > 4
   6:                    Select n
   7:   
   8:  ' Same thing using lamba expression
   9:  results = nums.Where(Function(n) n > 4)
  10:   
  11:  ' Displays 5 8 6
  12:  For Each n As Integer In results
  13:      Console.Write(n & " ")
  14:  Next
  15:   
  16:  Console.WriteLine(results.Count())     ' 3
  17:  Console.WriteLine(results.First())     ' 5
  18:  Console.WriteLine(results.Last())     ' 6
  19:  Console.WriteLine(results.Average())     ' 6.33333
  20:   
  21:  results = results.Intersect({5, 6, 7})     ' 5 6
  22:  results = results.Concat({5, 1, 5})     ' 5 6 5 1 5
  23:  results = results.Distinct()     ' 5 6 1
  24:   
  25:  Dim Students() As Student = {
  26:      New Student With {.Name = "Bob", .Gpa = 3.5},
  27:      New Student With {.Name = "Sue", .Gpa = 4.0},
  28:      New Student With {.Name = "Joe", .Gpa = 1.9}
  29:  }
  30:   
  31:  ' Get a list of students ordered by Gpa with Gpa >= 3.0
  32:  Dim goodStudents = From s In Students
  33:              Where s.Gpa >= 3.0
  34:              Order By s.Gpa Descending
  35:              Select s
  36:   
  37:  Console.WriteLine(goodStudents.First.Name)     ' Sue
   1:  int[] nums = { 5, 8, 2, 1, 6 };
   2:   
   3:  // Get all numbers in the array above 4
   4:  var results = from n in nums
   5:                  where n > 4
   6:                  select n;
   7:   
   8:  // Same thing using lamba expression
   9:  results = nums.Where(n => n > 4);
  10:   
  11:  // Displays 5 8 6
  12:  foreach (int n in results)
  13:      Console.Write(n + " ");
  14:   
  15:   
  16:  Console.WriteLine(results.Count());     // 3
  17:  Console.WriteLine(results.First());     // 5
  18:  Console.WriteLine(results.Last());     // 6
  19:  Console.WriteLine(results.Average());     // 6.33333
  20:   
  21:  results = results.Intersect(new[] {5, 6, 7});     // 5 6
  22:  results = results.Concat(new[] {5, 1, 5});     // 5 6 5 1 5
  23:  results = results.Distinct();     // 5 6 1
  24:   
  25:  Student[] Students = {
  26:      new Student{ Name = "Bob", Gpa = 3.5 },
  27:      new Student{ Name = "Sue", Gpa = 4.0 },
  28:      new Student{ Name = "Joe", Gpa = 1.9 }
  29:  };
  30:   
  31:  // Get a list of students ordered by Gpa with Gpa >= 3.0
  32:  var goodStudents = from s in Students
  33:              where s.Gpa >= 3.0
  34:              orderby s.Gpa descending
  35:              select s;
  36:   
  37:  Console.WriteLine(goodStudents.First().Name);     // Sue
Java
Kotlin
Razor syntax (Special ASP.NET tags)
   1:  'Implicit expression    
   2:  @name Hello, <b>@name.</b> 
   3:   
   4:  'Explicit expression    
   5:  @(5+5) Hello, @name. Your age is: <b>@(5+5).</b> 
   6:   
   7:  'Unencoded expression    
   8:  @Html.Raw(name) Hello, <b>@Html.Raw(name).</b> 
   9:   
  10:  'Multi-statement code blocks    
  11:  @Code
  12:          /* VB.NET Code goes here */
  13:  End Code 
  14:  @Code
  15:      Dim greeting = "Hello, world!"
  16:      For i = 1 To 3
  17:          @<p>@greeting (@i)</p>
  18:          Next i
  19:  End Code
  20:   
  21:  'Plain text inside a code block    
  22:  @Code
  23:      @:Plain text goes here
  24:  End Code 
  25:  @If IsPost Then
  26:      Dim text = "Code goes here..."
  27:      @:Plain text goes here...
  28:  End If
  29:   
  30:  'Plain text inside a code block (alternative)    
  31:  @<text>Plain text goes here...</text> 
  32:  @If IsPost Then
  33:      Dim text = "Code goes here..."
  34:      @<text>Plain text goes here...</text>
  35:  End If 
  36:   
  37:  'Server-side comment    
  38:  @*
  39:      Here's a Razor server-side comment
  40:      It won't be rendered to the browser
  41:      It can span multiple lines
  42:  *@
  43:   
  44:  'Conditional attribute (New in MVC 4)    
  45:  <div style="@divStyle">Hello, world!</div> 
  46:  @Code
  47:      Dim divStyle As String
  48:      If Request.QueryString("style") IsNot Nothing Then
  49:          divStyle = "background-color: yellow;"
  50:      End If
  51:  End Code
  52:  <div style="@divStyle">Hello, world!</div> 
   1:  //Implicit expression    
   2:  @name Hello, <b>@name.</b> 
   3:   
   4:  //Explicit expression    
   5:  @(5+5) Hello, @name. Your age is: <b>@(5+5).</b> 
   6:   
   7:  //Unencoded expression    
   8:  @Html.Raw(name) Hello, <b>@Html.Raw(name).</b> 
   9:   
  10:  //Multi-statement code blocks    
  11:  @{
  12:          /* C# Code goes here */
  13:  } 
  14:  @{
  15:      var greeting = "Hello, world!";
  16:      for(int i = 1; i <= 3; i++)
  17:      {
  18:          <p>@greeting (@i)</p>
  19:      }
  20:  }
  21:   
  22:  //Plain text inside a code block    
  23:  @:Plain text goes here... 
  24:  @if(isTrue)
  25:  {
  26:      var text = "Code goes here...";
  27:      @:Plain text goes here...
  28:  } 
  29:   
  30:  //Plain text inside a code block (alternative)    
  31:  <text>Plain text goes here...</text> 
  32:  @if(isTrue)
  33:  {
  34:      var text = "Code goes here...";
  35:      <text>Plain text goes here...</text>
  36:  } 
  37:   
  38:  //Server-side comment
  39:  @*
  40:      Here's a Razor server-side comment
  41:      It won't be rendered to the browser
  42:      It can span multiple lines
  43:  *@ 
  44:   
  45:  //Conditional attribute (New in MVC 4)     
  46:  <div style="@divStyle">Hello, world!</div>
  47:  @{
  48:      string divStyle = null;
  49:      if(Request.QueryString["style"] != null)
  50:      {
  51:          divStyle = "background-color: yellow;";
  52:      }
  53:  }
  54:  <div style="@divStyle">Hello, world!</div>
Java
Kotlin


Comments ( )
Link to this page: //www.vb-net.com/KotlinSyntax/Index.htm
< THANKS ME>