Java vs. C#

Constructor


Java
 
constructor-modifier:
    public
    protected
    private




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 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

C#
 
constructor-modifier:
    public
    protected
    internal
    private
    extern
    static

constructor-initializer: : base(argument-list) : this(argument-list)
using System; class A { public A() { PrintFields(); } 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 { 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