In: Computer Science
Provide at least three (3) best practices when creating methods in C# and explain why they are "best.
1. Use Proper Naming Conventions, Indentations and
Comments
Proper naming conventions and Indentations are
prefered for consistency and readability of the code. Putting
comments for each block of codes is a good practice, which serves
very handy when one reads the code written by another person or
written by himself/herself long ago.
2. Always Use Properties instead of Public Variables:
Reason behind this is, it makes your code properly
encapsulated in OOPs environment. By using getters & setters,
you can restrict the user directly accessing the member variables.
You can restrict setting the values explicitly thus making your
data protected from accidental changes.
3. Prefer Run-time Constants over Compile time Constants
Run-time constants are those which are evaluated at
the run-time and declared with the keyword “readonly”. On the other
side, compile time constants are static, evaluated at the time of
compilation and declared with the keyword “const”. Compile time
constants (const) must be initialized at the time of declaration
and can’t be changed later. Also, they are limited to only numbers
and strings. The IL replaces the const variable with the value of
it over the whole code and thus it is a bit faster. Whereas, the
Run-time constants (read-only) are initialized in the constructor
and can be changed at different initialization time. The IL
references the read-only variable and not the original value. So,
when you have some critical situation, use const to make the code
run faster. When you need a reliable code, always prefer read-only
variables.
4. Prefer “is” and “as” Operators While Casting
Instead of Explicit casting, use the Implicit casting
to avoid unnecessary exception handlings.