Hi everyone! This article is about the age-old question, Java vs “fill in the blank”, and in our case – C#.
If you are a Java developer, then you love Java, and you spend time arguing with co-workers about why Java is better or at least not worse than their language of choice. These arguments will never end, that’s because there are so many languages out there and every year new languages are created, which claim to be the “Solution to all our problems“.
Today I’m going to share with you some nice features that exist in C#, and Java MUST have them too.
It’s not a question of whether something can’t be solved in a specific language, rather it’s a question of style, preference, readability, maintainability etc. In addition, it’s also a matter of experience and what we are accustomed to. So I’m not going to argue philosophical questions here and focus on my experience of writing code in C# after some practice with Java.
Now, let’s get to some irreplaceable C# features you’d “Kill for” to have in Java:
Generics
C# has real generics, not a last minute add on to keep up with the rest of the world. No type erasure just pure generics. The syntax is roughly the same between the languages and if you can read one, you can likely read/use the other.
The difference is in the implementation. In Java, classes are compiled down to Object and then cast to the actually needed type, but C# implements generics all the way down to the bytecode. Due to this, in C# we have performance improvements, reflection, and deep type safety verification.
Struct(value-type)
In C#, Struct(value-type) syntax is similar to Class(reference-type). It has parameterless constructor generated by the compiler and we can NOT overload such constructor and it does not support inheritance, but can yield significant performance benefits when used correctly. This is because of less memory used by Struct.
Let’s imagine that we have two lists, List<
and List<
and add 100 instances in each of them.
- CLASS: the list will have an array of 100 instances inside, and when there will be no reference to them anymore, the garbage collector will dispose every single class instance to reclaim the memory.
- STRUCT: all our Struct instances are stored inside the list itself and when the list goes out of scope, the garbage collector only needs to dispose ONE SINGLE OBJECT.
Developers at Microsoft recommend using a STRUCT instead of a CLASS only for those types which are smaller than 16 bytes, are immutable, are short-lived and are not frequently boxed.
Under these circumstances, using a STRUCT may also be slightly more efficient than using a CLASS because it will more likely be stored in the stack rather than in the heap.
LINQ + Lambda
In C# there is one very nice language integrated feature, like LINQ, which can do amazing things if compared to Lambda. Mmm… There is so much syntax-sugar in those…
LINQ is inspired from SQL, and the syntax is similar. If you want to get something special from a list, look at the following example.
This is Java 8 (using stream):
[code language=”java” firstline=”0″]
List<String> sortedNames = people.stream()
.map(Person::getName)
.sorted(String::compareToIgnoreCase)
.collect(Collectors.toList());
[/code]
This is LINQ (using query syntax):
[code language=”java” firstline=”0″]
IEnumerable<string> sortedNames = from p in people
orderby p.Name.ToLower()
select p.Name;
[/code]
The result of this statement would be a collection of people’s names, sorted in ascending order. But, wait a minute, let’s combine LINQ with Lambda, what can we get?
This is also LINQ (using method syntax):
[code language=”java” firstline=”0″]
IList<string> sortedNames = people.Select(person => person.Name)
.OrderBy(x => x.ToLower())
.ToList();
[/code]
It’s so easy to write such code and to read it, am I right?
Async/Await
This is a feature that gives you the possibility of doing asynchronous programming. Async/Await increases the performance and responsiveness of your application, particularly when you have long-running operations that do not require blocking the execution of the main thread, and organizes your code in a neat and readable way significantly better than boilerplate code of the traditional thread creation and handling.
How do we use it? Look at the example below.
[code language=”java” firstline=”0″ title=”When returning void:”]
public async Task SomethingAsync()
{
await DoSomethingAsync();
}
[/code]
[code language=”java” firstline=”0″ title=”When returning a result:”]
public async Task<string> SomethingAsync()
{
return await DoSomethingAsync();
}
[/code]
The thing to note here is that when returning a value in an async method you return the inner type (i.e in this case “string”) rather than a Task<
instance.
That’s all that you need to do. The methods will be executed asynchronously. You don’t have to bother anymore about managing Threads with BackgroundWorkers. Cool, right?
Properties and Properties + Lambda
Last but not the least in this article – Properties. You’ve probably already heard about this syntactic-sugar provided by C#, right? OK, I will give you some examples and you’ll understand what I am talking about.
How do you declare getters and setters for an attribute in Java? The most known 7 rows in the history 🙂
Here’s how we do it in C#:
[code language=”java” firstline=”0″]
public class Person
{
public string Name { get; set; }
}
[/code]
One row only? Nice! Would you like to implement your own get and set logic?
[code language=”java” firstline=”0″]
public class Person
{
private string name;
public string Name
{
get { return name; }
set
{
if ("Andrei".Equals(value))
{
Console.WriteLine("I’m happy!");
}
this.name = value;
}
}
}
[/code]
You also can do it in one row using Lambda:
[code language=”java” firstline=”0″]
public bool IsNameEmpty => string.IsNullOrEmpty(Name)
or
public string FullName => FirstName + LastName;
[/code]
Is it not simple enough?
There are so many other features that you should try – “Lazy
Microsoft has been going through a bit of an internal reconstruction and has moved parts of the .NET framework into open source world, even made it runnable on Linux. It’s not all there yet, just the .Net Core, but it’s a start. I also want to mention the new, experimental framework – BLAZOR. In relation with .Net Core, you are able to write websites BACKEND and FRONTEND using ONLY C#. Yeah guys, ONLY C#, forget about JavaScript.
In a few years’ time I believe C# and .NET will be fully compatible with Linux and it may become a very different platform. Until then, you can stick with Java. 😉
By the way, I’ve seen many articles about “What does C# have that Java doesn’t“, or “My experience switching from Java to C#“, and from this perspective, I’m giving you a CHALLENGE – now it’s YOUR turn to try C# and write an article about “Features in Java that C# MUST have“.
Peace!