Archive

Posts Tagged ‘.NET’

Different points of Java and C#

October 3rd, 2011 No comments

Recently I’ve started discovering C# in .NET world. As my background is Java and its world, I encounter various difficulties in learning C#. It’s not a bad idea for me to take note different points of Java and C#, that would not only let me validate my understanding well, but also help those who are in a situation like me can quickly stick to the core of both worlds.

I make comparison based on:

  • Java 6
  • C# 4.0

Points of difference are written:

  • in pairs
  • one by one
  • in no order

Mostly I will collect materials from Internet for explanation and demonstration. Feel free to comment or drop me an email if I wrote something wrong. Thank you!

1. Class variables

Java

Member variables in a class are called fields.

public class Bicycle {

    // the Bicycle class has three fields
    public int cadence;
    public int gear;
    public int speed;
}

C#

A class can have fields and properties. They look similar from outside but from inside, a field has no logic while a property may have logic.

public class Stock

{

decimal currentPrice;  // The private “backing” field

public decimal CurrentPrice    // The public property

{

get { return currentPrice; }

set { currentPrice = value; }

}

}

2. Access modifiers

Java

Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier

(package-private)

Y Y N N
private Y N N N

The first data column indicates whether the class itself has access to the member defined by the access level. As you can see, a class always has access to its own members. The second column indicates whether classes in the same package as the class (regardless of their parentage) have access to the member. The third column indicates whether subclasses of the class “declared outside this package” have access to the member. The fourth column indicates whether all classes have access to the member.

C#

public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.

private
The type or member can be accessed only by code in the same class or struct.

protected
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

3. Constant variables

Java

A final variable can only be initialized once, either via an initializer or an assignment statement. It need not be initialized at the point of declaration: this is called a ‘blank final’ variable. A blank final instance variable of a class must be definitely assigned at the end of every constructor of the class in which it is declared; similarly, a blank final static variable must be definitely assigned in a static initializer of the class in which it is declared: otherwise, a compile-time error occurs in both cases.

public class Sphere {
    public static final double PI = 3.141592653589793;  // a constant
    public final double radius;  // a blank final constant
    public Sphere() {
    radius = 1.0;
    }
}

C#

Constants are declared with the const modifier. Only the C# built-in types (excluding System.Object) may be declared as const. For a list of the built-in types, see Built-In Types Table (C# Reference). User-defined types, including classes, structs, and arrays, cannot be const. Use the readonly modifier to create a class, struct, or array that is initialized one time at runtime (for example in a constructor) and thereafter cannot be changed.

Constants must be initialized as they are declared.

class Calendar1
{
    public const int months = 12;
}

When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

class Age
    {
        readonly int _year;
        Age(int year)
        {
            _year = year;
        }
        void ChangeYear()
        {
            //_year = 1967; // Compile error if uncommented.
        }
    }

3. Static Constructors

Java

Static constructor is not really supported by Java, but you can use static initialization block instead. A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:

static {

    // whatever code is needed for initialization goes here
}

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

C#

A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

Static constructors have the following properties:

  • A static constructor does not take access modifiers or have parameters.
  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  • A static constructor cannot be called directly.
  • The user has no control on when the static constructor is executed in the program.
  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.
  • If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Example.

class Apple
 {
 static Apple()
 {
 Console.WriteLine("Apple type is initialized.");
 }

 public Apple()
 {
 Console.WriteLine("one");
 }
 }

When you instantiate above class, output will be:

Apple type is initialized.

one

4. Packages and Namespaces

Java

Classes and interfaces are organized into packages, which in fact are directories on operating system. Package declaration must be first and before any other statement (except comment) in a Java source file.

To declare a package, use keyword package.

//in the Rectangle.java file
package graphics;
public class Rectangle {
   . . .
}

Then, put the source file in a directory whose name reflects the name of the package to which the type belongs:

.....\graphics\Rectangle.java

C#

Classes are organized virtually into namespaces, no directory is required like that of Java. A class can have many namespace declarations.

To declare a namespace, use keyword namespace.

namespace N1     // N1
{
    class C1      // N1.C1
    {
        class C2   // N1.C1.C2
        {
        }
    }
    namespace N2  // N1.N2
    {
        class C2   // N1.N2.C2
        {
        }
    }
}

The following code:

namespace N1.N2
{
   class A {}
   class B {}
}

is semantically equivalent to

namespace N1
{
   namespace N2
   {
      class A {}
      class B {}
   }
}

5. Order of declaration

Java

// declare package first

package A

// then import something

import B

C#

A traditional order is (more):

// use something

using B

// then declare namespace

namespace A

Howeve the correct order is (more):

// declare namespace

namespace A

// then use something

using B