Coding style#
We will introduce code a more meaningful program and introduce coding style along with this program.
Creating a new project#
Use the
sandwich icon to access drop-down menus. Then close your project by clicking
File
->Close Solution
.Use
New Solution
button on the top right of the welcome screen. Similar to your first project create a new project, but use the nameCurrencyConverter
.
A currency converter with input#
Let us finally try a more meaningful program — a currency converter. We will also talk about code style.
Replace Program.cs
with the following:
1using System.Text.Json;var client=new HttpClient ( );
2string json=
3await client.GetStringAsync("https://api.frankfurter.dev/v1/latest?base=DKK");
4var dkk_in_eur = JsonDocument.Parse(json).RootElement.GetProperty("rates").GetProperty("EUR").GetDouble();
5
6Console.WriteLine( $"1 DKK = {dkk_in_eur} EUR");
7Console.Write("Enter amount in DKK: ");
8
9var dkk_amount = Convert.ToDouble(Console.ReadLine());
10var eur_amount = dkk_amount * dkk_in_eur;
11Console.WriteLine($"{dkk_amount} DKK = {eur_amount:F2} EUR");
Run the program using F5. The debugger will be activated and the console will ask you to
Enter amount in DKK
.Enter an amount, e.g.,
100
and then press Enter. DKK amount will be converted to EUR using the exchange rate of today.
Before we talk what the code does in detail, we will talk about code style. Look at the highlighted lines. Does something catch your eye? Think about it some seconds before you continue.
If you have the feeling that the code is not easy to read, then you are on the right track! Some code is harder to read than others and this depends on how the programmer selects variable names, where she puts spaces etc.
When we write ordinary text, then we pay attention that the words that belong to a sentence belong to the same line unless we continue on the next line. Compare the two texts, for example:
The program converts between DKK and EUR.
The
program
converts
between DKK and EUR.
Both text have the same meaning, but the former is more readable. When we write programs we also pay attention to programming style.
- programming style
also known as coding style, are the conventions and patterns used in writing source code, resulting in a consistent and readable code
Some style mistakes in the first lines are:
This may be hard to catch: A typical statement ends with a semicolon
;
. Every statement is typically on a separate line. However we see two statements on line 1.We use spaces around
=
, e.g.,a = b
. Line 1 and 2 do not follow this rule.We don’t leave spaces after a function name and between empty parentheses:
HttpClient()
like in line 1.We typically separate lines that logically do not belong together like in line 1, e.g.,:
using System.Text.Json; var client = new HttpClient();
Additionally we could also separate
Console.WriteLine
functions for better readability, as they print something on the terminal.A similar analogy would be writing paragraphs in written text.
Auto-format#
We humans may not behave consistently and make mistakes. Machines typically do more consistent work. Fortunately, editors can automatically format the code for us:
Select all code by pressing Ctrla.
Press Ctrl which opens the context actions.
If you forget it, this is also available in the right-click menu.
Select
Reformat and cleanup
. A new window with the titleSet up Default Cleanup Profile
will pop up.Leave
Built-in Reformat Code
selected and click onSet Up and Run
. The code will be formatted.
You will still see some words underlined with gray wavy lines (also called squiggles). Hover with your mouse pointer on one of them. You will see that it does not match a rule: C# uses camel case for local variable names as a programming style and we should stick to this style for better code readability.
- camel case
the practice of writing phrases without spaces or punctuation and with capitalized words, e.g., YouTube, iPhone.
Now we will fix this.
Click on one of the underlined words and press Ctrl.. A menu will pop up.
Click on
Rename to ...
. Every repetition of this word will be renamed automatically.Repeat the last step until all gray underlines are gone.
Test your program by running it again. The behavior should not change.
Auto-format at each save#
Let us format our code every time we save our file:
Click on
on the top right corner.
Click on
Settings
. Settings window will pop up.Search for
autoformat
.Actions on Save
settings will come up.Activate
Reformat and Cleanup Code
.Click on
Save
.
Warning
Auto format only works when you explicitly save your file using Ctrls, but not when you start debugging using F5, even starting debugging automatically saves your file.
So if you notice that your code is not formatted, try a manual save.