Declarations
In this lesson, we will learn how to declare and initialize the components of C# a code.
Number of Declarations Per-Line
One declaration per line is recommended since it encourages commenting. In other words:
int level; // indentation level
int size; // size of table
Do not put more than one variable or variables of different types on the same line when declaring them. Avoid:
int a, b; //What is 'a'? What does 'b' stand for?
The above example also demonstrates the drawbacks of non-obvious variable names. Be clear when naming variables.
Initializations
Try to initialize local variables as soon as they are declared. For example:
string name = myObject.Name;
or
int val = time.Hours;
Class and Interface Declarations
When coding C# classes and interfaces, the following formatting rules should be followed:
- No space between a method name and the parenthesis
(
starting its parameter list. - The opening brace
{
appears in the next line after the declaration statement. - The closing brace
}
starts a line by itself indented to match its corresponding opening brace.
For example :
Press + to interact
class MySample : MyClass, IMyInterface{int myInt;public MySample(int myInt){this.myInt = myInt ;}void Inc(){++myInt;}void EmptyMethod(){}}