官术网_书友最值得收藏!

Writing proper C#

Lines of code function like sentences, meaning they need to have some sort of separating or ending character. Every line of C#, called a statement, MUST end with a semicolon to separate them for the code compiler to process.

However, there's a catch that you need to be aware of. Unlike the written word we're all familiar with, a C# statement doesn't technically have to be on a single line; whitespace and newlines are ignored by the code compiler. For example, a simple variable could be written like this:

public int firstName = "Harrison";

Alternatively, it could also be written as follows:

public
int
firstName
=
"Harrison";

These two code snippets are both perfectly acceptable to Visual Studio, but the second option is highly discouraged in the software community as it makes code extremely hard to read. The idea is to write your programs as efficiently and clearly as possible.

There will be times when a statement will be too long to reasonably fit on a single line, but those are few and far between. Just make sure that it's formatted in a way someone else could understand, and don't forget the semicolon.

The second formatting rule you need to drill into your coding muscle memory is the use of curly brackets or braces. Methods, classes, and interfaces all need a set of curly brackets after their declaration. We'll talk about each of these in-depth later on, but it's important to get the standard formatting in your head early on. The traditional practice in C# is to include each bracket on a new line, as shown here:

public void MethodName() 
{

}

However, when you create a new script from the Unity Editor or go online to the Unity documentation, you'll see the first curly bracket located on the same line as the declaration:

public void MethodName() {

}

While this isn't something to tear your hair out over, the important thing is to be consistent. "Pure" C# code will always put each bracket on a new line, while C# examples that have to do with Unity and game development will most often follow the second example.

Good, consistent formatting style is paramount when starting in programming, but so is being able to see the fruits of your work. In the next section, we'll talk about how to print out variables and information straight to the Unity console.

主站蜘蛛池模板: 扬州市| 白玉县| 渭源县| 新竹市| 连城县| 平度市| 高淳县| 屏东市| 东至县| 新野县| 白沙| 凤阳县| 岑溪市| 东安县| 大悟县| 建湖县| 清水河县| 台北县| 崇文区| 阿克苏市| 隆昌县| 汝州市| 贵南县| 旬邑县| 三门县| 托里县| 武隆县| 平邑县| 定边县| 河北省| 连平县| 大庆市| 竹北市| 安龙县| 逊克县| 政和县| 绵竹市| 潼南县| 渭源县| 汉中市| 北碚区|