Вы находитесь на странице: 1из 45

Java vs C#

Getting started code

Java
Java is a strongly-typed objectoriented language developed by SUN. class Hello { public static void main(String[] args) { System.out.println("hello , world"); } } //you must save the file with .java extension //from command line to compile it >javac Hello.java //generate a Hello.class file and run it >java Hello hello, world

C#
C# is a strongly-typed object-oriented language developed by Microsoft. class Hello { static void Main() { System.Console.WriteLine("hell o, world"); } } //by convention, save the file with .cs extension //from command line to compile it >csc Hello.cs //generate a Hello.exe file and run it >Hello hello, world

Java vs C#
Keywords & Reserved Words

Java
52 abstract package boolean private break do if synchronized double implements this else import 77 abstract bool byte char class

C#
as break case checked const base catch continue

protected byte public case return catch short char static class strictfp const super continue switch default

throw extends throws false transient final true finally try float void for volatile goto while assert

instanceof int interface long native new null

C# doesn't have assert boolean extends final implements instanceof native package strictfp super synchronized throws trainsient

decimal delegate else event false fixed foreach if int internal long new operator override protected readonly sbyte short static struct throw try ulong unsafe virtual volatile Java doesn't as checked delegate explicit fixed int is object out readonly sbyte stackalloc struct ulong unsafe virtual

default do enum explicit finally float goto implicit interface is namespace null out params public ref sealed sizeof string switch true typeof unchecked ushort void while have base decimal enum extern foreach internal lock operator override ref sealed string typeof unchecked ushort

double extern for in lock object private return stackalloc this uint using

bool event implicit namespace params sizeof uint using

Java vs C#
Types

Java
type: primitive types reference types numeric-type: integral types floating-point types integral-type: byte short int long char

C#
type: value types reference types numeric-type: integral types floating-point types decimal integral-type: sbyte byte short ushort int uint long ulong char floating-point-type: float double reference-type: class types interface types array types delegate types Predefined types or system-provided types: object string sbyte short int long byte ushort uint ulong float double bool char decimal NOTE: value types include simple types, enum types and struct types.

floating-point-type: float double reference-type: class types interface types array types Primitive types(8) boolean byte char short int long float double

Java vs C#
Access Modifiers

Java
public Access not limited protected Access limited to the package or subclass in a different package (no access modifier) Access limited to the package private Access limited to the containing type

C#
public Access not limited protected Access limited to the containing class or types derived from the containing class protected internal Access limited to this program or types derived from the containing class (no access modifier) by default it is private internal Access limited to this program private Access limited to the containing type

Application Startup

Java
Only one: One of public static void main(String[] args) static {...} static {...} static static {...}

C#
these: void Main() {...} void Main(string[] args) int Main() {...} int Main(string[] args)

Array Type

Java
int [,,] array = new int [3, 4, 5];//illegal int [1,1,1] = 5;//illegal int [][][] array = new int [3] [4][5]; // ok int [1][1][1] = 5; class Test { public static void main(String[] args) { int[] a1; // single-dimensional array of int int[][] a2; // 2dimensional array of int int[][][] a3; // 3dimensional array of int int[][] j2; // "jagged" array: array of (array of int) int[][][] j3; // array of (array of (array of int)) } }

C#
int [,,] array = new int [3, 4, 5]; // creates 1 array int [1,1,1] = 5; int [][][] array = new int [3][4] [5]; // creates 1+3+12=16 arrays int [1][1][1] = 5; class Test { static void Main() { int[] a1; // singledimensional array of int int[,] a2; // 2-dimensional array of int int[,,] a3; // 3-dimensional array of int int[][] j2; // "jagged" array: array of (array of int) int[][][] j3; // array of (array of (array of int)) } } class Test { static void Main() { int[] a1 = new int[] {1, 2, 3}; int[,] a2 = new int[,] {{1, 2, 3}, {4, 5, 6}}; int[,,] a3 = new int[10, 20, 30]; int[][] j2 = new int[3][]; j2[0] = new int[] {1, 2, 3}; j2[1] = new int[] {1, 2, 3, 4, 5, 6}; j2[2] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; } }

class Test { public static void main(String[] args) { int[] a1 = new int[] {1, 2, 3}; int[][] a2 = new int[][] {{1, 2, 3}, {4, 5, 6}}; int[][][] a3 = new int[10][20][30]; int[][] j2 = new int[3] []; j2[0] = new int[] {1, 2, 3}; j2[1] = new int[] {1, 2, 3, 4, 5, 6}; j2[2] = new int[] {1, 2, class Test 3, 4, 5, 6, 7, 8, 9}; { } static void Main() { } int[] arr = new int[5]; for (int i = 0; i < class Test arr.Length; i++) { arr[i] = i * i; public static void for (int i = 0; i < main(String[] args) { arr.Length; i++)

int[] arr = new int[5]; for (int i = 0; i < arr.length; i++) arr[i] = i * i; for (int i = 0; i < arr.length; i++) System.out.println(" arr[" + i + "] = " + arr[i]); } }

Console.WriteLine("arr[{0} ] = {1}", i, arr[i]); } }

int[][] jag = new int[][] {new int[] {1, 2, 3, 4}, new int[] {5, 6, 7, 8, 9, 10}}; for (int i = 0; i < jag.Length; i++) for (int j = 0; j < jag[i].Length; j++) int[][] jag = new int[][] {new System.Console.WriteLine(jag[ int[] {1, 2, 3, 4}, new int[] i][j]); {5, 6, 7, 8, 9, 10}}; or //access elements for (int i = 0; i < jag.GetLength(0); for (int i = 0; i < jag.length; i++) i++) for (int j = 0; j < for (int j = 0; j < jag[i].GetLength(0); j++) jag[i].length; j++) System.Console.WriteLine(jag[ System.out.println(jag[ i][j]); i][j]);

Conditional Statement

Java
if/else switch :? if statement public static void main(String[] args) { if (args.length == 0) System.out.println("No args"); else System.out.println("Args") ; } if/else switch :?

C#

if statement static void Main(string[] args) { if (args.Length == 0) Console.WriteLine("No args"); else Console.WriteLine("Args"); }

if (myInt < 0 || myInt == 0) { Console.WriteLine("Your number {0} if (myInt < 0 || myInt == 0) is less than or equal to zero.", { myInt); System.out.println("Your number } "+myInt+" is less than or equal to else if (myInt > 0 && myInt <= 10) zero."); {

} else if (myInt > 0 && myInt <= 10) { System.out.println("Your number "+myInt+" is between 1 and 10."); } else if (myInt > 10 && myInt <= 20) { System.out.println("Your number "+myInt+" is between 11 and 20."); } else if (myInt > 20 && myInt <= 30) { System.out.println("Your number "+myInt+" is between 21 and 30."); } else { System.out.println("Your number "+myInt+" is greater than 30."); }

Console.WriteLine("Your number {0} is between 1 and 10.", myInt); } else if (myInt > 10 && myInt <= 20) { Console.WriteLine("Your number {0} is between 11 and 20.", myInt); } else if (myInt > 20 && myInt <= 30) { Console.WriteLine("Your number {0} is between 21 and 30.", myInt); } else { Console.WriteLine("Your number {0} is greater than 30.", myInt); }

switch statement static void Main(string[] args) { switch (args.Length) { case 0: Console.WriteLine("No switch statement args"); public static void main(String[] break; args) { case 1: switch (args.length) { Console.WriteLine("One case 0: arg "); System.out.println("No break; args"); default: break; int n = args.Length; case 1: Console.WriteLine("{0} System.out.println("On args", n); e arg "); break; break; } default: } int n = args.length; System.out.println(n + switch (myInt) " args"); { break; case 1: } case 2: } case 3: Console.WriteLine("Your number switch (myInt) is {0}.", myInt); { break; case 1: default: case 2: Console.WriteLine("Your number case 3: {0} is not between 1 and 3.", myInt); System.out.println("Your break; number is "+ myInt); } break; default: void DoCommand(string command) { System.out.println("Your switch (command.ToLower()) { number "+myInt+" is not between 1 case "run": and 3.");

break;

String[] selection= {"run","save","quit"}; void DoCommand(int idx) { switch (idx) { case 0: DoRun(); break; case 1: DoSave(); break; case 2: DoQuit(); break; default: InvalidCommand(idx); break; } } int a = 5; System.out.print(a==5 ? "A is 5" : "A is not 5"); prints: A is 5

DoRun(); break; case "save": DoSave(); break; case "quit": DoQuit(); break; default: InvalidCommand(command); break; }

int a = 5; System.Console.WriteLine(a==5 ? "A is 5" : "A is not 5"); prints: A is 5

Constructor

Java
constructor-modifier: public protected private

C#
constructor-modifier: public protected internal private extern static constructor-initializer: : base(argument-list) : this(argument-list) using System; class A { public A() { PrintFields(); }

constructor-initializer: super(argument-listopt) this(argument-listopt) class A { public A() { PrintFields(); } public void PrintFields() {}

} class B extends A { int x = 1; int y; public B() { y = -1; } public void PrintFields() { System.out.println("x = "+x+" y = "+y); } } class Test { public static void main(String[] args) { B b = new B(); } } output: x = 0 y = 0 import java.util.ArrayList; class A { int x = 1, y = -1, count; public A() { count = 0; } public A(int n) { count = n; } } class B extends A { double sqrt2 = Math.sqrt(2.0); ArrayList items = new ArrayList(100); int max; public B() { this(100); items.add("default"); } public B(int n) { super(n - 1); max = n; } } java doesn't have static constructor but has a static block. class Test {

public virtual void PrintFields() {} } class B: A { int x = 1; int y; public B() { y = -1; } public override void PrintFields() { Console.WriteLine("x = {0}, y = {1}", x, y); } } class T { static void Main() { B b = new B(); } } output: x = 1, y = 0 using System.Collections; class A { int x = 1, y = -1, count; public A() { count = 0; } public A(int n) { count = n; } } class B: A { double sqrt2 = Math.Sqrt(2.0); ArrayList items = new ArrayList(100); int max; public B(): this(100) { items.Add("default"); } public B(int n): base(n - 1) { max = n; } }

static constructor using System; class Test {

public static void main(String[] args) { A.F(); B.F(); } } class A { static { System.out.println("Init A"); } public static void F() { System.out.println("A.F"); } } class B { static { System.out.println("Init B"); } public static void F() { System.out.println("B.F"); } } output: Init A A.F Init B B.F constructor circular dependency class A { public static int X; static { X = B.Y + 1;} } class B { public static int Y = A.X + 1; static {} public static void main(String[] args) { System.out.println("X = "+A.X+", Y = "+B.Y); } } output: X = 1, Y = 2

static void Main() { A.F(); B.F(); } } class A { static A() { Console.WriteLine("Init A"); } public static void F() { Console.WriteLine("A.F"); } } class B { static B() { Console.WriteLine("Init B"); } public static void F() { Console.WriteLine("B.F"); } } output: Init A A.F Init B B.F constructor circular dependency using System; class A { public static int X; static A() { X = B.Y + 1;} } class B { public static int Y = A.X + 1; static B() {} static void Main() { Console.WriteLine("X = {0}, Y = {1}", A.X, B.Y); } } output: X = 1, Y = 2

default Modifier

Java
class A { int x; static void F(B b.x = 1; } } class B extends A { static void F(B b.x = 1; } } class A {...} public class B { A F() {...} A G() {...} public A H() {...}//ok } class A { int x; static void F(B b.x = 1; } } class B: A { static void F(B b.x = 1; // } }

C#

b) { // Ok

b) { // Ok

b) { // Ok

b) { Error, x not accessible

class A {...} public class B { A F() {...} internal A G() {...} public A H() {...}//error } the H method in B results in a compile-time error because the return type A is not at least as accessible as the method.

Documentation

Java
single-linecomment: // inputcharactersopt multiple-linecomment: /* .... */ single-line-comment: // input-characters multiple-line-comment: /* .... */ /// documetation */ XML format

C#

/** documentation */ namespace Graphics javadoc format { /// <remarks>Class <c>Point</c> models a point in a

an example you may need html format not xml format. package Graphics; /** Class Point models a point in a two-dimensional plane. */ public class Point { /** Instance variable x represents the point's xcoordinate. */ private int X; /** Instance variable y represents the point's ycoordinate. */ private int Y; /** Property X represents the point's xcoordinate. */ public int getX() {return X; } public void setX(int value) { X = value; } /** Property Y represents the point's ycoordinate.

two-dimensional plane. /// </remarks> public class Point { /// <summary>Instance variable <c>x</c> represents the point's /// x-coordinate.</summary> private int x; /// <summary>Instance variable <c>y</c> represents the point's /// y-coordinate.</summary> private int y; /// <value>Property <c>X</c> represents the point's x-coordinate.</value> public int X { get { return x; } set { x = value; } } /// <value>Property <c>Y</c> represents the point's y-coordinate.</value> public int Y { get { return y; } set { y = value; } } /// <summary>This constructor initializes the new Point to /// (0,0).</summary> public Point() : this(0,0) {} /// <summary>This constructor initializes the new Point to /// (<paramref name="xor"/>,<paramref name="yor"/>).</summary> /// <param><c>xor</c> is the new Point's xcoordinate.</param> /// <param><c>yor</c> is the new Point's ycoordinate.</param> public Point(int xor, int yor) { X = xor; Y = yor; }

*/ /// <summary>This method changes the point's public int location to getY() { /// the given coordinates.</summary> return Y; /// <param><c>xor</c> is the new x} coordinate.</param> public void /// <param><c>yor</c> is the new ysetY(int value) { coordinate.</param>

Y = value; } /** This constructor initializes the new Point to (0,0). */ public Point() { this(0,0); } /** This constructor initializes the new Point to xor, yor. <P>xor is the new Point's x-coordinate. <P>yor is the new Point's y-coordinate. */ public Point(int xor, int yor) { X = xor; Y = yor; } /** This method changes the point's location to the given coordinates. <P>xor is the new xcoordinate. <p>yor is the new ycoordinate. @see Translate */ public void Move(int xor, int yor) { X = xor; Y = yor; } /** This method changes the point's location by the given x- and y-offsets.

/// <see cref="Translate"/> public void Move(int xor, int yor) { X = xor; Y = yor; } /// <summary>This method changes the point's location by /// the given x- and y-offsets. /// <example>For example: /// <code> /// Point p = new Point(3,5); /// p.Translate(-1,3); /// </code> /// results in <c>p</c>'s having the value (2,8). /// </example> /// </summary> /// <param><c>xor</c> is the relative xoffset.</param> /// <param><c>yor</c> is the relative yoffset.</param> /// <see cref="Move"/> public void Translate(int xor, int yor) { X += xor; Y += yor; } /// <summary>This method determines whether two Points have the same /// location.</summary> /// <param><c>o</c> is the object to be compared to the current object. /// </param> /// <returns>True if the Points have the same location and they have /// the exact same type; otherwise, false.</returns> /// <seealso cref="operator=="/> /// <seealso cref="operator!="/> public override bool Equals(object o) { if (o == null) { return false; } if (this == o) { return true; } if (GetType() == o.GetType()) { Point p = (Point)o; return (X == p.X) && (Y == p.Y); } return false; } /// <summary>Report a point's location as a string.</summary> /// <returns>A string representing a point's

location, in the form (x,y), /// without any leading, training, or embedded <pre> whitespace.</returns> Point p = public override string ToString() { new Point(3,5); return "(" + X + "," + Y + ")"; p.Transla } te(-1,3); </pre> /// <summary>This operator determines whether two results Points have the same in p's having the /// location.</summary> value (2,8). /// <param><c>p1</c> is the first Point to be <p> compared.</param> <p>xor is /// <param><c>p2</c> is the second Point to be the relative xcompared.</param> offset. /// vreturns>True if the Points have the same <p>yor is location and they have the relative y/// the exact same type; otherwise, offset. false.</returns> @see Move /// <seealso cref="Equals"/> */ /// <seealso cref="operator!="/> public void public static bool operator==(Point p1, Point p2) Translate(int { xor, int yor) { if ((object)p1 == null || (object)p2 == null) X += xor; { Y += yor; return false; } } /** This method determines if (p1.GetType() == p2.GetType()) { whether two return (p1.X == p2.X) && (p1.Y == p2.Y); Points have the } same location. return false; <p>o is } the object to be compared to the /// <summary>This operator determines whether two current object. Points have the same /// location.</summary> <P> True /// <param><c>p1</c> is the first Point to be if the Points compared.</param> have the same /// <param><c>p2</c> is the second Point to be location and they compared.</param> have /// <returns>True if the Points do not have the the exact same location and the same type; /// exact same type; otherwise, otherwise, false. false.</returns> /// <seealso cref="Equals"/> */ /// <seealso cref="operator=="/> public public static bool operator!=(Point p1, Point p2) boolean { locationEquals(Ob return !(p1 == p2); ject o) { } if (o == null) { /// <summary>This is the entry point of the Point retur class testing n false; /// program. } /// <para>This program tests each method and example:

<p>For

operator, and /// is intended to be run after any non-trvial retur maintenance has n true; /// been performed on the Point } class.</para></summary> if public static void Main() { (getClass() == // class test code goes here o.getClass()) { } Point } p = (Point)o; } retur n (X == p.X) && (Y == p.Y); >csc Point.cs /doc:my.xml } <doc> return <assembly> false; <name>Point</name> } </assembly> /** Report a <members> point's location <member name="T:Graphics.Point"> as a string. <remarks>Class <c>Point</c> models a point A string in a two-dimensional representing a plane. point's location, </remarks> in the form </member> (x,y), <member name="F:Graphics.Point.x"> without <summary>Instance variable <c>x</c> any leading, represents the point's training, or x-coordinate.</summary> embedded </member> whitespace. <member name="F:Graphics.Point.y"> */ <summary>Instance variable <c>y</c> public represents the point's String toString() y-coordinate.</summary> { </member> return <member name="M:Graphics.Point.#ctor"> "(" + X + "," + Y <summary>This constructor initializes the + ")"; new Point to } (0,0).</summary> /** This </member> operator <member determines name="M:Graphics.Point.#ctor(System.Int32,System.Int32 whether two )"> Points have the <summary>This constructor initializes the same new Point to location. (<paramref name="xor"/>,<paramref <p>p1 is name="yor"/>).</summary> the first Point <param><c>xor</c> is the new Point's xto be compared. coordinate.</param> <p>p2 is <param><c>yor</c> is the new Point's ythe second Point coordinate.</param> to be compared. </member> <p>True <member if the Points name="M:Graphics.Point.Move(System.Int32,System.Int32) have the same "> location and they <summary>This method changes the point's have location to == o) {

if (this

the exact same type; otherwise, false. @see Equals */ public static boolean equals(Point p1, Point p2) { if ((Object)p1 == null || (Object)p2 == null) { retur n false; } if (p1.getClass() == p2.getClass()) { retur n (p1.X == p2.X) && (p1.Y == p2.Y); } return false; } /** This operator determines whether two Points have the same location. <p>p1 is the first Point to be compared. <p>p2 is the second Point to be compared. <p>True if the Points do not have the same location and the exact same type; otherwise, false. @see locationEquals */ public static boolean

the given coordinates.</summary> <param><c>xor</c> is the new xcoordinate.</param> <param><c>yor</c> is the new ycoordinate.</param> <see cref="M:Graphics.Point.Translate(System.Int32,System.I nt32)"/> </member> <member name="M:Graphics.Point.Translate(System.In t32,System.Int32)"> <summary>This method changes the point's location by the given x- and y-offsets. <example>For example: <code> Point p = new Point(3,5); p.Translate(-1,3); </code> results in <c>p</c>'s having the value (2,8). </example> </summary> <param><c>xor</c> is the relative xoffset.</param> <param><c>yor</c> is the relative yoffset.</param> <see cref="M:Graphics.Point.Move(System.Int32,System.Int32) "/> </member> <member name="M:Graphics.Point.Equals(System.Object)"> <summary>This method determines whether two Points have the same location.</summary> <param><c>o</c> is the object to be compared to the current object. </param> <returns>True if the Points have the same location and they have the exact same type; otherwise, false.</returns> <seealso cref="M:Graphics.Point.op_Equality(Graphics.Poin t,Graphics.Point)"/> <seealso cref="M:Graphics.Point.op_Inequality(Graphics.Po int,Graphics.Point)"/> </member> <member name="M:Graphics.Point.ToString"> <summary>Report a point's location as a string.</summary> <returns>A string representing a point's

notEquals(Point p1, Point p2) { return ! (p1 == p2); } /** This is the entry point of the Point class testing program. <p>This program tests each method and operator, and is intended to be run after any non-trvial maintenance has been performed on the Point class. */ public static void main(String[] args) { // class test code goes here } }

location, in the form (x,y), without any leading, training, or embedded whitespace.</returns> </member> <member name="M:Graphics.Point.op_Equality(Graphics.Poi nt,Graphics.Point)"> <summary>This operator determines whether two Points have the same location.</summary> <param><c>p1</c> is the first Point to be compared.</param> <param><c>p2</c> is the second Point to be compared.</param> <returns>True if the Points have the same location and they have the exact same type; otherwise, false.</returns> <seealso cref="M:Graphics.Point.Equals(System.Object)"/> <seealso cref="M:Graphics.Point.op_Inequality(Graphics.Poi nt,Graphics.Point)"/> </member> <member name="M:Graphics.Point.op_Inequality(Graphics.Po int,Graphics.Point)"> <summary>This operator determines whether two Points have the same location.</summary> <param><c>p1</c> is the first Point to be use javadoc tool compared.</param> <param><c>p2</c> is the second Point to be to generate Java API compared.</param> <returns>True if the Points do not have format the same location and the exact same type; otherwise, false.</returns> <seealso cref="M:Graphics.Point.Equals(System.Object)"/> <seealso cref="M:Graphics.Point.op_Equality(Graphics.Poin t,Graphics.Point)"/> </member> <member name="M:Graphics.Point.Main"> <summary>This is the entry point of the Point class testing program. <para>This program tests each method and operator, and is intended to be run after any non-trvial maintenance has

been performed on the Point class.</para></summary> </member> <member name="P:Graphics.Point.X"> <value>Property <c>X</c> represents the point's x-coordinate.</value> </member> <member name="P:Graphics.Point.Y"> <value>Property <c>Y</c> represents the point's y-coordinate.</value> </member> </members> </doc>

Event Handler

Java
import java.awt.event.ActionListener; public class Form1 extends java.awt.Frame implements ActionListener { java.awt.Button button1 = new Button(); public void actionPerformed(ActionEvent ae) { System.out.println("button1 was clicked!"); } button1.addActionListener(this); ... }

C#
public delegate void EventHandler(object sender, System.EventArgs e); public class Button { private EventHandler handler; public event EventHandler Click { add { handler += value; } remove { handler -= value; } } } public class Form1 { public Form1() { // Add Button1_Click as an event handler for Button1's Click event Button1.Click += new EventHandler(Button1_Click); } Button Button1 = new Button(); void Button1_Click(object sender, EventArgs e) { Console.WriteLine("Button1 was clicked!"); }

public void Disconnect() { Button1.Click -= new EventHandler(Button1_Click); } }

Exception

Java
ArithmeticException ArrayIndexOutOfBoundsException NullPointerException OutOfMemoryException ClassCastException

C#
ArithmeticException IndexOutOfRangeException NullReferenceException OutOfMemoryException InvalidCastException

final vs sealed

Java
final class Test { ... } //no subclass allowed

C#
sealed class Test { ... } //no derivation allowed

String vs string

Java
String is a reference type but immutable. for example,(Note: the Uppercalse S for String) String s1 = "hello"; String s2 = s1; s1 = "goodbye";

C#
string is a reference type but immutable. for example,(Note: the lower-case s for string) string s1 = "hello"; string s2 = s1; s1 = "goodbye";

System.out.println(s2);//hello System.Console.WriteLine(s2);//hello System.out.println(s1);//goodbye System.Console.WriteLine(s1);//goodbye string path = "C:\\My Documents\\"; There is no verbatim string in Java string path = "C:\\My Documents\\"; can be written with verbatim string like: string path = @"C:\My Documents\";

Inheritance

Java
A class can have one super class, but may implement many interfaces. class Sub extends Super implements InterA, InterB, ... //class A's super class is Object. //class A is a subclass of Object class implicitly class A { public void F() { System.out.println("A.F"); } } class B extends A { public void G() { System.out.println("B.G"); } } class Test { public static void main(String[] args) { B b = new B(); b.F(); // Inherited from A b.G(); // Introduced in B A a = b; as an A a.F();

C#
A class can have one super class, but may implement many interfaces. class Sub: Super, InterA, InterB, ... //class A's base class is object //class A is a subclass of object class implicitly class A { public void F() { Console.WriteLine("A.F"); } } class B: A { public void G() { Console.WriteLine("B.G"); } } class Test { static void Main() { B b = new B(); b.F(); // Inherited from A b.G(); // Introduced in B // Treat a

A a = b; B as an A // Treat a B a.F(); } }

class A { public virtual void F() { class A Console.WriteLine("A.F"); { } public void F() { } System.out.println("A.F"); class B: A } { } public override void F() { class B extends A base.F(); { Console.WriteLine("B.F"); public void F() { } super.F(); } System.out.println("B.F"); class Test } { } static void Main() { class Test B b = new B(); { b.F(); public static void main(String[] A a = b; args) { a.F(); B b = new B(); } b.F(); } A a = b; a.F(); } abstract class A } { public abstract void F(); } abstract class A class B: A { { public abstract void F(); public override void F() { } Console.WriteLine("B.F"); class B extends A } { } public void F() { class Test System.out.println("B.F"); { } static void Main() { } B b = new B(); class Test b.F(); { A a = b; public static void main(String[] a.F(); args) { } B b = new B(); } b.F(); A a = b; a.F(); //A popular example } public class DrawingObject } { public virtual void Draw() { //A popular example Console.WriteLine("I'm just public class DrawingObject a generic drawing object."); { } public void Draw() } { System.out.println("I'm just public class Line : DrawingObject a generic drawing object."); {

} } public class Line extends DrawingObject { public void Draw() { System.out.println("I'm a Line."); } } public class Circle extends DrawingObject { public void Draw() { System.out.println("I'm a Circle."); } } public class Square extends DrawingObject { public void Draw() { System.out.println("I'm a Square."); } } public class DrawDemo { public static void main(String[] args) { DrawingObject[] dObj = new DrawingObject[4]; dObj[0] = dObj[1] = dObj[2] = dObj[3] = DrawingObject(); new Line(); new Circle(); new Square(); new

public override void Draw() { Console.WriteLine("I'm a Line."); } } public class Circle : DrawingObject { public override void Draw() { Console.WriteLine("I'm a Circle."); } } public class Square : DrawingObject { public override void Draw() { Console.WriteLine("I'm a Square."); } } public class DrawDemo { public static int Main(string[] args) { DrawingObject[] dObj = new DrawingObject[4]; dObj[0] = dObj[1] = dObj[2] = dObj[3] = DrawingObject(); new Line(); new Circle(); new Square(); new

foreach (DrawingObject drawObj in dObj) { drawObj.Draw(); } return 0; } Output: I'm I'm I'm I'm object }

for(int i= 0; i < dObj.length; i++) { dObj[i].Draw(); } }

a Line. a Circle. a Square. just a generic drawing

Output: I'm I'm I'm I'm object

a Line. a Circle. a Square. just a generic drawing

Instance

Java
class A { int x = 1; int y = x + 1; // OK }

C#
class A { int x = 1; int y = x + 1; // Error, reference to instance member of this }

Interface

Java
interface IControl { void Paint(); } interface ITextBox extends IControl { void SetText(String text); } interface IListBox extends IControl { void SetItems(String[] items); } interface IComboBox extends

C#
interface IControl { void Paint(); } interface ITextBox: IControl { void SetText(string text); } interface IListBox: IControl { void SetItems(string[] items); } interface IComboBox: ITextBox, IListBox {} class Control {...}

ITextBox, IListBox {} class Control {...} interface IControl { void Paint(); } interface IDataBound { void Bind(Binder b); } public class EditBox extends Control implements IControl, IDataBound { public void Paint() {...} public void Bind(Binder b) {...} } interface modifiers(outer interface) public default(no modifier)

interface IControl { void Paint(); } interface IDataBound { void Bind(Binder b); } public class EditBox: Control, IControl, IDataBound { public void Paint() {...} public void Bind(Binder b) {...} } interface modifiers new public protected internal private

access interface members interface ICloneable { object Clone(); } interface IComparable { access interface members int CompareTo(object other); interface ICloneable } { class ListEntry: ICloneable, Object Clone(); IComparable } { interface IComparable object ICloneable.Clone() {...} { int IComparable.CompareTo(object int CompareTo(Object other); other) {...} } } class ListEntry implements ICloneable, IComparable { public interface ITeller public Object Clone() {...} { public int CompareTo(Object void Next (); other) {...} } } public interface IIterator { public interface ITeller void Next (); { } void Next (); } public class Clark : ITeller, IIterator { public interface IIterator void ITeller.Next () { { } void Next (); void IIterator.Next () { }

} public class Clark implements } ITeller, IIterator Clark clark = new Clark (); { ((ITeller)clark).Next(); void ITeller.Next () {//error } void IIterator.Next () {//error } } (lack of flexibility and easy to be conflicted) code one: void Next() {}//ok

internal Modifier

Java
public class A { public static int X; static int Y; private static int Z; } class B { public static int X; static int Y; private static int Z; public class C { public static int X; static int Y; private static int Z; } private class D { public static int X; static int Y; private static int Z; } }

C#
public class A { public static int X; internal static int Y; private static int Z; } internal class B { public static int X; internal static int Y; private static int Z; public class C { public static int X; internal static int Y; private static int Z; } private class D { public static int X; internal static int Y; private static int Z; } }

Library & Package

Java
// HelloLibrary.java package Microsoft.CSharp.Introduction; { public class HelloLibrary { public String getMessage() { return "hello, world"; } } } >javac -d HelloLibrary.java The above command produces a HelloLibrary.class file stored at Microsoft\CSharp\Introduction\ subdirectory // HelloApp.java import Microsoft.CSharp.Introduction; class HelloApp { public static void main(String[] args) { HelloLibrary m = new HelloLibrary(); System.out.println(m.getMes sage()); } } >javac HelloApp.java >java HelloApp hello, world

C#
// HelloLibrary.cs namespace Microsoft.CSharp.Introduction { public class HelloMessage { public string Message { get { return "hello, world"; } } } } >csc /target:library HelloLibrary.cs The above command produces a class library HelloLibrary.dll // HelloApp.cs using Microsoft.CSharp.Introduction; class HelloApp { static void Main() { HelloMessage m = new HelloMessage(); System.Console.WriteLine(m.M essage); } } >csc /reference:HelloLibrary.dll HelloApp.cs //The above command produces an application HelloApp.exe file When executed, printout: hello, world

Loop Constructs

Java

C#

while do-while for

while do-while for foreach

while statement while statement public static void main(String[] static void Main(string[] args) { args) { int i = 0; int i = 0; while (i < args.Length) { while (i < args.length) { Console.WriteLine(args[i]); System.out.println(args[i]); i++; i++; } } } } do statement do statement static void Main() { static void main() { int i; int i; do { do { i++; i++; }while (i != 5); } while (i != 5); } } for statement for statement static void Main(string[] args) { static void main(String[] args) { for (int i = 0; i < for (int i = 0; i < args.length; args.Length; i++) i++) Console.WriteLine(args[i]); System.out.println(args[i]); } } foreach statement//short hand for Java has no foreach statement for statement All foreach statements can be static void Main(string[] args) { replaced with for statements foreach (string s in args) Console.WriteLine(s); } break statement public static void main(String[] args) { int i = 0; while (true) { if (i == args.length) break; System.out.println(args[i+ +]); } } continue statement public static void main(String[] args) { int i = 0; while (true) { System.out.println(args[i+ +]); break statement static void Main(string[] args) { int i = 0; while (true) { if (i == args.Length) break; Console.WriteLine(args[i+ +]); } } continue statement static void Main(string[] args) { int i = 0; while (true) { Console.WriteLine(args[i+ +]); if (i < args.Length) continue;

} }

if (i < args.length) continue; break;

} }

break;

class Test { class Test static void Main() { { double[,] values = public static void main(String[] { {1.2, 2.3, 3.4, 4.5}, args) { {5. double[][] values = {{1.2, 6, 6.7, 7.8, 8.9} }; 2.3, 3.4, 4.5}, foreach (double {5.6, elementValue in values) 6.7, 7.8, 8.9} }; Console.Write("{0} ", for(int i = 0; i < elementValue); values.length; i++) Console.WriteLine(); for(int j = 0; j < } values[0].length; j++) } System.out.print(valu print: 1.2 2.3 3.4 4.5 5.6 6.7 7.8 es[i][j]+" "); 8.9 } } class Test print: 1.2 2.3 3.4 4.5 5.6 6.7 7.8 { 8.9 static void Main(string[] args) { class Test string[,] table = {{"red", { "blue", "green"}, public static void main(String[] {"Monday args) { ", "Wednesday", "Friday"} }; String[][] table = {{"red", foreach (string str in "blue", "green"}, args) { {"Monday", int row, colm; "Wednesday", "Friday"} }; for (row = 0; row <= 1; done: ++row) { for(int i = 0; i < for (colm = 0; colm args.length; i++) { <= 2; ++colm) { String str = args[i]; if (str == int row, colm; table[row,colm]) { for (row = 0; row <= 1; goto done; ++row) { } for (colm = 0; colm } <= 2; ++colm) { } if (str == Console.WriteLine("{0} table[row][colm]) { not found", str); System.out.pr continue; intln("Found "+str+ done: " at Console.WriteLine("Foun ["+row+"]["+colm+"]"); d {0} at [{1}][{2}]", break str, done;//java goto out of date row, colm); } } } } } } System.out.println(str >Test green +" not found"); Found green at [0][2] } >Test Sunday

} } >java Test green Found green at [0][2] >java Test Sunday Sunday not found

Sunday not found

Method Modifiers

Java
public protected no modifier private static final abstract native synchronized strictfp

C#
public protected internal private static sealed abstract extern virtual override new

Operators

Java
{ } [ ] ( ) . , : ; + * / % & | ^ ! ~ = < > ? ++ -&& || << >> == != <= >= += -= *= /= %= &= |= ^= <<= >>= >>> Java doesn't have operator -> Pre-processing directives None

C#
{ } [ ] ( ) . , : + * / % ^ ! ~ = < > ? ++ || << >> == != <= >= += *= /= %= &= |= ^= <<= >>= -> C# doesn't have operator Pre-processing directives # ; & --= >>>

| &&

Out Parameters

Java
Java doesn't have out parameters. You can achieve C#'s functionality by wrapping a primitive to a class, or using an array to hold multiple returned values, and then call back that value via pass by reference. class Test { static void divide(int a, int b, int result, int remainder) { result = a / b; remainder = a % b; System.out.println(a +"/"+ b + " = "+ result + " r " + remainder); } public static void main(String[] args) { for (int i = 1; i < 10; i+ +) for (int j = 1; j < 10; j++) { int ans = 0, r = 0; divide(i, j, ans, r); } } } class Test { static void SplitPath(String path, String dir, String name) { int i = path.length(); while (i > 0) { char ch = path.charAt(i-1); if (ch == '\\' || ch == '/' || ch == ':') break; i--; } dir = path.substring(0, i); name = path.substring(i); System.out.println(dir);

C#
C# provides the out keyword, which indicates that you may pass in uninitialized variables and they will be passed by reference. Note the calling method should mark out keyword either. class Test { static void Divide(int a, int b, out int result, out int remainder) { result = a / b; remainder = a % b; } static void Main() { for (int i = 1; i < 10; i+ +) for (int j = 1; j < 10; j++) { int ans, r; Divide(i, j, out ans, out r); Console.WriteLine(" {0} / {1} = {2}r{3}", i, j, ans, r); } } } using System; class Test { static void SplitPath(string path, out string dir, out string name) { int i = path.Length; while (i > 0) { char ch = path[i - 1]; if (ch == '\\' || ch == '/' || ch == ':') break; i--; } dir = path.Substring(0, i);

System.out.println(name); name = path.Substring(i); } } public static void static void Main() { main(String[] args) { string dir, name;//like a String dir="", name =""; place holder SplitPath("c:\\Windows\\Sys SplitPath("c:\\Windows\\Sys tem\\hello.txt", dir, name); tem\\hello.txt", out dir, out } name); } Console.WriteLine(dir);//ca ll back prints: Console.WriteLine(name); c:\Windows\System\ } hello.txt } prints: c:\Windows\System\ Thanks for Peter's suggestion. He suggests to hello.txt

use an array as one of possible solutions in Java to replace out parameter feature in C#.

Override

Java
class A { public void F() { System.out.println("A.F"); } public void G() { System.out.println("A.G"); } } class B extends A { public void F() { System.out.println("B.F"); } public void G() { System.out.println("B.G"); } } class Test { public static void main(String[] args) { B b = new B(); A a = b;

C#
using System; class A { public void F() { Console.WriteLine("A.F"); } public virtual void G() { Console.WriteLine("A.G"); } } class B: A { new public void F() { Console.WriteLine("B.F"); } public override void G() { Console.WriteLine("B.G"); } } class Test { static void Main() { B b = new B(); A a = b;

a.F(); b.F(); a.G(); b.G(); } }

a.F(); b.F(); a.G(); b.G(); } } the output: A.F B.F B.G B.G using System; class A { public virtual void F() { Console.WriteLine("A.F"); } } class B: A { public override void F() { Console.WriteLine("B.F"); } } class C: B { new public virtual void F() { Console.WriteLine("C.F"); } } class D: C { public override void F() { Console.WriteLine("D.F"); } } class Test { static void Main() { D d = new D(); A a = d; B b = d; C c = d; a.F(); b.F(); c.F(); d.F(); } } the output: B.F B.F D.F D.F

the output: B.F B.F B.G B.G class A { public void F() { System.out.println("A.F"); } } class B extends A { public void F() { System.out.println("B.F"); } } class C extends B { public void F() { System.out.println("C.F"); } } class D extends C { public void F() { System.out.println("D.F"); } } class Test { public static void main(String[] args) { D d = new D(); A a = new B(); B b = new B(); C c = d; a.F(); b.F(); c.F(); d.F(); } } the output: B.F B.F D.F

D.F override modifier You cannot override private class A { public void F() } class B extends A { public void F() private } class C extends B { public void F() } You can hide B.F by runtime type to be more

{}

{}//cannot be

override modifier class A { public virtual void F() {} } class B: A { new private void F() {} // Hides A.F within B } class C: B { public override void F() {} // Ok, overrides A.F }

{} controlling

Parameter Array

Java
Java doesn't have such feature. public class Test { public static void main (String[] args) { System.out.println(add (new int[] {1,2,3,4})); } public static int add (int[] array) { int sum = 0; for(int i = 0; i < array.length; i++) sum += array[i]; return sum; } } prints: 10 class Test

C#
The params modifier may be added to the last parameter of a method so that the method accepts any number of parameters of a particular type public class Test { public static void Main () { Console.WriteLine (add (1, 2, 3, 4).ToString()); } public static int add (params int[] array) { int sum = 0; foreach (int i in array) sum += i; return sum; } } prints: 10 class Test

static void F(int[] args) { System.out.println("# of arguments: " + args.length); for (int i = 0; i < args.length; i++) System.out.println("args[" + i + "] = " + args[i]); } public static void main(String[] args) { F(); //error F(1); //error F(1, 2); //error F(1, 2, 3);//error F(new int[] {1, 2, 3, 4}); } } class Test { static void F(Object[] args) { for(int i = 0; i < args.length; i++) { Object o = args[i]; System.out.println(o.getCl ass().getName()); } } public static void main(String[] args) { Object[] a = {new Integer(1), "Hello", new Double(123.456)}; Object o = a; F(a); //F((Object)a);//error //F(o);//error F((Object[])o); } } prints: java.lang.Integer java.lang.String java.lang.Double java.lang.Integer java.lang.String java.lang.Double

static void F(params int[] args) { Console.WriteLine("# of arguments: {0}", args.Length); for (int i = 0; i < args.Length; i++) Console.WriteLine("\ targs[{0}] = {1}", i, args[i]); } static void Main() { F(); F(1); F(1, 2); F(1, 2, 3); F(new int[] {1, 2, 3, 4}); } } using System; class Test { static void F(params object[] args) { foreach (object o in a) { Console.Write(o.GetT ype().FullName); Console.Write(" "); } Console.WriteLine(); } static void Main() { object[] a = {1, "Hello", 123.456}; object o = a; F(a); F((object)a); F(o); F((object[])o); } } prints: System.Int32 System.String System.Double System.Object[] System.Object[] System.Int32 System.String System.Double

Primitives vs Objects

Java
Java primitives cannot be assigned to reference types directly. class Test { public static void main(String[] args) { int i = 123; Object o = i; // error int j = (int) o; // error System.out.println(3.toString() );//error } }

C#
C# provides a "unified type system". All types derive from the type object class Test { static void Main() { int i = 123; object o = i; // boxing int j = (int) o; // unboxing Console.WriteLine(3.ToSt ring()); } }

protected Modifier

Java

C#

public class A public class A { { protected int x; protected int x; static void F(A a, B b) { static void F(A a, B b) { a.x = 1; // Ok a.x = 1; // Ok b.x = 1; // Ok b.x = 1; // Ok } } } } public class B extends A public class B: A { { static void F(A a, B b) { static void F(A a, B b) { a.x = 1; // Ok a.x = 1; // Error, must access b.x = 1; // Ok // through instance of } B } b.x = 1; // Ok } }

Reference Parameters

Java
class Test { class Test { static void swap(int a, int b) { static void int t = a; int b) { a = b; int t = b = t; a = b; } b = t; public static void main(String[] } args) { static void int x = 1; int x = int y = 2; int y = System.out.println("pre: x = " + x + " y = " + y); swap(x, y); System.out.println("post: x = " + x + " y = " + y); } } The output of the program is: pre: x = 1, y = 2 post: x = 1, y = 2 NOTE: You have to use reference type to make swap work in such situation.

C#
Swap(ref int a, ref a;

Main() { 1; 2;

Console.WriteLine("pre: x = {0}, y = {1}", x, y); Swap(ref x, ref y); Console.WriteLine("post: x = {0}, y = {1}", x, y); } } The output of the program is: pre: x = 1, y = 2 post: x = 2, y = 1

Scope

Java
class A {} class Test { public static void main(String[] args) { String A = "hello, world"; String s = A; Class t = new A().getClass(); System.out.println(s); // writes "hello, world" System.out.println(t); // writes "class A"

C#
class A {} class Test { static void Main() { string A = "hello, world"; string s = A; // expression context Type t = typeof(A); // type context Console.WriteLine(s); // writes "hello, world" Console.WriteLine(t); // writes "A"

class Test { double x; void F(boolean b) { x = 1.0; if (b) { int x = 1; } } }

class Test { double x; void F(bool b) { x = 1.0; if (b) { int x = 1;//error } } } compile-time error because x refers to different entities within the outer block. The following is OK class Test { double x; void F(bool b) { if (b) { x = 1.0; } else { int x = 1; } } } because the name x is never used in the outer block

Stack class

Java
public class Stack { private Node first = null; public boolean isEmpty { return (first == null); } public Object Pop() { if (first == null) throw new Exception("Can't Pop from an empty Stack."); else { Object temp =

C#
public class Stack { private Node first = null; public bool Empty { get { return (first == null); } } public object Pop() { if (first == null) throw new Exception("Can't Pop from an empty Stack.");

first.Value;

else { object temp = first.Value; } first = first.Next; } return temp; public void Push(Object o) { } first = new Node(o, first); } } public void Push(object o) { class Node { first = new Node(o, first); public Node Next; } public Object Value; class Node public Node(Object value) { { this(value, null); public Node Next; } public object Value; public Node(Object value, public Node(object value): Node next) { this(value, null) {} Next = next; public Node(object value, Value = value; Node next) { } Next = next; } Value = value; } } } } first = first.Next; return temp;

static context

Java
class Test { int x; static int y; void F() { x = 1; // Ok, same as this.x = 1 y = 1; // Ok, same as Test.y = 1 } static void G() { y = 1; // Ok, same as Test.y = 1 } public static void main(String[] args) { Test t = new Test(); t.x = 1; // Ok t.y = 1; // Ok Test.y = 1; // Ok } }

C#
class Test { int x; static int y; void F() { x = 1; // Ok, same as this.x = 1 y = 1; // Ok, same as Test.y = 1 } static void G() { y = 1; // Ok, same as Test.y = 1 } static void Main() { Test t = new Test(); t.x = 1; // Ok t.y = 1; // Error, cannot access static member through instance Test.y = 1; // Ok } }

class C { private static void F() { System.out.println("C.F" ); } public static class Nested { public static void G() { F(); } } } class Test { public static void main(String[] args) { C.Nested.G(); } } circular definition class Test { static int a = b + 1;//illegal forward reference static int b = a + 1; public static void main(String[] args) { System.out.println("a = "+a+" b = "+b); } } //no compilation

class C { private static void F() { Console.WriteLine("C.F"); } public class Nested { public static void G() { F(); } } } class Test { static void Main() { C.Nested.G(); } } circular definition class Test { static int a = b + 1; static int b = a + 1; static void Main() { Console.WriteLine("a = {0}, b = {1}", a, b); } } prints: a = 1 b = 2

static field initialization using System; class Test { static field initialization static void Main() { class Test Console.WriteLine("{0} {1}", { B.Y, A.X); public static void } main(String[] args) { public static int f(string s) { System.out.println(B.Y + Console.WriteLine(s); A.X); return 1; } } public static int f(String } s) { class A System.out.println(s); { return 1; public static int X = Test.f("Init } A"); } } class A class B { { public static int X = public static int Y = Test.f("Init Test.f("Init A"); B"); } } class B prints: or

public static int Y = Test.f("Init B"); } prints: Init B Init A 2

Init A Init B 1 1

Init B Init A 1 1

use static constructor using System; class Test { static void Main() { Console.WriteLine("{0} {1}", B.Y, A.X); java has no static constructor } class Test public static int f(string s) { { Console.WriteLine(s); public static void return 1; main(String[] args) { } System.out.println(B.Y + } A.X); class A } { public static int f(String static A() {} s) { public static int X = System.out.println(s); Test.f("Init A"); return 1; } } class B } { class A static B() {} { public static int Y = A(){} Test.f("Init B"); public static int X = } Test.f("Init A"); the output must be: } Init B class B Init A { 1 1 B(){} public static int Y = Test.f("Init B"); } prints: Init B Init A 2

struct

Java
Java doesn't have struct. You may design a final class or a simple class

C#
A struct is a user-defined value type. It is declared in a very similar way to a class,

to replace struct

except that it can't inherit from any class, class Point nor can any class inherit from it. { struct is not a reference type. public int x, y; struct Point public Point(int x, int y) { { this.x = x; public int x, y; this.y = y; public Point(int x, int y) { } this.x = x; } this.y = y; Point a = new Point(10, 10); } Point b = a; } a.x = 100; Point a = new Point(10, 10); System.out.println(b.x); Point b = a; prints: 100 a.x = 100; Since Point is a reference type, System.Console.WriteLine(b.x); b and a point to the same prints: 10 address, Since struct Point is a value type, when a's value changed, b's value not a reference type, a's value changed too. changed doesn't involve b's value. structs are sealed, lightweighted and more efficient than classes.

synchronized vs. lock

Java
class Cache { public void add(Object x) { synchronized (this) { ... } } public void remove(Object x) { synchronized (this) { ... } } }

C#
class Cache { public static void Add(object x) { lock (typeof(Cache)) { ... } } public static void Remove(object x) { lock (typeof(Cache)) { ... } } } or lock(this) {...}

synchronized vs. lock

Java
class Cache { public void add(Object x) { synchronized (this) { ... } } public void remove(Object x) { synchronized (this) { ... } } }

C#
class Cache { public static void Add(object x) { lock (typeof(Cache)) { ... } } public static void Remove(object x) { lock (typeof(Cache)) { ... } } } or lock(this) {...}

try/catch statement

Java
try/catch statement static int F(int a, int b) { if (b == 0) throw new Exception("Divide by zero"); return a / b; } public static void main(String[] args) { try { System.out.println(F(5, 0)); }catch(Exception e) { System.out.println("Error"); } }

C#
try/catch statement static int F(int a, int b) { if (b == 0) throw new Exception("Divide by zero"); return a / b; } static void Main() { try { Console.WriteLine(F(5, 0)); }catch(Exception e) { Console.WriteLine("Error") ; } }

nested try/finally statement class Test nested try/finally statement { class Test public static void main(String[] { args) { static void Main() { while (true) { while (true) { try { try { try { try {

ln("Before break");

System.out.print

ine("Before break");

Console.WriteL

break; break; } } finally { finally { System.out.print Console.WriteL ln("Innermost finally block"); ine("Innermost finally block"); } } } } finally { finally { System.out.println(" Console.WriteLine( Outermost finally block"); "Outermost finally block"); } } } } System.out.println("After Console.WriteLine("After break"); break"); } } } } prints: prints: Before break Before break Innermost finally block Innermost finally block Outermost finally block Outermost finally block After break After break throw statement class Test { static void F() throws Exception { try { G(); } catch (Exception e) { System.out.println("Exce ption in F: " + e.getMessage()); e = new Exception("F"); throw e; // re-throw } } static void G() throws Exception{ throw new Exception("G"); } public static void main(String[] args) { try { F(); } catch (Exception e) { System.out.println("Exce ption in Main: " + e.getMessage()); } } } >java Test Exception in F: G throw statement class Test { static void F() { try { G(); } catch (Exception e) { Console.WriteLine("Exc eption in F: " + e.Message); e = new Exception("F"); throw; // rethrow } } static void G() { throw new Exception("G"); } static void Main() { try { F(); } catch (Exception e) { Console.WriteLine("Exc eption in Main: " + e.Message); } } } >csc Test.cs Exception in F: G Exception in Main: F

Exception in Main: F

Type Example

Java
public class Color { String Red, Blue, Green; } public class Point { public int x, y; } public interface IBase { void F(); } public interface IDerived extends IBase { void G(); } public class A { protected void H() { System.out.println("A.H"); } } public class B extends A implements IDerived { public void F() { System.out.println("B.F, implementation of IDerived.F"); } public void G() { System.out.println("B.G, implementation of IDerived.G"); } protected void H() { System.out.println("B.H, override of A.H"); } }

C#
public enum Color { Red, Blue, Green } public struct Point { public int x, y; } public interface IBase { void F(); } public interface IDerived: IBase { void G(); } public class A { protected virtual void H() { Console.WriteLine("A.H"); } } public class B: A, IDerived { public void F() { Console.WriteLine("B.F, implementation of IDerived.F"); } public void G() { Console.WriteLine("B.G, implementation of IDerived.G"); } override protected void H() { Console.WriteLine("B.H, override of A.H"); } } public delegate void EmptyDelegate();

public abstract void EmptyDelegate(); import personnel.data; class Employee { private static DataSet ds; public String name; public double salary; ... }

using Personnel.Data; class Employee { private static DataSet ds; public string Name; public decimal Salary; ... }

Вам также может понравиться