Created Tuesday 07 January 2014
Similarities
- both have similar syntax
- all objects are references
- both use auto garbage collection
- both are type safe
- both allow generics (with slight differences. See :CSharp:MigratingFromJava3)
- single inheritance
- both have built-in unicode support
- both have built-in support for exception handling. (With differences. See below.)
- both have similar build processes (see :CSharp:MigratingFromJava4)
Differences
- there is no
throws
list of exceptions for function declarations---you have to look at docs, examine code, etc. to figure out if something gets thrown (error prone) - in Java, you must catch all
Exception
s that are explicitly thrown;RuntimeException
s need not be caught. In contrast, in C#, all exceptions are equivalent to JavaRuntimeException
s (so they never need to be caught even when explictly thrown). - Java is supported by more OSes
- C# has an "unsafe" mode (aka C++ mode)
- C# allows operator overloading (can be gross)
- C# supports indexers where you can access a class like an array (see
this
keyword below) - C# has dynamic-language support (can be dangerous. See
dynamic
keyword below) - C# has extra language keywords (see below)
- both support inheritance but each handles it slightly differently (see :CSharp:MigratingFromJava2)
- C# has anonymous types (see :CSharp:MigratingFromJava2)
- C# has extension methods --- "add" new methods to existing types without modifying the original source code (See MigratingFromJava2)
- C# can define a class across different files (see
partial
keyword below)
Java Keywords With No C# Equivalents
- native
- transient
- synchronized (when used on methods) - C# supports only synchronized blocks with
lock
keyword; however, you cannot synchronize methods.
C# Keywords With No Java Equivalents
- as keyword --- tries to cast object to given type; otherwise, returns null
Object o = //... string s = o as string; if (s != null) //...
- checked keyword --- creates block where you must check for arithmetic exceptions.
checked { try { short x = 32767; short y = 32767; short z = y + z; } catch (OverflowException e) { //... } }
- decimal --- defines 128-bit number
- delegate --- function pointers (see :CSharp:MigratingFromJava2)
- dynamic
/
object ---object
works just likeObject
in Java.dynamic
was introduced in C# 4.0. It works just likeObject
except that you don't need to make explicit casts (i.e., it turns C# into a dynamic language, so this can be dangerous). Allows interaction with dynamically typed objects. See resources below. See also duck typing.
object o = 10; dynamic d = 10; int x = (int) o + 3; //cast needed int y = d + 3;// cast not needed!
- built-in support for event handlers (see :CSharp:MigratingFromJava2)
- explicit --- defines casting from one class to another class as a user-defined operator
class Apartment { public string name; //convert an aparment to a house public static explicit operator House(Apartment a) { return new House(a.name); } //... } Apartment a = new Apartment("Soho"); //cast Apartment to House House h = (House) a;
- extern --- methods whose implementations are defined externally
- foreach --- used for
foreach
loops. Use in keyword. - get
/
set ---get {}
andset {}
define setters and getters that behave like class fields. Use value for the setter.
class MyClass { private int myint; public int MyInt { get { return m_int; } set { m_int = value; } } } MyClass m = new MyClass(); Int i = m.MyInt; m.MyInt = 23; //Note: in C# 3.0 the above class declaration is equivalent to: //(thanks to auto-implemented properties) class MyClass { public int MyInt { get; set; } } //You can also create instantances of these classes with set: MyClass myClass = new MyClass{ MyInt = 4 };
- implicit --- works just like
explicit
except you don't have to use an explicit cast - namespace --- used to create a scope containing a group of related objects.
namespace SampleNamespace { class SampleClass { } namespace SampleNamespace.Nested { class SampleClass2 { } } }
- new --- works just like
new
in Java. However, it can also be used to hide base methods in child classes. Note that if you cast a child object to a parent object, you will be able to access the hidden method. (Contrast this behavior withvirtual/override
)
class BaseClass { public void m1() { //... } } class DerivedClass : BaseClass { public new void m1() { //... } } DerivedClass derived = new DerivedClass(); derived.m1(); //calls DerivedClass#m1 BaseClass casted = new DerivedClass(); casted.m1(); //calls BaseClass#m1
- operator --- allows you to override operators in classes.
public class Vector3D { public static Vector3D operator + (Vector3D v) { //.. } }
- partial --- add this keyword before
class
to define a class over several files. - out --- signals that method argument may be modified by the method. HOWEVER, the official docs says to use
out
sparringly. - override/virtual --- use this keyword pair to effectively erase base methods in child classes. (Compare with
new.)
class BaseClass { public virtual void m1() { //... } } class DerivedClass : BaseClass { public override void m1() { //... } } DerivedClass derived = new DerivedClass(); derived.m1(); //calls DerivedClass#m1 BaseClass casted = new DerivedClass(); casted.m1(); //calls DerivedClass#m1
- params --- works just like ... in Java.
public int add(params int[] args) { //... } //can call #add with variable number of arguments: add(1); add(1,2,3);
- ref --- in C# like in Java objects are passed by reference. Marking a parameter with
ref
passes a pointer to that pointer. The official docs say to use this keyword infrequently. - sbyte --- signed byte between -128 and 127
- struct --- lightweight class. Works just like a class except that structs are: (1) stored on the stack instead of the heap. (2) passed by value instead of by reference. (3) constructors (if defined) must take parameters. (4) no support for inheritance. (However, structs can implement interfaces.) (5) you can control memory layout of its fields. See resources for details.
- this --- works just like
this
in Java. However, it's also used to create an indexer. An indexer allows you to access a class object like an array: you define the operator [] for a class.
class Layout { string[] _values = new string[100]; // Backing store public string this[int number] { get { return _values[number]; } set { _values[number] = value; } } } Layout layout = new Layout(); layout[1] = "Hello world"; String value1 = layout[1]; //Note: in above example, "number" is an int but it can be any type. //Note: an indexer can use any number of parameters
- typeof --- returns the
Type
of the object - unit --- unsigned integer
- ulong --- unsigned long
- unchecked --- opposite of checked. No arithmetic exception checking in block.
- unsafe --- defines an unsafe block
- using --- ensure object is disposed (marked for garbage collection) as soon as you're done using it.
using (MyResource myRes = new MyResource()) { myRes.DoSomething(); } //is equivalent to { // limits scope of myRes MyResource myRes= new MyResource(); try { myRes.DoSomething(); } finally { // Check for a null resource. if (myRes!= null) // Call the object's Dispose method. ((IDisposable)myRes).Dispose(); } } //NOTE: object must implement IDisposable interface
The using keyword is also used to import namespaces:
using System; System.Console.WriteLine("Hello"); Console.WriteLine("World!");
- var --- implicit type similar to using
Object
keyword in Java except that compiler knows the underlying type - ? --- in addition for conditional shorthand (
expr ? s1 : s2
), use this symbol to create nullable fields in classes. Ex:public int? x
is a int that can also take on the null value. - ?? --- is the null coalescing operator.
A = a ?? new A()
is shorthand forA = a != null ? a : new A()
Unsafe Mode Keywords
Unsafe code is for allowing C/C++ style pointer manipulation. See :CSharp:MigratingFromJava2
fixed
--- used in unsafe mode for manipulating pointers- sizeof
- stacalloc
Resources
- C# and Java: Comparing Programming Languages
- Java vs C#
- Hidden Features of C#
- http://stackoverflow.com/questions/20976660/migrate-from-java-to-c
- http://programmers.stackexchange.com/questions/221944/using-c-to-learn-c
- https://github.com/bdb-opensource/c-sharp-pitfalls
- http://msdn.microsoft.com/en-us/library/ms836794.aspx
- http://stackoverflow.com/questions/15803965/use-new-keyword-in-c-sharp
- http://stackoverflow.com/questions/5523031/dynamic-keyword-vs-object-data-type
- What is the difference between dynamic and object keywords?
- Official Docs: Avoid OUT params
- Official Docs: Working with structs
- Official Docs: Indexers
- Are there any opensource C# IDEs?
No backlinks to this page. comments powered by Disqus