Posts

C# Magical Syntax

Introduction This post is an update to an old one on my  old blog  and it was inspired by my latest posts on C# versus Java . You may not have realized that some of the patterns that you’ve been using for ages in your C# programs are based on conventions, rather than on a specific API. What I mean by this is, some constructs in C# are based on some magical methods with well-defined names which are not defined in any base class or interface, but yet just work. Let’s see what they are. Enumerating Collections You are probably used to iterating through collections using the foreach statement. If you are, you may know that foreach actually wraps a call to a method called GetEnumerator , like the one that is defined by the IEnumerable and IEnumerable<T> interfaces. Thus, you might think, the magic occurs because the collection implements one or the two, but you would be wrong: it turns out that in order to iterate through a class using foreach all it takes is that the c...

Java vs C# - Part 2

Introduction This is part two of a series of posts on Java and C#, the first part is available here . This time, I am going to talk about a lot of things that weren’t covered before, and leave some stuff for future posts! I'm covering: Object and collection initialization Casts Methods Operator overloading Attributes/annotations Exceptions Iterations Returning enumerables Lambda functions Expression trees Auto closing blocks Object and Collection Initialization C# offers an interesting syntax for initializing instance properties at the same time a variable is declared, which can be combined with parameterized constructors: MyClass c = new MyClass( "constructor argument" ){ OneProperty = 1, AnotherProperty = "two" }; It also offers a syntax for defining the values of a collection upon declaration, including dictionaries (indexed collections): var list1 = new List< string > { "A" , "B" , "C" }; List< string > list2 = [...