Blog @nicoschuele.com


Week 30 in Tech

Navigating the corporate speak

I really loved the analysis of Satya Nadella's email to potentially laid-off employees by Lee Hutchinson writing for Ars Technica. This part nails it:

The last sentence takes the anonymous could-be-from-any-company cake, though: Microsoft will "focus on breakthrough innovation that expresses and enlivens... digital work and digital life experiences." If you parse that, it turns out that what the e-mail says is "we will try to sell more things by making good things that people like."

Xcode beta 4

Xcode beta 4 was released. It adds public, internal and private modifiers to the Swift language and corrects many issues.

Brick: a complete beginner course on app development

This week, we announced Brick. It is a web-based course on app development for Mac and iOS with the Swift programming language. Intended for the complete beginner to programming, it is also suitable for seasoned developers wanting to learn the intricacies of developing for the Apple platforms.

Windows Phone going after the low-end market

According to analytics, the best selling Windows Phone are the low-end ones. Microsoft seems to continue with the strategy and announced the Lumia 530, a cut-down version of the Lumia 630.

Apple files a patent for an iTime smartwatch

According to Wired UK, Apple filed a patent for a smartwatch design named iTime. A possible announcement for September?

Amazon announces a $126 million loss in quarterly earnings

The whole quarterly financial breakdown is here. Well, their newly launched physical shopping cart didn't seem to help.

Continuity explained

Very good piece from Ars Technica: Explaining Continuity. If AirDrop, Handoff, iBeacon, etc... are still a black box to you, this article will shed some light.

Yosemite public beta is out

If you feel like bricking your Mac, the Mac OS X 10.10 public beta is out. Get it here. Or maybe, install it on a separate partition or in a VM ;-)


Swift is a great first language for beginners

With Guillaume and Kyra we formed Team Brick in order to teach programming for Apple OS X and iOS using the new Swift language. It is named Brick and it is intended at the complete beginner. No prior programming experience required.

I see a lot of questions online that are a variation of "Is Swift suited as a first language for a complete beginner?". Opinions differ but I personally think it is a great language to learn how to code. Here is why.

Programming, not hacking

First, there's a distinction that needs to be made: hacking bits and pieces together after completing a few video lessons on popular online training outlets in order to quickly produce a MVP is not programming. Understanding what programming is requires a certain amount of theoretical knowledge and becoming a proficient programmer requires to know how to apply these concepts.

With that out of the way, let's continue to see why Swift is an excellent choice for people wanting to seriously learn how to write programs.

Environment

To write code, you need a development environment. The most basic one is composed of a text editor and an interpreter or a compiler. Setting up a proper development environment can sometimes be a pain, especially when one needs to download and configure multiple packages, make sure they are compatible with each other and keep them individually updated. Seasoned programmers don't break a sweat to manage their environment but this is typically a point where novice struggle. Want to know everything required to set up Ruby on Rails on a Mac? Have a look at one of my previous guide and you'll get a sense of all the steps involved.

If you take Ruby and/or Python, two languages heavily recommended to learn how to code, once you are done setting them up, you will also need a certain level of familiarity with the command-line interface. Again, to many beginners, this is quite cryptic. Notice that at that point, you haven't yet started to learn how to code.

Some languages offer what is known as an Integrated Development Environment or IDE for short. It is a special kind of software whose purpose is to ...write software. IDE usually include an editor, a compiler, a debugger and plenty of nice and useful features for coders such as code completion (meaning that you start typing a word and the IDE can autocomplete it). Swift development is done using an IDE. It is made by Apple, it's free and it's named Xcode.

Setting up a Swift development environment is as easy as visiting the Mac App Store, looking for Xcode and clicking on "Install". Done.

Helping hand

Beginners make mistakes. A lot. Whether it comes from a misplaced comma, a bracket that wasn't closed properly or simply from issuing a wrong instruction in the code. Languages such as JavaScript, Ruby or Python are not good at catching these mistakes as you write your code. That is due to their interpreted nature. Most of the time, you'll only know you've made a mistake when you attempt to run your program only to see it fail miserably with a cryptic error message such as Undefined method '' for nil:NilClass. Not super friendly for a beginner, right?

On the other hand, Swift is capable of highlighting such mistakes as you are typing your code. Again, this is due to the language compiled nature and the use of the Xcode IDE. Not only Swift requires you to be very explicit in your instructions, it can also warn you that you are currently typing something that is not quite correct. If it can't catch a mistake as you type, as it sometimes happens, it will happen at compile time before you execute your program and usually issue a relevant and easy to understand error message. This is, in my opinion, more novice-friendly.

Basic programming concepts

As said earlier, becoming a programmer requires to understand a lot of basic concepts. One such concept is known as data types. In a nutshell, it means that a computer must know which type of data you are feeding it: a number, text, dates, etc.

Interpreted languages such as Ruby and Python are quite popular because they effectively abstract such concepts. In theory, this allows for a boost in productivity by not having to care about these but in practice, it often results in sloppily written code that turns out to be difficult to maintain and troubleshoot. For example, a programmer familiar with the concept of data types and the way a computer uses them will be more productive. On the other hand, because these languages abstract the concept, it is difficult to explain it to a novice and then have the novice truly understand what (s)he is doing.

Swift, to some extent, lets you choose if you want to be explicit about data types (type annotation) or if you want the compiler to take care of that for you (type inference). This is excellent for beginners as they are able to grasp the concepts at first and then are given the possibility to take shortcuts.

Advanced concepts

Swift is a very modern language. It features some quite advanced concepts such as closures, generics, extension methods, type inference, functional programming patterns, and many more. A beginner is unlikely to need these at first but as (s)he continues to learn, they'll come in handy in order to craft great apps for the Apple ecosystem without having the need to switch to another language that would allow for more functionalities.

Object-Oriented

Swift is an object-oriented language. Today, most languages are but they implement the object-oriented programming (OOP) concepts differently. A typically bad candidate to learn programming the object-oriented way is JavaScript. There are many advocating JavaScript as a first language but in my opinion, the basic concepts of object-oriented programming are very hard to explain (and understand) using JavaScript.

On the other hand, Swift adheres perfectly to the OOP key characteristics which are polymorphism, encapsulation and inheritance. It makes teaching and understanding the concept of objects in programming quite simple. You can easily translate Cat is an Animal in Swift.

Financial consideration

Everybody learns how to code for a different reason but at some point, many want to benefit from the countless hours spent learning. Swift allows you to jump in a thriving ecosystem by letting you publish (and sell!) your completed apps on the Mac App Store and on the iOS App Store.

The culture associated with other languages (again, Ruby and Python or even the NodeJS platform) is mostly open-source. It is rather rare to see an app written in Ruby being sold (and would even be frown upon). On the other hand, it is common for iOS developers to sell their creations on the App Store.

Soon but not right now, though

There's one caveat, though. Swift is a great first language to learn how to code, yes. But not right now. That is because the language itself is currently in a beta phase and won't be officially released before September 2014. At this moment, the core of the language is still undergoing heavy changes, sometimes weekly. That would make it quite difficult for a novice to start learning it.

When Apple officially releases Swift, if you are still looking at learning how to code, I'd recommend that you consider Swift as your first programming language. Oh, and maybe that you take a look at Brick as we are betting on Swift to teach you how to become a great coder!


Week 29 in Tech

I'm trying a new thing on this blog: the week in tech. News that caught my eyes between Fridays and that I find relevant from a developer's perspective. The intent is to have a short digest which shouldn't take more than 5 minutes to read. If the audience justifies it, I'll make a separate outlet for it. Of course, feedback is welcome!

Microsoft eliminating up to 14% of its workforce

This made the news this week:

Microsoft Corp. said it will eliminate as many as 18,000 jobs, the largest round of cuts in its history, as Chief Executive Officer Satya Nadella integrates Nokia Oyj’s handset unit and slims down the software maker.

Among the first business units to get axed, Xbox Entertainement Studios. That means that there won't be any original shows for Xbox as initially announced by the company.

The full story here.

A new Apple and IBM partnership to focus on the enterprise

Times have changed since the 1984 ad: Apple and IBM announced a new partnership to help bring iOS devices in the enterprise.

The combination will create apps that can transform specific aspects of how businesses and employees work using iPhone and iPad, allowing companies to achieve new levels of efficiency, effectiveness and customer satisfaction—faster and easier than ever before.

The first thing that came to my mind was iAS 400.

Guess what! Tizen-powered phone delayed!

Originally announced for a September 2013 release, the Samsung Z which should be the first Tizen-powered phone has again been delayed by Samsung. No release date announced, though.

Microsoft boasts huge scope for growth to partners

Excerpt from Microsoft keynote at the Worldwide Partner Conference, on Ars Technica:

More broadly, Turner said that Microsoft has just a 14 percent share of all devices when one counts smartphones and tablets alongside PCs, and that this represents a huge opportunity for the company and its partners.

Does that mean that companies with 0% market share have even a larger growth opportunity? Interesting way to present numbers!

Apple publishes a blog on Swift

As stated in the first entry, the only one at this time (emphasis mine):

We have big plans for the Swift language, including improvements to syntax, and powerful new features. And as Swift evolves, we will provide tools in Xcode to help you migrate your source code forward.

This is yet another hint at retiring Objective-C as the first citizen language for any Apple-related development in the future.

Xcode 6 beta 3 available to anyone

Anybody can get Xcode 6 beta 3. No need for a paid developer subscription.

Yet another Apple-bashing ad from Samsung

Not even a month after the wall huggers anti-iPhone ad, Samsung now takes a stab at the iPad with yet another Apple-bashing ad. What if, for a change, Samsung would boast about its unique features without always feeling the need for a comparison with the competition? Stay classy.


Batch convert CRLF to LF

Ever worked with people using Windows machines while you are on Mac or Linux? Have you ever had issues with line endings formatting? Or even worse, reached the infamous Git error:

fatal: CRLF would be replaced by LF in ......

A quick script

So I wrote an absolutely not awesome script that converts DOS CRLF line endings with Unix LF line endings. just save this in a file named crlf2lf:

#! /bin/sh
for x
do
    echo "Converting $x ..."
    tr -d '\015' < "$x" > "convert.$x"
    mv "convert.$x" "$x"
    echo "$x done."
done

Simple! Don't forget to chmod u+x crlf2lf and if you want to use it on all the files within a directory, just do this:

crlf2lf *

...and that's it!

Extend it

I published the script on Github. Not because it's beautiful or complicated but because it would be fun if people would extend it to do more, like make it recursive and so on.

image


Discovering Markdown

I'm late to the party. Very late. 10 years late. Because the latest official release of Markdown dates back to 2004. Recently, I've been spending my nights writing technical documents, with a lot of embedded code and just made the switch from writing them directly in HTML to writing them in Markdown. Here's a brief tutorial on Markdown, how it can help you write faster and my current setup.

Markup

The basic idea behind a markup language is to arrange logically bits and pieces of data, usually text, by annotating them. There are many markup languages such as HTML, LaTex and XML. Markdown is itself a markup language.

Easy to read, easy to write

Markdown was created by Apple-centric blogger John Gruber with contributions from the late Aaron Swartz. The idea behind it is to let writers easily compose texts that would be converted to valid HTML. A text written in Markdown is easy to read and easy to write. Contrary to HTML, elements don't need to be wrapped in opening and closing tags.

Have a look

Let's just compare 3 times the same text. Once in plain text, once in HTML and once in Markdown.

plain text

This is the title
This is a subtitle
The following word should be rendered in italic and this one in bold.
Look at an unordered list:
Item 1
Item 2
Item 3
This is a piece of code that displays <Hello World> in the console:
public static Main(){
Console.WriteLine("<Hello World>");
}
And this is a link to my site.

HTML

<h1>This is the title</h1>

<h2>This is a subtitle</h2>

<p>The following word should be rendered in <em>italic</em> and this one in <strong>bold</strong>.</p>

<p>Look at an unordered list:</p>

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>


<p>This is a piece of code that displays <code>&lt;Hello World&gt;</code> in the console:</p>

<pre><code>public static Main(){
    Console.WriteLine("&lt;Hello World&gt;");
}
</code></pre>

<p>And this is a <a href="http://www.nicoschuele.com">link</a> to my site.</p>

Note the amount of tags needed to render this properly in HTML. Also note that the < character, for example, needs to be converted to &lt; in order to be displayed correctly when wrapped inside <code> tags. If you need to write code samples on a blog, that's a drag.

Markdown

# This is the title

## This is a subtitle

The following word should be rendered in *italic* and this one in **bold**.

Look at an unordered list:

* Item 1
* Item 2
* Item 3

This is a piece of code that displays `<Hello World>` in the console:

    public static Main(){
        Console.WriteLine("<Hello World>");
    }

And this is a [link][1] to my site.

[1]: http://www.nicoschuele.com

Much cleaner, easier to read, faster to write. And you know what? The HTML example above was generated from this same Mardown sample!

The result

And this is the produced output from the Markdown code above:

Output

Different flavors

The vanilla version of Markdown sparked some augmented versions. The most well-known are the Github Flavored Markdown (also known as GFM) and Multimarkdown. They each have their own additions to the basic Markdown syntax, for example, Multimarkdown has the capability to add footnotes.

Even if you are new to Markdown, chances are that you already encountered it. It is used to edit posts on StackOverflow, Reddit and GitHub, to name a few.

What you need

First, you'll need to learn the syntax. It should take you about 30 mins for it. Yup, it's that simple. Have a look at the reference.

Then, all you need is a plain text editor and start writing! Personally, I use a nice free app on OS X called MOU with a dark theme. It as a right pane showing you a live preview of your formatted text. With it you can also copy as HTML and your Markdown text will be stored in HTML format in your clipboard. MOU also allows you to generate formatted PDF directly. I might switch to LightPaper, though, but hadn't yet had the chance to write something significant with it. This is what MOU looks like:

Mou App

Sometimes, when on Windows, for example, I use a free online editor called StackEdit. It has the same features as MOU and can save files to your Dropbox.

Switching

Since I switched to Markdown from HTML to write, I really get my writings done much faster. So yeah, I'm late to the game but I enjoy it nonetheless. I've even modified the editor feature on my blog to use Markdown rather than HTML.


Understanding and implementing events in C#

I previously wrote about how to use delegates in C# and using delegates with anonymous methods. No discussion on delegates would be complete without at least introducing the event model. Let's do just that!

Things happen

Before diving into the intricacies of the code itself, let's just explain what events are. Imagine you have a smartphone and that it rings in your pocket: the ringing notifies you so you can take an appropriate action like answering the call. Well, that is the events model. An object (in this example, the phone) does something: it rings. The action of ringing is said to be an event which is raised (or fired). Another object (you) has subscribed to the event so it can in turn execute the appropriate method (answering). Here, we have two classes: Smartphone which is the publisher and Person which is the subscriber and an event which is Ringed.

Let's write a concrete example. Our publisher will be a class Monster which can Roar(). When the monster roars, it raises the event Roared. We also have a class Kid which will Subscribe() to the Monster.Roared event and execute the method Cry() when the monster roars. Each time the monster roars, we want all the kids to cry. Pretty scary stuff.

Creating a monster

Let's look at the Monster class. For brevity, it only implements a Name property and a Roar method:

public class Monster
{
    public string Name { get; set; }

    public delegate void RoarHandler(object sender, EventArgs e);
    public event RoarHandler Roared;

    public Monster(string name) {
        this.Name = name;
    }

    public void Roar() {
        Console.WriteLine("{0} roars loudly!",this.Name);
        if (Roared != null) {
            Roared(this, EventArgs.Empty);
        }
    }
}

Notice these two lines:

public delegate void RoarHandler(object sender, EventArgs e);
public event RoarHandler Roared;

We first start by declaring a special kind of delegate. It is known as the handler for the event. That is the method (or rather the method contained in the delegate) that will execute when the event is raised. By convention, in .NET, event handlers return void and take two parameters: the sender and the arguments for the events. More on that later. Just know it is a convention for now.

Then, we declare the event itself using the event keyword. It is of type RoarHandler and is called Roared. Again, this is a convention in .NET to name events as an action that has happened such as Clicked, Moved, Printed and so on.

We also have the instance method Roar(). When the monster roars, if any other object subscribed to the Roared event, we want to execute the appropriate RoarHandler containing the subscriber's method to be run.

Let's make kids

With our Monster class created, we now need to create another one that can subscribe to the Roared event. It will be Kid and when a monster roars, the kid will Cry(). Look at the class and I'll comment it after:

public class Kid
{
    public string Name { get; set; }

    public Kid(string name) {
        this.Name = name;
    }

    public void Cry(object monster, EventArgs e) {
        Monster m = monster as Monster;
        string monsterName = m == null ? "Some monster" : m.Name;
        Console.WriteLine("{0} cries because {1} is roaring.",this.Name,m.Name);
    }

    public void Subscribe(Monster m) {
        m.Roared += Cry;
    }
}

Look at the Cry() method signature. Notice something? It matches perfectly the monster RoarHandler delegate. That's because this is how delegates work (but you already know that as you read my previous posts on delegates). That's the method that will be contained within the RoarHandler and executed when the monster Roar(). The implementation of the method is trivial: we just test that the sender can be converted to a Monster object.

There's one more bit of plumbing needed for it to work. We must implement a Subscribe() method so our object can be connected (or subscribed) to the event. Just as with delegates, adding a method to a delegate is done using the += operator.

That's it for our Kid. Let's create a stub to see this in action.

Time to scare the crap out of kids

In our main program, we create a monster, two kids, enable them to hear the monster roaring and then, we have the monster roars loudly so we can see what happens:

class Program
{
    static void Main(string[] args) {
        Monster m = new Monster("Kaiju");
        Kid k1 = new Kid("Tim");
        Kid k2 = new Kid("Jill");

        k1.Subscribe(m);
        k2.Subscribe(m);

        m.Roar();
    }
}

Running the program outputs this to the console:

Kaiju roars loudly!
Tim cries because Kaiju is roaring.
Jill cries because Kaiju is roaring.

Our kids were notified that the monster roared and they started to cry.

This is not finished

That was the basics of the event model in .NET but we can go further. Remember when I talked about using delegates with anonymous methods? We can refactor our Subscribe() method a little bit by using an anonymous method thus removing the need for the Cry() method. This is how the Kid class looks like now:

public class Kid
{
    public string Name { get; set; }

    public Kid(string name) {
        this.Name = name;
    }

    public void Subscribe(Monster m) {
        m.Roared += delegate(object monster, EventArgs e) {
            Monster m2 = monster as Monster;
            string monsterName = m2 == null ? "Some monster" : m2.Name;
            Console.WriteLine("{0} cries because {1} is roaring.", this.Name, m2.Name);
        }; 
    }
}

I just renamed the second m object to m2 to avoid a name collision.

And now with lambda

To go even further, we could replace the delegate in the anonymous method with a lambda expression. That's what the cool kids do today. That's how the Subscribe() method would look:

public void Subscribe(Monster m) {
    m.Roared += (monster, e) => {
        Monster m2 = monster as Monster;
        string monsterName = m2 == null ? "Some monster" : m2.Name;
        Console.WriteLine("{0} cries because {1} is roaring.", this.Name, m2.Name);
    };
}

Have some sugar

There's also some syntactic sugar for declaring the event. In the Monster class, you could just rewrite these two lines:

public delegate void RoarHandler(object sender, EventArgs e);
public event RoarHandler Roared;

...with this one line which says the same but uses a generic method:

public event EventHandler<EventArgs> Roared;

That's because the definition for the System.EventHandler<> delegate is:

public delegate void EventHandler<TEventArgs>(Object sender, TEventArgs e);

Conclusion

That was a short introduction on how .NET implements the event model. Of course, there's much more to it, like replacing EventArgs with your own arguments class and making use of it. This could be the subject of a future post!


Using a Delegate with an Anonymous method in C#

Read the simple explanation od Delegates in C# I wrote previously.

In the this block of code taken from the example, the operation delegate references the existing Add method:

OperationDelegate operation;
if (opsType.ToLower() == "a") {
    operation = Add;
}

If you didn't have the Add method already created, you could create a method on the fly. This is known as an anonymous method. The previous example is rewritten using an anonymous method:

OperationDelegate operation;
if (opsType.ToLower() == "a") {
    operation = delegate(int a, int b) {
        Console.WriteLine("Anonymous addition: {0}", a + b);
    };
}

It is quite important to understand how to assign anonymous methods to delegates even though anonymous methods are not the flavor of choice anymore. They tend to be replaced by lambda expressions but it would be hard to introduce the subject without having seen anonymous methods first.

I will do an introduction to lambda expressions in a future post but for now, I just want to rewrite the example using one so you can see what it would give:

OperationDelegate operation;
if (opsType.ToLower() == "a") {
    operation = (a,b) => Console.WriteLine("Anonymous addition: {0}", a + b);
}

Parameters are on the left of the => operator and the method body goes on the right.


A simple explanation of Delegates in C#

Ask any developer new to C# about what is one of the most difficult concept to grasp and chances are pretty big that you will get "delegates" as an answer. Syntactically, there's nothing hard about them. The difficulty resides in when and how to use one. Let's see a short, simple and trivial example.

Declaring a delegate

To explain it simply, you can say that a delegate is a special type that can hold a reference to a function. A variable containing a function, if you will. People familiar with C++ could compare a delegate to a function to a pointer.

First of all, you need to declare a delegate. Much like a function, you specify a return type and parameters:

namespace DelegateSample
{
  public delegate void OperationDelegate(int a, int b);

  class Program
  {
      static void Main(string[] args) {
         
      }
  }
}

Functions that can be used by the delegate

The next step is to write one or more function that could be referenced by the delegate. If you want a delegate to reference a function, its signature (return type and parameters) must be the same as the delegate signature:

namespace DelegateSample
{
    public delegate void OperationDelegate(int a, int b);

    class Program
    {
        static void Add(int num1, int num2) {
            Console.WriteLine("Addition: {0}", num1 + num2);
        }

        static void Multiply(int someNum1, int someNum2) {
            Console.WriteLine("Multiplication: {0}", someNum1 * someNum2);
        }

        static void Main(string[] args) {
           
        }
    }
}

Putting the delegate to use

Everything is now in place to use our delegate. Let's assume that we create a small console calculation application. We will prompt the user for two numbers and the type of operation he wants to do (inputs check omitted for clarity):

namespace DelegateSample
{
    public delegate void OperationDelegate(int a, int b);

    class Program
    {
        static void Add(int num1, int num2) {
            Console.WriteLine("Addition: {0}", num1 + num2);
        }

        static void Multiply(int someNum1, int someNum2) {
            Console.WriteLine("Multiplication: {0}", someNum1 * someNum2);
        }

        static void Main(string[] args) {
            Console.Write("Enter a number: ");
            int firstNum = int.Parse(Console.ReadLine());
            Console.Write("Enter another one: ");
            int secondNum = int.Parse(Console.ReadLine());

            Console.Write("What type of ops? (A)ddition or (M)ultiplication: ");
            string opsType = Console.ReadLine();
        }
    }
}

Then, we declare a new variable operation of type OperationDelegate. We test our user's input: if he wants an addition, we assign the Add function to the operation variable. If he wants a multiplication, we store the Multiply method. If he makes no choice, we store both methods! Yes, delegates allow you to store more than one function. Both will be executed one after the other. This is known as a multicast delegate. Be aware that when using multicast delegates, you can't rely on which order the functions will be called.

Assigning a function to a delegate, like with any variable, is done using the = operator. To add another function to a delegate, you do it with the += operator. Let's see this:

namespace DelegateSample
{
    public delegate void OperationDelegate(int a, int b);

    class Program
    {
        static void Add(int num1, int num2) {
            Console.WriteLine("Addition: {0}", num1 + num2);
        }

        static void Multiply(int someNum1, int someNum2) {
            Console.WriteLine("Multiplication: {0}", someNum1 * someNum2);
        }

        static void Main(string[] args) {
            Console.Write("Enter a number: ");
            int firstNum = int.Parse(Console.ReadLine());
            Console.Write("Enter another one: ");
            int secondNum = int.Parse(Console.ReadLine());

            Console.Write("What type of ops? (A)ddition or (M)ultiplication: ");
            string opsType = Console.ReadLine();

            OperationDelegate operation;
            if (opsType.ToLower() == "a") {
                operation = Add;
            }
            else if (opsType.ToLower() == "m") {
                operation = Multiply;
            }
            else {
                operation = Add;
                operation += Multiply;
            }
        }
    }
}

Notice: When you assign a function to a delegate variable, you use the function name without its parenthesis nor its parameters. That is because you want to reference it, not execute it.

Executing the delegate

Like any function, you call the delegate by its variable name, passing in the required parameters:

namespace DelegateSample
{
    public delegate void OperationDelegate(int a, int b);

    class Program
    {
        static void Add(int num1, int num2) {
            Console.WriteLine("Addition: {0}", num1 + num2);
        }

        static void Multiply(int someNum1, int someNum2) {
            Console.WriteLine("Multiplication: {0}", someNum1 * someNum2);
        }

        static void Main(string[] args) {
            Console.Write("Enter a number: ");
            int firstNum = int.Parse(Console.ReadLine());
            Console.Write("Enter another one: ");
            int secondNum = int.Parse(Console.ReadLine());

            Console.Write("What type of ops? (A)ddition or (M)ultiplication: ");
            string opsType = Console.ReadLine();

            OperationDelegate operation;
            if (opsType.ToLower() == "a") {
                operation = Add;
            }
            else if (opsType.ToLower() == "m") {
                operation = Multiply;
            }
            else{
                operation = Add;
                operation += Multiply;
            }

            operation(firstNum, secondNum);
        }
    }
}

Result

Executing the above program, using 10, 20 and a as inputs will output the following:

Enter a number: 10
Enter another one: 20
What type of ops? (A)ddition or (M)ultiplication: a
Addition: 30

If instead of a, you'd input b, you'd get the following result because both Add and Multiply would be called:

Enter a number: 10
Enter another one: 20
What type of ops? (A)ddition or (M)ultiplication: b
Addition: 30
Multiplication: 200

And that's it for delegates. It is the most trivial example I could think of.


Displaying posts 1 - 8 of 73 in total




RailsBricks
An app generator I created to speed up Ruby on Rails development. RailsBricks is open-source. By the way, this site was built with RailsBricks!
HowToCode.io
I founded HowToCode.io to teach high quality web development, for free. The aim is to take students from novice to employable.
Trakx
I love lists. I create many and for everything, really. Trakx is built with RailsBricks and is my own list management tool. It is free and anybody can sign up.
qwikGit
Speeding up Git common actions by wrapping them in single switches. For example, to add, commit, merge and then push to a remote repository, just type qgit -cmp instead of a long serie of Git commands.
qwikGem
The main goal of qwikGem is to quickly create the needed boilerplate code and assets to start creating a CLI-style Ruby gem.