SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
.
.

C# / Java Language Comparison
Robert Bachmann

April 4, 2011

1 / 22
Outline

My favorite pitfalls
Common conventions
Type system
Generics
Keywords
Exceptions
Speci c features of Java
Speci c features of C#

2 / 22
My favorite pitfalls

str == "hello"
Checks equality in C#. Checks identity in Java.
Virtual methods
Opt-out in Java (final keyword) vs. opt-in in C# (virtual keyword)
Dates
new GregorianCalendar(2011, 3, 4)1 vs.
new DateTime(2011,4,4)

1

Hint: use YodaTime, Date4J, …
3 / 22
Common conventions

Package names / Namespaces: org.acme.foo vs. Acme.Foo
Interfaces: Supplier vs. ISupplier
Methods: doSomething vs. DoSomething
Opening braces: Same line in Java vs. next line in C#

4 / 22
Type system
Basic types

Java
String
Object
boolean
char
short
int
long
double
oat
byte
—
—
—
—

C#
string
object
bool
char
short
int
long
double
oat
sbyte
byte
ushort
uint
ulong

CLR Type
String
Object
Boolean
Char
Int16
Int32
Int64
Double
Single
SByte
Byte
UInt16
UInt32
UInt64
5 / 22
Type system
Java has reference and primitive types.
C# has reference and value types.
Uses an uni ed type system, for example you can do 42.ToString()
It’s possible to create custom value types:
public struct Point
{
public int X { get; set; }
public int Y { get; set; }
public override string ToString ()
{
return String . Format ("({0} ,{1})", X, Y);
}
}

6 / 22
Generics

Java uses type erasure. Generics are (mostly) a compiler feature.
new ArrayList <Integer >(). getClass ();
// -> ArrayList
new ArrayList <String >(). getClass ();
// -> ArrayList

C# uses rei ed generics. Generics are a runtime feature.
new List <int >(). GetType ();
// -> List `1[ Int32 ]
new List <string >(). GetType ();
// -> List `1[ String ]

7 / 22
Generics in Java
Code:
ArrayList <String > list1 = new ArrayList <String >();
list1 .add(" hello ");
String s = list1 .get (0);
ArrayList <Integer > list2 = new ArrayList <Integer >();
list2 .add (42);
int i = list2 .get (0);

Decompiled:
ArrayList list1 = new ArrayList ();
list1 .add(" hello ");
String s = ( String ) list1 .get (0);
ArrayList list2 = new ArrayList ();
list2 .add( Integer . valueOf (42));
int i = (( Integer ) list2 .get (0)). intValue ();
8 / 22
Generics in C#
Code:
List <string > list1 = new List <string >();
list1 .Add(" hello ");
string s = list1 [0];
List <int > list2 = new List <int >();
list2 .Add (42);
int i = list2 [0];

Decompiled:
List <string > list = new List <string >();
list.Add(" hello ");
string text = list [0];
List <int > list2 = new List <int >();
list2 .Add (42);
int num = list2 [0];
9 / 22
Generics
List factory method example

public class ListFactory {
public static <T> List <T> newList () {
// ^^^
return new ArrayList <T >();
}
}
// use with
List <String > list = ListFactory . newList ();

10 / 22
Generics
List factory method example

public class ListFactory
{
public static IList <T> newList <T >()
// ^^^
{
return new List <T >();
}
}
// use with
IList <int > list = ListFactory .newList <int >();
// Does not work:
IList <int > list = ListFactory . newList ();
// The type arguments for method
// ListFactory .newList <T >() ' cannot be inferred
// from the usage .
// Try specifying the type arguments explicitly .
11 / 22
Generics
Constraints

<T extends Comparable <T>> T max(T a, T b) {
if (a. compareTo (b) > 0)
return a;
else
return b;
}
T max <T >(T a, T b)
where T : IComparable <T>
{
if (a. CompareTo (b) > 0)
return a;
else
return b;
}
12 / 22
Generics
Constraints

where T : ClassOrInterface,
same as T extends ClassOrInterface
where T : new(), T has a parameterless constructor.
where T : class, T is a reference type.
where T : struct, T is a value type.

13 / 22
Keywords

Visibility
Common: public, protected, and private
Java: Package visibility.
C#: internal and protected internal
final vs. sealed (for methods and classes)
final vs. readonly (for members)
for (T item : items) vs. foreach (T item in items)
instanceof vs. is
Foo.class vs. typeof(Foo)

14 / 22
Exceptions

Java
Must throw a Throwable
Has checked and unchecked exceptions
Re-throw with throw e;

C#
Must throw an Exception
Has no checked exceptions
Re-throw with throw;
throw e; has a different semantic

15 / 22
Speci c features of Java

Anonymous inner classes
static import

16 / 22
Speci c features of C#

First class properties
using blocks
Preprocessor
Delegates and lambda expressions
LINQ

17 / 22
Speci c features of C#
using blocks

// using ( IDisposable )
static String ReadFirstLineFromFile ( String path) {
using ( StreamReader reader = File. OpenText (path )) {
return reader . ReadLine ();
}
}
// http :// download .java.net/jdk7/docs/ technotes /
// guides / language /try -with - resources .html
// try ( AutoClosable )
static String readFirstLineFromFile ( String path)
throws IOException {
try ( BufferedReader br =
new BufferedReader (new FileReader (path )) {
return br. readLine ();
}
}
18 / 22
Speci c features of C#
Preprocessor

public static void Main( string [] args)
{
#if DEBUG
Console . WriteLine (" Debug ␣...");
# endif
Console . WriteLine (" Hello ");
}

19 / 22
Speci c features of C#
Delegates and lambda expressions

public delegate bool Predicate <T>(T obj );
public static void Main( string [] args)
{
List <string > list = new List <string >{
" Hello ", " World ", "what 's", "up"
};
Predicate <String > shortWord ;
shortWord = delegate ( string s) { return s. Length < 4;};
shortWord = s => s. Length < 4;
list.Find( shortWord );
// or just
list.Find(s => s. Length < 4);
}

20 / 22
Speci c features of C#
LINQ

public static void Main( string [] args)
{
var list = new List <string > {
" Hello ", " World ", "what 's", "up"
};
var result = from item in list select item. Length ;
foreach (int i in result ) {
Console . WriteLine (i);
// -> 5, 5, 6, 2
}
}

21 / 22
Speci c features of C#
More features

Operator overloading
dynamic pseudo-type
yield keyword, similar to Python
Extension methods
Expression trees
Explicit interfaces
Partial classes
…
See http://en.wikipedia.org/wiki/Comparison_of_C_Sharp_and_Java

22 / 22

Mais conteúdo relacionado

Mais procurados

C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmers
Mark Whitaker
 

Mais procurados (20)

Difference between Java and c#
Difference between Java and c#Difference between Java and c#
Difference between Java and c#
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmers
 
C++ oop
C++ oopC++ oop
C++ oop
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
 
C++ Training
C++ TrainingC++ Training
C++ Training
 
Esoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basicsEsoft Metro Campus - Certificate in java basics
Esoft Metro Campus - Certificate in java basics
 
Writing Parsers and Compilers with PLY
Writing Parsers and Compilers with PLYWriting Parsers and Compilers with PLY
Writing Parsers and Compilers with PLY
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharp
 
C++11
C++11C++11
C++11
 
C++17 std::filesystem - Overview
C++17 std::filesystem - OverviewC++17 std::filesystem - Overview
C++17 std::filesystem - Overview
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
 

Destaque

Java vs .net
Java vs .netJava vs .net
Java vs .net
Tech_MX
 
FMP Storyboard
FMP StoryboardFMP Storyboard
FMP Storyboard
7jebarrett
 
Slide ken18 nov2013
Slide ken18 nov2013Slide ken18 nov2013
Slide ken18 nov2013
learnerchamp
 

Destaque (20)

Google's Guava
Google's GuavaGoogle's Guava
Google's Guava
 
JNA
JNAJNA
JNA
 
Java v/s .NET - Which is Better?
Java v/s .NET - Which is Better?Java v/s .NET - Which is Better?
Java v/s .NET - Which is Better?
 
Java vs .net
Java vs .netJava vs .net
Java vs .net
 
Java vs .net (beginners)
Java vs .net (beginners)Java vs .net (beginners)
Java vs .net (beginners)
 
Java vs .Net
Java vs .NetJava vs .Net
Java vs .Net
 
Jython
JythonJython
Jython
 
Sv eng ordbok-2012
Sv eng ordbok-2012Sv eng ordbok-2012
Sv eng ordbok-2012
 
Organizing edmngt
Organizing edmngtOrganizing edmngt
Organizing edmngt
 
FMP Storyboard
FMP StoryboardFMP Storyboard
FMP Storyboard
 
Unidad I Análisis Vectorial
Unidad I Análisis VectorialUnidad I Análisis Vectorial
Unidad I Análisis Vectorial
 
Behaviorism Powerpoint
Behaviorism PowerpointBehaviorism Powerpoint
Behaviorism Powerpoint
 
Slide ken18 nov2013
Slide ken18 nov2013Slide ken18 nov2013
Slide ken18 nov2013
 
Retirada de medicación antiepiléptica.
Retirada de medicación antiepiléptica. Retirada de medicación antiepiléptica.
Retirada de medicación antiepiléptica.
 
Danielle davis learning theory
Danielle davis   learning theoryDanielle davis   learning theory
Danielle davis learning theory
 
Sesión anatomopatológica. Discusión. [caso cerrado]
Sesión anatomopatológica. Discusión. [caso cerrado]Sesión anatomopatológica. Discusión. [caso cerrado]
Sesión anatomopatológica. Discusión. [caso cerrado]
 
Características clínicas de una serie de pacientes con amnesia global trans...
Características clínicas de una serie de pacientes con amnesia global trans...Características clínicas de una serie de pacientes con amnesia global trans...
Características clínicas de una serie de pacientes con amnesia global trans...
 
Trastornos motores asociados a demencia frontotemporal.
Trastornos motores asociados a demencia frontotemporal. Trastornos motores asociados a demencia frontotemporal.
Trastornos motores asociados a demencia frontotemporal.
 
Cefalea en la mujer.
Cefalea en la mujer. Cefalea en la mujer.
Cefalea en la mujer.
 
Utilidad del EEG en el área de urgencias de un hospital de tercer nivel
Utilidad del EEG en el área de urgencias de un hospital de tercer nivelUtilidad del EEG en el área de urgencias de un hospital de tercer nivel
Utilidad del EEG en el área de urgencias de un hospital de tercer nivel
 

Semelhante a C# / Java Language Comparison

Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
Mohamed Krar
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
Philip Johnson
 

Semelhante a C# / Java Language Comparison (20)

Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
C# programming
C# programming C# programming
C# programming
 
Lesson11
Lesson11Lesson11
Lesson11
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Clean Code
Clean CodeClean Code
Clean Code
 
Java generics
Java genericsJava generics
Java generics
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
Csharp4 generics
Csharp4 genericsCsharp4 generics
Csharp4 generics
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
 
Primitives in Generics
Primitives in GenericsPrimitives in Generics
Primitives in Generics
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

C# / Java Language Comparison

  • 1. . . C# / Java Language Comparison Robert Bachmann April 4, 2011 1 / 22
  • 2. Outline My favorite pitfalls Common conventions Type system Generics Keywords Exceptions Speci c features of Java Speci c features of C# 2 / 22
  • 3. My favorite pitfalls str == "hello" Checks equality in C#. Checks identity in Java. Virtual methods Opt-out in Java (final keyword) vs. opt-in in C# (virtual keyword) Dates new GregorianCalendar(2011, 3, 4)1 vs. new DateTime(2011,4,4) 1 Hint: use YodaTime, Date4J, … 3 / 22
  • 4. Common conventions Package names / Namespaces: org.acme.foo vs. Acme.Foo Interfaces: Supplier vs. ISupplier Methods: doSomething vs. DoSomething Opening braces: Same line in Java vs. next line in C# 4 / 22
  • 6. Type system Java has reference and primitive types. C# has reference and value types. Uses an uni ed type system, for example you can do 42.ToString() It’s possible to create custom value types: public struct Point { public int X { get; set; } public int Y { get; set; } public override string ToString () { return String . Format ("({0} ,{1})", X, Y); } } 6 / 22
  • 7. Generics Java uses type erasure. Generics are (mostly) a compiler feature. new ArrayList <Integer >(). getClass (); // -> ArrayList new ArrayList <String >(). getClass (); // -> ArrayList C# uses rei ed generics. Generics are a runtime feature. new List <int >(). GetType (); // -> List `1[ Int32 ] new List <string >(). GetType (); // -> List `1[ String ] 7 / 22
  • 8. Generics in Java Code: ArrayList <String > list1 = new ArrayList <String >(); list1 .add(" hello "); String s = list1 .get (0); ArrayList <Integer > list2 = new ArrayList <Integer >(); list2 .add (42); int i = list2 .get (0); Decompiled: ArrayList list1 = new ArrayList (); list1 .add(" hello "); String s = ( String ) list1 .get (0); ArrayList list2 = new ArrayList (); list2 .add( Integer . valueOf (42)); int i = (( Integer ) list2 .get (0)). intValue (); 8 / 22
  • 9. Generics in C# Code: List <string > list1 = new List <string >(); list1 .Add(" hello "); string s = list1 [0]; List <int > list2 = new List <int >(); list2 .Add (42); int i = list2 [0]; Decompiled: List <string > list = new List <string >(); list.Add(" hello "); string text = list [0]; List <int > list2 = new List <int >(); list2 .Add (42); int num = list2 [0]; 9 / 22
  • 10. Generics List factory method example public class ListFactory { public static <T> List <T> newList () { // ^^^ return new ArrayList <T >(); } } // use with List <String > list = ListFactory . newList (); 10 / 22
  • 11. Generics List factory method example public class ListFactory { public static IList <T> newList <T >() // ^^^ { return new List <T >(); } } // use with IList <int > list = ListFactory .newList <int >(); // Does not work: IList <int > list = ListFactory . newList (); // The type arguments for method // ListFactory .newList <T >() ' cannot be inferred // from the usage . // Try specifying the type arguments explicitly . 11 / 22
  • 12. Generics Constraints <T extends Comparable <T>> T max(T a, T b) { if (a. compareTo (b) > 0) return a; else return b; } T max <T >(T a, T b) where T : IComparable <T> { if (a. CompareTo (b) > 0) return a; else return b; } 12 / 22
  • 13. Generics Constraints where T : ClassOrInterface, same as T extends ClassOrInterface where T : new(), T has a parameterless constructor. where T : class, T is a reference type. where T : struct, T is a value type. 13 / 22
  • 14. Keywords Visibility Common: public, protected, and private Java: Package visibility. C#: internal and protected internal final vs. sealed (for methods and classes) final vs. readonly (for members) for (T item : items) vs. foreach (T item in items) instanceof vs. is Foo.class vs. typeof(Foo) 14 / 22
  • 15. Exceptions Java Must throw a Throwable Has checked and unchecked exceptions Re-throw with throw e; C# Must throw an Exception Has no checked exceptions Re-throw with throw; throw e; has a different semantic 15 / 22
  • 16. Speci c features of Java Anonymous inner classes static import 16 / 22
  • 17. Speci c features of C# First class properties using blocks Preprocessor Delegates and lambda expressions LINQ 17 / 22
  • 18. Speci c features of C# using blocks // using ( IDisposable ) static String ReadFirstLineFromFile ( String path) { using ( StreamReader reader = File. OpenText (path )) { return reader . ReadLine (); } } // http :// download .java.net/jdk7/docs/ technotes / // guides / language /try -with - resources .html // try ( AutoClosable ) static String readFirstLineFromFile ( String path) throws IOException { try ( BufferedReader br = new BufferedReader (new FileReader (path )) { return br. readLine (); } } 18 / 22
  • 19. Speci c features of C# Preprocessor public static void Main( string [] args) { #if DEBUG Console . WriteLine (" Debug ␣..."); # endif Console . WriteLine (" Hello "); } 19 / 22
  • 20. Speci c features of C# Delegates and lambda expressions public delegate bool Predicate <T>(T obj ); public static void Main( string [] args) { List <string > list = new List <string >{ " Hello ", " World ", "what 's", "up" }; Predicate <String > shortWord ; shortWord = delegate ( string s) { return s. Length < 4;}; shortWord = s => s. Length < 4; list.Find( shortWord ); // or just list.Find(s => s. Length < 4); } 20 / 22
  • 21. Speci c features of C# LINQ public static void Main( string [] args) { var list = new List <string > { " Hello ", " World ", "what 's", "up" }; var result = from item in list select item. Length ; foreach (int i in result ) { Console . WriteLine (i); // -> 5, 5, 6, 2 } } 21 / 22
  • 22. Speci c features of C# More features Operator overloading dynamic pseudo-type yield keyword, similar to Python Extension methods Expression trees Explicit interfaces Partial classes … See http://en.wikipedia.org/wiki/Comparison_of_C_Sharp_and_Java 22 / 22