Skip to main content

Posts

Showing posts with the label Type Safety

C# 2.0 - Anonymous Methods

Let's get back to my series on the evolution of the C# language. Everybody is familiar with what a delegate is, right? We know that delegates are a big part of the events system in .Net. We register a method on that delegate ( called handler ) that is invoked when the delegate is invoked. In other words, a delegate simply points to a method. The advantage here is that, as the delegate wraps the method and is an object, we can simply pass it to a method as a parameter! Think about this: This is how we use a delegate in events, for instance. The class exposes the delegate and we register our method to listen it. When the delegate is called inside the class, all the registered methods will be called (because of this, we call it a Multicast Delegate ). This works well, because all you have to do is have a method with the required signature. In the example above, we needed to declare two methods just to make a Console.WriteLine. Isn't this too much? I think it's a bit to...

The evolution of C# Part II - Generics

This is a well discussed matter throughout the internet. Everyone knows about generics, what they do and what they are used for, right? No. There is a variety of reasons why you wouldn't know about generics, and some of them are: You are new in the language You are not new in the language but never cared to learn it Simply because you never learned the basics about generics, it doesn't mean you've never used it. If you recognize this snippet, then you are already dealing with generics: So, what is the advantage of generics? Type safety Generics will allow you to catch the errors at compile time rather than runtime by enforcing the rules of type safety that make C# a statically typed language. This leads to increased productivity because you don't have to run the code to know that something is wrong. For example, if in the snippet above you tried to add a new item of type string, a compiler exception would be thrown. Typically, in C# 1.0, you would use an...