I have been searching the web looking for a definition for declarative and imperative programming that would shed some light for me. However, the language used at some of the resources that I have found is daunting – for instance at Wikipedia.
Does anyone have a real-world example that they could show me that might bring some perspective to this subject (perhaps in C#)?
C# – the difference between declarative and imperative paradigm in programming
cdeclarative-programmingimperative-programmingparadigms
Related Topic
- C# – What are the correct version numbers for C#
- C# – the difference between a field and a property
- C# – What’s the difference between the ‘ref’ and ‘out’ keywords
- C# – Difference Between Select and SelectMany
- C# – Calculate difference between two dates (number of days)
- C# – a NullReferenceException, and how to fix it
Best Answer
A great C# example of declarative vs. imperative programming is LINQ.
With imperative programming, you tell the compiler what you want to happen, step by step.
For example, let's start with this collection, and choose the odd numbers:
With imperative programming, we'd step through this, and decide what we want:
Here, we're saying:
With declarative programming, on the other hand, you write code that describes what you want, but not necessarily how to get it (declare your desired results, but not the step-by-step):
Here, we're saying "Give us everything where it's odd", not "Step through the collection. Check this item, if it's odd, add it to a result collection."
In many cases, code will be a mixture of both designs, too, so it's not always black-and-white.