Is the "if" statement considered a method?
Solution 1:
In languages such as C, C++, C#, Java, IF
is a statement implemented as a reserved word, part of the core of the language. In programming languages of the LISP family (Scheme comes to mind) IF
is an expression (meaning that it returns a value) and is implemented as a special form. On the other hand, in pure object-oriented languages such as Smalltalk, IF
really is a method (more precisely: a message), typically implemented on the Boolean
class or one of its subclasses.
Bottom line: the true nature of the conditional instruction IF
depends on the programming language, and on the programming paradigm of that language.
Solution 2:
No, the "if" statement is nothing like a method in C#. Consider the ways in which it is not like a method:
- The entities in the containing block are in scope in the body of an "if". But a method does not get any access to the binding environment of its caller.
- In many languages methods are members of something -- a type, probably. Statements are not members.
- In languages with first-class methods, methods can be passed around as data. (In C#, by converting them to delegates.) "if" statements are not first-class.
- and so on. The differences are myriad.
Now, it does make sense to think of some things as a kind of method, just not "if" statements. Many operators, for instance, are a lot like methods. There's very little conceptual difference between:
decimal x = y + z;
and
decimal x = Add(y, z);
And in fact if you disassemble an addition of two decimals in C#, you'll find that the generated code actually is a method call.
Some operators have unusual characteristics that make it hard to characterize them as methods though:
bool x = Y() && Z();
is different from
bool x = And(Y(), Z());
in a language that has eager evaluation of method arguments; in the first, Z() is not evaluated if Y() is false. In the second, both are evaluated.
Your creation of an "if" method rather begs the question; the implementation is more complicated than an "if" statement. Saying that you can emulate "if" with a switch is like saying that you can emulate a bicycle with a motorcycle; replacing something simple with something far more complex is not compelling. It would be more reasonable to point out that a switch is actually a fancy "if".