You are on page 1of 9

Basics1

C# file is saved as program.cs

Basic Structure of Program


In [ ]:
using System;

namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}

Example explained

Line 1: using System means that we can use classes from the System namespace.

Line 2: A blank line. C# ignores white space. However, multiple lines makes the code more readable.

Line 3: namespace is used to organize your code, and it is a container for classes and other namespaces.

Line 4: The curly braces {} marks the beginning and the end of a block of code.

Line 5: class is a container for data and methods, which brings functionality to your program. Every line of code that runs in C# must be inside a class.
In our example, we named the class Program.

Line 7: Another thing that always appear in a C# program, is the Main method. Any code inside its curly brackets {} will be executed.

Line 9: Console is a class of the System namespace, which has a WriteLine() method that is used to output/print text. If you omit the using System line,
you would have to write System.Console.WriteLine() to print/output text.
Line 10: Here, System is a namespace, Console is a class within namespace System and WriteLine is method of class Console.

Note: Every C# statement ends with a semicolon ;.

Note: C# is case-sensitive: "MyClass" and "myclass" has different meaning.

For more on Namespace, refer to this from Programmiz - https://www.programiz.com/csharp-programming/namespaces

Output
To output values or print text in C#, you can use the WriteLine() method:

In [9]:
Console.WriteLine("Hello World!");

Hello World!
You can add as many WriteLine() methods as you want. Note that it will add a new line for each method:

In [10]:
Console.WriteLine("Hello World!");
Console.WriteLine("I am Learning C#");
Console.WriteLine("It is awesome!");

Hello World!
I am Learning C#
It is awesome!

In [11]:
Console.WriteLine(3 + 3);

6
There is also a Write() method, which is similar to WriteLine().The only difference is that it does not insert a new line at the end of the output:

In [12]:
Console.Write("Hello World! ");
Console.Write("I will print on the same line.");

Hello World! I will print on the same line.

Comments
In [14]:
// This is a single line comment

Console.WriteLine("Hello World!");

Hello World!

In [16]:
/* This is a
multiline comment */

Console.WriteLine("Hello World!");

Hello World!

Variables
In C#, there are different types of variables (defined with different keywords), for example:

int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
string - stores text, such as "Hello World". String values are surrounded by double quotes
bool - stores values with two states: true or false

To create a variable, you must specify the type and assign it a value

In [17]:
string name = "John";
Console.WriteLine(name);

John

In [18]:
int myNum = 15;
Console.WriteLine(myNum);

15

In [19]:
int myNum;
myNum = 15;
Console.WriteLine(myNum);
15

In [20]:
int myNum = 15;
myNum = 20; // myNum is now 20
Console.WriteLine(myNum);

20

In [21]:
int myNum = 5;
double myDoubleNum = 5.99D;
char myLetter = 'D';
bool myBool = true;
string myText = "Hello";

Console.WriteLine(myNum);
Console.WriteLine(myDoubleNum);
Console.WriteLine(myLetter);
Console.WriteLine(myBool);
Console.WriteLine(myText);

5
5.99
D
True
Hello
Values of variables declared with const cannot be changed.

In [22]:
const int myNum = 15;
myNum = 20; // error

(2,1): error CS0131: The left-hand side of an assignment must be a variable, property or indexer

The const keyword is useful when you want a variable to always store the same value, so that others (or yourself) won't mess up your code. An
example that is often referred to as a constant, is PI (3.14159...).

Note: You cannot declare a constant variable without assigning the value. If you do, an error will occur: A const field requires a value to be provided.

The "+" operator concatenates two strings or two variables.


In [23]:
string name = "John";
Console.WriteLine("Hello " + name);

Hello John

In [24]:
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
Console.WriteLine(fullName);

John Doe

In [27]:
int x = 5, y = 6, z = 50;
Console.WriteLine(x + y + z);

61

In [26]:
int x, y, z;
x = y = z = 50;
Console.WriteLine(x + y + z);

150

The general rules for naming variables are:

Names can contain letters, digits and the underscore character (_).
Names must begin with a letter, an underscore or @ symbol.
Names should start with a lowercase letter and it cannot contain whitespace.
Names are case sensitive ("myVar" and "myvar" are different variables).
Reserved words (like C# keywords, such as int or double) cannot be used as names.

Data Types
In [31]:
long myNum = 15000000000L;
Console.WriteLine(myNum);

float yourNum = 5.75F;


Console.WriteLine(yourNum);

15000000000
5.75
Use float or double?
The precision of a floating point value indicates how many digits the value can have after the decimal point. The precision of float is only six or seven
decimal digits, while double variables have a precision of about 15 digits. Therefore it is safer to use double for most calculations.

In [32]:
float f1 = 35e3F;
double d1 = 12E4D;
Console.WriteLine(f1);
Console.WriteLine(d1);

35000
120000

Best Practices for Naming a Variable

Choose a variable name that make sense. For example, name, age, subject makes more sense than n, a and s.
Use camelCase notation (starts with lowercase letter) for naming local variables. For example, numberOfStudents, age, etc.
Use PascalCase (starts with uppercase letter) for naming public member variables. For example, FirstName, Price, etc.
Use a leading underscore (_) followed by camelCase notation for naming private member variables. For example, _bankBalance, _emailAddress,
etc.

Implicitly typed variables


Alternatively in C#, we can declare a variable without knowing its type using var keyword, such variables are called implicitly typed local variables.
Variables declared using var keyword must be initialized at the time of declaration.
The compiler determines the type of variable from the value that is assigned to the variable. In the above example, value is of type int.
It is important to understand that the var keyword does not mean "variant" and does not indicate that the variable is loosely typed, or late-
bound. It just means that the compiler determines and assigns the most appropriate type.

In [2]:
var i = 0;

Console.WriteLine(i);

0
.

Note on keywords:- Although keywords are reserved words, they can be used as identifiers if @ is added as prefix. For example,
int @void;

The above statement will create a variable @void of type int.

Contextual Keywords
Besides regular keywords, C# has 25 contextual keywords. Contextual keywords have specific meaning in a limited program context and can be used
as identifiers outside that context. They are not reserved words in C#.

You might also like