Dear all, welcome to this new tutorial dedicated to C# (CSharp)! In just
15 minutes we will see everything you need to know to realize your
first script!
C# is an object-oriented coding language similar to JavaScript, Java, C++
and Visual Basic, often used to develop desktop, mobile and web
applications, up to games and complex software.
To start coding with C# you need an Integrated Development Enviroment (IDE)
for example Visual Studio, able to compile and debug your code. You can
install its free Community version
including the .NET desktop development needed to run the C# code.
As you open Visual Studio go to Create a new Project and select Console
Application. Set the project name, where to save it and the name for the
solution, intended as the entire C# code you are going to build. As .NET
framework you can leave 3.1 or go for the latest one. This is needed to
run scripts and libraries used while coding with C#.
When you start with a new C# code this usually includes default
instructions (or statements), such as pasting on the Console the classic
'Hello world'. You can also see its basic structure: you get the
namespaces that collect several classes, where each class groups several
statements and operations to perform under {}. In this case you have a
single Example namespace and a single Program class. By default you also
get the Main function, which defines the heart of your C# code.
To paste the 'Hello world' text you simply call the default Console class,
add a period and then WriteLine, with its content under parentheses. This
is a standard C# operation made available by the default System namespace,
declared on top through 'using System'.
The script may include spaces and new lines that improve its readability
without impacting its result. It also needs a ; every time you end any
statement. The code is then saved under a .cs file within the folder path
specified.
To run the script go to Debug, Start Debugging or just press F5.
Now let's see how to work with the variables. These are elements that save
data under a defined name.
Type 'int' to define a variable that must save an integer numerical value
and then type its name (number) with an = to assign the value to save (8).
Always end the statement with ; . You can verify the result with Console.
WriteLine with the variable name as input.
In the same way you can type string to define variables saving text
strings under "", char to save text characters under '' and double to
get numerical numbers with decimals separated by their period. You also
type bool to set boolean variables that can be either true or false.
You can also put together (or concatenate) multiple variables and pieces of
text by using the + operation. In this case you drop text under "" and use
a + sign to continue with the number variable.
To transform lines into comments either use // to comment a single line or
/* and */ to comment entire blocks. All commented lines will turn in green
color and get completely ignored by the compiler. Very useful to
make test without deleting and losing any statement.
On numerical variables you can type + and * to perform additions and
multiplications and - and / for subtractions and divisions. You can also
include parentheses if necessary. Consider that non-integer divisions get
rounded when saved inside an int variable.
With C# you can also save values inserted via Console. If you define a
vacant dataOne variable and assign to it Console.ReadLine with parentheses,
the Console waits for the user input that gets saved inside dataOne when
the Enter key is pressed. This is very useful to make logins and prompts as
long as it is supported by instructions through Console.WriteLine.
On C# you can also make conditionals with IF, used to run statements only
in case a specified condition is true. Type IF, the condition under
parentheses, a greater than b and then all the statements under braces.
You can go on with ELSE to run other statements in case the condition above
is false. Whereas use ELSE IF to specify another condition under
parentheses. Besides the > you can also use <, == to say 'equal', != to
say 'different than' and also logic operations such as double pipe to
perform an OR and && to perform an AND.
Besides the IF you can use the SWITCH cycle to take into account several
possible values (or cases) over a single variable. Type SWITCH, the
variable under parentheses (in this case an integer one) and the braces.
Then type case, the value to match, : and then all the statements to
follow if this case is true. Each case must end with the break line and ; .
You can also include a 'default' case that is run when none of the cases
above is matched.
Whereas if you need to run several statements at a defined number of times
you can implement the FOR cycles. Type FOR and specify three inputs under
parentheses and separated by ; . The first part collects the assignments,
including the i variable used to count the cycles; then you specify the
condition to respect, such as i < 3 and then the increment on such i
counter at the end of each cycle, written as i++ or as an increment of
itself by 1. The FOR statements ( always within {} ) get repeated until the
i counter does not respect the condition any longer, so when i is
equal to 3.
Another useful cycle is the WHILE. This is used in case you need to
repeat statements as long as a condition is true in an undefined number
of times. Type WHILE, its condition under () and then all its statements within
braces. The cycle will repeat until the condition becomes false, so make
sure to evolve the variable within the condition or you will end up in
an endless cycle causing errors.
Similar to WHILE is the DO cycle, with the only difference that you
specify the statements first and then the condition in the end next to
WHILE. This means that you run the statements at least once before
verifying or exiting the cycle.
With C# you can also work with elements called Arrays. These contain an
ordered list of values of the same kind and under the same name.
Define the data type with [] to make an array, then type array name, =
and its content under braces and separated by commas. In this case you
build a string array so you have to add "" on each text value.
At this point you can access to any of the array elements by typing the
array name and its index number under []. Pay attention that this starts
from zero, so you may use the 4 index to catch the 'cake' (fifth) element.
In the same way you can assign other values, make operations or paste data
through a FOR cycle, using the i counter as an index number.
In this case the .length extracts the total number of array elements. This
is an example of function (or method) often used on C# to define complex
and custom operations to perform anywhere in your code.
By default you have the Main method that identifies the script run by the
compiler. After its } you can create another method by typing 'static
void' and its name. The 'void' defines a method that
does not return any output.
Next to the method name you can specify any input under parentheses or
leave them vacant if you do not need any. Then drop all the statements to
run under {}.
You can call this method within the Main script and run its statements by
typing its name and adding its vacant mandatory parentheses.
Whereas if you add inputs you have to define their data kind and separate
them with commas. When you call this method you also have to specify the
values for these inputs in order, in this case 10 for h and 'steps'
for name.
If you want to return any value just type 'static' and define the output
data kind (for example 'double') followed by method name and inputs.
Among the statements you can add the return keyword to save the method
output, for example the product of the two inputs given.
The same System namespace collects loads of ready-made methods you can use.
For example the Array.Sort applied to any array gives its elements listed
by following an alphabetical order; and the Convert. method converts the
data kind of any variable to another.
Please check our video description to learn more about the default methods
inside C#!
When the script starts to be long it is very useful to group statements and
methods under several namespaces, classes and external files.
You can create a new .cs file and save it within the project directory.
Then make a new class on it with 'public class' and its 'Computer' name
within a new namespace called Tech.
Each class has its own variables: if you define a new string variable this
is visible only within its Computer class. Whereas if you type 'public
string' you make the variable visible across all the other classes,
including the ones under the Example namespace. Here you will have to
include the new Tech namespace by typing 'using Tech' above.
Let's use this public 'structure' variable within the objects. The objects
are virtual representations of physical objects with own properties and
data (or fields) derived from the same classes they belong to.
To define a new object inside the Computer class type Computer, the
object name, = and the 'new' keyword with 'Computer' again and its
parentheses. At this point if you type the object name, period and the
variable 'structure' from the Computer class, we will save its data as
a new myRig field. This works as long as you include the Tech namespace
above with its Computer class defined as 'public'.
You can make assignments and concatenations with objects
as seen.
Now that we have seen all the basics, you can understand this simple C#
code. This solution ask name and age with a ReadLine command, calculating
the maximum heart frequency from these, an IF ask the user whether
to show additional data with closing lines in the end.
You can download this sample script in the video description.
When your script is ready you can build the final .exe by going to Build
Solution. With this you can run the entire script without the support of
any IDE such as Visual Studio.
Thanks very much for watching this tutorial! Make sure to check our
video description to get additional help and tips and subscribe to our
channel for other free outstanding tutorials in the future!