C# 4 Java Programmers

“Today” I learned C# and I will post some intersting facts about Java and C#. But please, this is just a draft. Maybe this wikipedia article is a better place for you.

And please correct me, if I posted mistakes or invalid facts about C#. Or if you missed a great feature of C# or an example of the facts, then please let me know.

Basics

  • All .NET languages are compatible to each other. I know that there are now some more languages for the jvm, but the jvm was published with only one language: Java.
  • package in Java will be namespace in c#; the root is “System”
  • style convention: a method starts with upper case: Method()
  • System.out.println(String) will be Console.Write(“Hello {0}!”, name);
  • Java String = c# string or String
  • Java Object = c# object or Object
  • Java boolean = c# bool
  • all types are objects (even Java primitives)
    e.g. if you write int in c# the class Int32 will be used
    the ‘c# primitives’ extend ValueType
    struct’s and enum’s are value types too
  • Unboxing: intVar = Convert.ToInt32(obj);
  • for enums only byte, short, long and int are valid (no string!)
  • int intDigit = Convert.ToInt32(Console.ReadLine()); //similar to Integer.parseInt(String); in Java
  • check arithmetic over- and underflows:
    long lngVariable = 235235252525L;
    int byteVar = checked((int)lngVariable); // raises an exception if var is not in bounds and even “checked { block; }” is possible or set properties in project->properties->Build->Advanced->Check for arithmetical….
  • more dimensional arrays in c# looks like:
    int[,] zelle = new int[4,3];
    int[,] point = new int[,]{{1,2,3},{4,5,6}}
    int[,] point = {{1,2,3},{4,5,6}}
  • the main method in C# is: static void Main(string[] args) //case sensitive!
  • Where we write in Java: for(int tempElement : intArr){block};
    we will do the same in c#: foreach(int tempElement in intArr){block};
    c#: foreach(Object tempElement in objArr){block}; //tempElement can be changed!
  • change the standard “call by value” on value types:
    call a method by: TestProc(ref intVar);
    or define a method by: TestProc(ref int intVar);
    (similar to “ref” is “out”; used to get several results from a method)
  • Java’s varargs “…”: public void sum(Integer… args) {}
    c#’s params: public long Sum(params int[] args) {}
  • operator overloading:
    public static FloorDouble operator + ( FloorDouble fd1, FloorDouble fd2 ) {
    return new FloorDouble( fd1.Value + fd2.Value );
    }
  • c# cloning: protected Object MemberwiseClone(); or via ICloneable
  • The relationship ‘has a’ in c# is really easy:
    class ClassA { private ClassB myObj; public ClassB MyObj { get {return myObj;} }}
    or e.g.: private int age;
    public int humanAge { get { return age; } set { age = value;} }
  • Java annotations = c# attribute
  • Java native = c# unsafe (you can use fixed, *pointer, ∫, a->b, … within c#!)
  • verbatim strings begin with the special character @. Please see this doc.
    string c = "hello \t world";               // hello     world
    string d = @"hello \t world";               // hello \t world
    string g = "\\\\server\\share\\file.txt";   // \\server\share\file.txt
    string h = @"\\server\share\file.txt";      // \\server\share\file.txt

Object Oriented Programming

  • sealed in c# means final class in Java
  • you can split sources in c# over several source files with the partial keyword
  • method modifier:
    Java public = c# public
    Java private = c# private or without modifier
    Java protected = C# protected
    Java without modifier = ?
    C# internal = a member is accessible from the entire assembly.
    All the objects you define inside a .cs file (you can define more than one object
    inside the .cs file, unlike Java, where you can usually define only one object) have a handle to the internal member.
    C# protected internal – think of this one as the union of protected and internal,
    as the item is is modifying is either protected or internal. This item can be
    accessed from the entire assembly, or within objects which derive from this class.
  • class modifier:
    Java public = c# public
    Java private = c# internal or without modifier
  • All methods in a c# objects are “final” by default.
  • Java @Override = c# override (different behaviour if the super method is virtual or not!)
  • c# readonly is more or less final keyword for a variable in a Java object
  • c# const is more or less final keyword for a variable in a Java class
  • c#’s ‘extend’: class ClassA : SuperClassA
  • constructor chain in c#: Line(double X) : this(X) {}
  • Java super = c# base
  • method hiding:
    class ClassA { public void TestMethod() { Console.WriteLine(“ClassA.TestMethod()”); }}
    calling ClassB.TestMethod() results in calling ClassA.TestMethod()!
    class ClassB : ClassA { private new void TestMethod() { Console.WriteLine(“ClassB.TestMethod()”); }}
  • Java instanceof is c# is: if(myObj is ClassA) {}
  • static constructor
    Java: class ClassA{ {/*here*/}}
    c#: class ClassA{ static ClassA() {/*here*/}}
  • function pointer in c#: public delegate void MyDelegate(int value1);
  • anonym method in c#: MyDelegate del = delegate(int value1) { return value1; };
    call via e.g.: del(123);
    keyword “event” in c#: public event MyDelegate MeasureError;
    (same as the listener concept in Java)
    to add a listener use: object.MyDelegate += new MeasureErrorEventHandler(MyError);
    cannot be used from a child class!
  • Java final method = c# sealed method

Generics

In c# we have real generics, with separate namespace: System.Collections.Generic (instead System.Collections)

For a direct comparison of these two packages, please visit this page of galileo computing and go to the chapter 7.4.8.

But it seems to me the Java collection API has some more Classes, e.g. today I missed a Set. Okay we can simulate it via a SortedList<Key, Value> …

  • use return default(T); to return 0 or null, because T could be a reference or a value type
  • System.Nullable<T> now we can nullable even value types! (Nullable.HasValue)
    usage: int? intVar;
  • C# IList<T> interface will be implemented by the generic type: List<T> (no generics: Array and ArrayList). Only Array allows arrays that are not zero-based.
  • (in Java it is the List<T> interface with ArrayList<T> and LinkedList<T> as implementations)
  • C# ICollection<T> interface: LinkedList<T> (doesn’t implement IList!?), Queue<T> and Stack<T> (no generics: Queue and Stack)
  • (in Java it is the Collection<T> interface)
  • C# IDictionary<K,V> interface: Dictionary<K,V> and SortedList<K,V> (no generics: Hashtable and SortedList)
  • (in Java it is the Map<K,V> interface)
  • C# abstract KeyedCollection<K,V> behaves like a dictionary and a list at the same time. Thats great!
  • Sort an array via:
    ArrayList list = ArrayList.Adapter(array);
    class Sorter : IComparer { public int Compare(object a, object b) {return 0,1,-1}}

    list.Sort(new Sorter());
  • C# has the keyword yield, which is useable if you implement IEnumerable. E.g.: IEnumerator GetEnumerator() {
    for(int i = 0; i < months.Length; i++) { yield return month[i]; }}

Some other ‘array’ classes

in C#: there is a BitVector which is variable in length and allocated on the heap (BitVector32 has only 32 bits and allocated on the stack, so its faster.)

In Java there is similar class BitSet.

IDE

  • add an existing project to the explorer: right click the explorer-> add->existing item
  • Quick Fix via: click on the small icon which pops up if you go with the mouse to an underlined error
  • in NetBeans: create a new class; extend it with the JPanel class -> not editable via visual editor
  • BUT in Visual Studio: new Class; extend it with the Panel class -> editable via DnD !!
  • There is a very small ‘button’ in the top right corner of every editor: You can drop it down and this will result in two views (horizontal splitted editors) of the current source file!
  • TODO: add more features that I found

Conclusion

What’s better in Java?

  • free (Open Source) and fully functional Virtual Machine
  • free (Open Source) and fully functional class library
  • free (Open Source) and fully functional IDE’s: netbeans, eclipse
  • mass of open source libraries
  • platform independed! (I know there is Mono, but when was the last time you tried to run the Visual Studio on Mono? And then look at Java: Eclipse, NetBeans, etc – all will run at least on linux and windows!)

Although I love Java there are really cool things in C#:

  • real generics!
  • instead setter/getter you can use label1.Text = “Test1”; (Accessors? )
  • XmlSerializer
  • linq
  • it is possible to overload operators
  • you can use string in switch statements!
  • you can use goto to escape from nested if statements!

Feel free to post your experiences with C#!

Resources

English documentation:
http://msdn.microsoft.com/en-us/library/ms228358.aspx

German documentation:
http://www.galileocomputing.de/openbook/csharp

16 thoughts on “C# 4 Java Programmers

  1. You missed a biggie with exception handling. The Java syntax for rethrowing an exception is DIFFERENT than C#.

    Java:
    try {
    throw new Exception();
    } catch(Exception e) {
    throw e;
    }

    C#
    try {
    throw new Exception();
    } catch(Exception e) {
    throw;
    }

  2. Under generics, I think there are a few better options:
    Map – Dictionary
    LinkedHashMap – SortedList or SortedDictionary (sort of)

  3. Thanks a lot James!
    @ 1 maybe I didn’t recognized the difference!
    @ 2 I will make a list of C# generics later (and maybe all Java, too)

  4. >> Java without modifier = ?

    Java without modifier = private in c#
    that case is “package” in java.

    >> use return default(T); to return 0 or null, because T could be a reference or a value type

    actually default(T) calls default constructor for structs. i.e. we can not simply conclude that it returns 0 for all value types. but it does return null for reference types.

    also, you should not skip partial classes, extension methods and differences in Threading API in your next edition:)

    • You can’t have a no argument constructor for a struct. So you cannot set members of the struct to anything but thier defaults

  5. Thanks contrapunctus for clarify the Java ‘package’ and the default(T) point.

    What are extension methods? And whats so different in the threading API?

    Hmmh, I didn’t skip enums and operater overloading. But maybe the comment was too short.

  6. Also, C#:
    – has a real Decimal literal. Very very nice compared to the verbose and buggy BigDecimal of Java.
    – does not have checked exceptions.
    – does not have wildcards for generics.
    – defines Double.MIN_VALUE as truly the smallest numerical value, Java returns the smallest *positive* numerical value.
    – allows a general catch statement, which implicit means catch(Exception e).
    – Local var type inference, extension methods, tree literals, anonymous types, automatic properties (LINQ)

  7. Peter–on the exceptions, didn’t mean to imply anything. Just learned that one the hard way very recently and wanted to make sure that one was pointed out. I’ve seen several other Java developers make the same mistake.

    I guess that’s what I get for not RTFM!

  8. Pingback: roScripts - Webmaster resources and websites

  9. Pingback: Bookmarking the web - w26/2008 - double density design

  10. I have found one difference between C#’s sealed method modifier and Java’s final modifier: There is not equivalent of the new modifier in Java for method signatures.

    public class CSharpBaseClass
    {
    public int CalculateSum(){
    int i = 0;
    //…
    return i;
    }
    }

    public class CSharpSubClass : CSharpBaseClass
    {
    //The new Keyword “Hides” the base class implimentation of this method
    public new int CalculateSum(){
    return 99;
    }
    }

    In Java when a method is marked as final. You can’t override it or “hide” it in subclasses.

    I haven’t found a true replacement for final in C#. Let me know if you know of a keyword that will not compile if “new” is used to “hide” a method. PS – the warning that .NET’s compiler issues if you override a method and do NOT use the new keyword isn’t strict enough, I want a compiler exception. 🙂

  11. Nice article. I have also written a small article on call by value and call by reference with both java and c#. Read that if you are interested…

Comments are closed.