Python function as first-class objects vs C#

Since I started working with Python, a year ago, I hear some Python developers emphasizing the fact that functions in python are first-class objects, which means you can assign them to variables, pass them as arguments to other functions or methods, store them or even return them by functions. The idea is better understood with an example:

Assign to variables and pass them to functions

output: Boom!

Return a function from other function

output: meow

Store them in data structure

output: Boom!
output:
meow
Boom!

Very simple, right? Now, how could that be done in C#? We can apply the same ideia. Let’s see:

Assign to variables and pass them to functions

output: Boom!

Return a function from other function

output: meow!

Store them in data structure

output: Boom!

Bonus: C# Methods that return a value, Func<>

The main difference between Action and Func is that Func returns a value. In the code below I show a generic list of Func with two static methods and a class Speaker that iterates in that list to call them.

output:
meow
Boom!

We can improve PlaySounds method and add a parameter for the volume. You could also add a function without the need to declare it, by using anonymous method, as the following example:

As you can see both C# and Python have an equivalent structure to do pretty much the same thing. The only difference is that Python has methods (functions the belong to a class) and functions and C# has only methods. I bet that it will change in futures versions of the C# language.

I’m planning to write more posts about the differences and similarities between Python and C#, if you find it interesting please send me suggestions and I’ll be happy to write and help the community.

Leave a comment

search previous next tag category expand menu location phone mail time cart zoom edit close