It is important that before programming you should know the C# Keywords and Identifiers. You need to know that keywords cannot be used as identifiers and more.
C# Keywords
There are some predefined and reserved words that have special meanings to the compiler. These words are called Keywords. The meaning of the keywords in C# cannot be changed nor can you use them as an identifier. Some of the keywords that you see in a program are int, float, public, etc.
For Example:
//Valid way to write keyword
int phNumber;
long cardNumber;
float @float;
//Invalid way to write keyword
int int;
float double;
There are 79 keywords in C#. All the keywords are written in lowercase.
List of C# keywords
abstract
as
base
bool
break
byte
case
catch
char
checked
class
const
continue
decimal
default
delegate
do
double
else
enum
event
explicit
extern
false
finally
fixed
float
for
foreach
goto
if
implicit
in
in (generic modifier)
int
interface
internal
is
lock
long
namespace
new
null
object
operator
out
out (generic modifier)
override
params
private
protected
public
readonly
ref
return
sbyte
sealed
short
sizeof
stackalloc
static
string
struct
switch
this
throw
true
try
typeof
uint
ulong
unchecked
unsafe
ushort
using
using static
void
volatile
while
Contextual Keywords
Aside from the above keywords, C# has 25 other keywords which are called contextual keywords. They have some specific meaning in a program. Unlike the above 79 regular keywords, contextual keywords are not reserved, they can be used as an identifier.
Identifiers are nothing but the name assigned to the entities such as variables, functions in a program, Union, classes, etc. They are tokens that has a unique name so that they can be uniquely identified in a program.
Example: int number;, number being an identifier.
Rules for Naming an Identifiers:
Identifiers are case-sensitive that is uppercase and lowercase letters are distinct.
The first letter of identifiers must be a letter or underscore or symbols. After the first letter, you can use digits.
White spaces are not allowed.
A keyword cannot be used as an identifier.
Some valid and invalid identifiers:
//Valid
Number
result1
_multiply
S2C
@number
@int
//Invalid
Number-2 //special character '-' is present.
3Sum //started with digit
int // int is a keyword
C# allows us to convert the variables of one data type to another. This conversion referred to as type conversion or type casting. There are various ways to typecast variables, casting can be between a larger size type to a smaller size type or vice-versa.
There are two types of casting in C#:
Implicit Casting (automatic casting): Conversion of smaller type to a larger. char -> int -> long -> float -> double
Explicit Casting (manual casting): Conversion of a larger type to a smaller size type. double -> float -> long -> int -> char
Implicit Casting
For this kind of conversion, there is no need for special syntax. Implicit includes the conversion of a smaller data type to a larger size data type and conversions from derived classes to base classes, so there is no loss of data here. It is also known as Automatic Type Conversion.
Although the two data types need to be compatible with each other that is the numeric data types are compatible with each other but the automatic conversion is not supported to the conversion of numeric type to char or boolean.
//Example
int num1 = 20;
int num2 = 30;
long result;
result = num1 + num2;
As the Implicit conversion is done by the compiler itself, compiler first checks the type compatibility before the conversion. The compatibility is checked in the following order:
byte -> short -> int -> long -> float -> double
The following shows the implicit types of conversion that is supported by C#:
Convert from
Convert to
byte
short, int, long, float, double
short
int, long, float, double
int
long, float, double
long
float, double
float
double
Example of implicit type casting in C# programming.
using System;
namespace Conversion
{
class ImplicitConversion
{
static void Main(string[] args)
{
int num1 = 20;
int num2 = 30;
long result;
result = num1 + num2;
Console.WriteLine("Result: {0}", result);
}
}
}
Output:
Result: 50
Explicit Casting
Explicit conversion is a manual conversion that it is done by the user themselves. We specifically do the explicit conversion to prevent data loss or maybe when the conversion is not succeeded and it is done by using a cast operator ().
This conversion is useful for incompatible data types where above automatic conversion cannot be done. This happens when data of a larger type is converted to data of a smaller type.
long double - > double -> float -> long -> short -> char
Example of explicit type casting in C# programming.
using System;
namespace Conversion
{
class ExplicitConversion
{
public static void Main(String[] args)
{
double db = 165.15;
//Explicit Casting
int num = (int) db;
Console.WriteLine("Value of i: {0}", num);
}
}
}
Output:
Value of i: 165
C# Type Conversion Methods
There are some built-in conversion methods provided by the C#.
Methods
Description
ToBoolean
This converts a type to a Boolean value,
ToByte
It will convert a type to a byte.
ToChar
It will convert a type to a single Unicode character.
ToDateTime
It will convert a type (integer or string type) to date-time structures.
ToDecimal
It will convert a floating-point or integer type to a decimal type.
ToDouble
It will convert a type to a double type.
ToInt16
It will convert a type to a 16-bit integer.
ToInt32
It will convert a type to a 32-bit integer.
ToInt64
It will convert a type to a 64-bit integer.
ToSbyte
It will convert a type to a signed byte type.
ToSingle
It will convert a type to a small floating-point number.
ToString
It will convert a type to a string.
ToType
It will convert a type to a specified type.
ToUInt16
It will convert a type to an unsigned int type.
ToUInt3
It will convert a type to an unsigned long type.
ToUInt64
It will convert a type to an unsigned big integer.
C# program to demonstrate some the built-in type conversion methods
using System;
namespace Conversion
{
class MethodConversion
{
public static void Main(String[] args)
{
int i = 20;
double d = 465.19;
float f = 77.154 F;
//uilt- In Type Conversion
Console.WriteLine(Convert.ToDouble(i));
Console.WriteLine(Convert.ToString(f));
Console.WriteLine(Convert.ToInt32(d));
Console.WriteLine(Convert.ToUInt32(f));
}
}
}
Unary Operators are the Increment and Decrement Operators. They operate on a single operand. They are ++ and -- operators. ++ is used to increase the value by 1 and — is used to decrease the value by 1.
Post-Increment or Post-Decrement: First, the value is used for operation and then incremented or decremented. Represented as a++ or a–.
Pre-Increment Pre-Decrement: Here First the value is incremented or decremented then used for the operation. Represented as ++a or –a.
Example of Unary Operators in C#
using System;
namespace Operator
{
class Unary
{
public static void Main(string[] args)
{
int num = 10, result;
result = ++num;
Console.WriteLine("'++num' Result: {0}", result);
result = --num;
Console.WriteLine("'--num' Result: {0}", result);
}
}
}
Output:
'++num' Result: 11
'--num' Result: 10
Example of Post and Pre Increment operators in C#
using System;
namespace Operator
{
class Unary
{
public static void Main(string[] args)
{
int num = 10;
Console.WriteLine("Post and Pre INCREMENT");
Console.WriteLine((num++));
Console.WriteLine((num));
Console.WriteLine((++num));
Console.WriteLine((num));
Console.WriteLine("Post and Pre DECREMENT");
num = 10;
Console.WriteLine((num--));
Console.WriteLine((num));
Console.WriteLine((--num));
Console.WriteLine((num));
}
}
}
Output:
Post and Pre INCREMENT
10
11
12
12
Post and Pre DECREMENT
10
9
8
8
Relational Operators are used in a program to check the relationship between two operands and accordingly, it returns boolean values, true or false. These operators are used with loops and Decision-Making Statements during condition checking.
List of relational operators in C#:
Operator
Name
Example
==
Equal to.
A == B
!=
Not equal.
A != B
>
Greater than.
A > B
<
Less than.
A < B
>=
Greater than or equal to.
A >= B
<=
Less than or equal to.
A <= B
Example of Relational Operators in C#
using System;
namespace Operators
{
class Relational
{
static void Main(string[] args)
{
int a = 11;
int b = 10;
//Gives true and false value
Console.WriteLine("'==' operator: {0}", a == b);
Console.WriteLine("'<' operator: {0}", a < b);
Console.WriteLine("'>' operator: {0}", a> b);
Console.WriteLine("'!=' operator: {0}", a != b);
/*Now if we change the value*/
a = 5;
b = 20;
Console.WriteLine("'<=' operator: {0}", a <= b);
Console.WriteLine("'>=' operator: {0}", a>= b);
}
}
}
Arithmetic Operators are used to perform mathematical operations on operands such as addition, subtraction, multiplication, division etc.
The following are the Arithmetic Operators
operator
description
+
addition adds two operands. eg, a+b.
-
subtraction subtracts two operands. eg, a-b.
*
multiplication multiplies two operands. eg, a*b.
/
division divides the operand by the second. eg, a/b.
%
modulo returns the remainder when the first operand is divided by the second. For example, a%b.
Example of Arithmetic Operators in C#
using System;
namespace Operators
{
class Arithmetic
{
static void Main(string[] args)
{
int a = 11;
int b = 5;
int result;
result = a + b;
Console.WriteLine("'+' operator, Result: {0}", result);
result = a - b;
Console.WriteLine("'-' operator, Result: {0}", result);
result = a * b;
Console.WriteLine("'*' operator, Result: {0}", result);
result = a / b;
Console.WriteLine("'/' operator, Result: {0}", result);
result = a % b;
Console.WriteLine("'%' operator, Result: {0}", result);
Console.ReadLine();
}
}
}
Operators are the foundation of any programming language, the program is incomplete without the operators as we use them in all of our programs.
Operators are the symbol that performs a specific mathematical or logical operation on operands. Example: Addition : 2 + 3, where 2 and 3 are the operands and + is the operator.
Following are the types of Operators in C#.
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Unary Operators
Bitwise Operators
Ternary or Conditional Operator
Miscellaneous Operators
C# Arithmetic Operators
Arithmetic Operators are used to perform mathematical operations on operands such as addition, subtraction, multiplication, division etc.
operator
description
+
addition adds two operands. eg, a+b.
-
subtraction subtracts two operands. eg, a-b.
*
multiplication multiplies two operands. eg, a*b.
/
division divides the operand by the second. eg, a/b.
%
modulo returns the remainder when the first operand is divided by the second. For example, a%b.
Click Here for example of Arithmetic Operators operators.
C# Assignment Operators
These operators are used in a program to assign a value of the right-hand side to the left-hand side as shown below.
//10 is assign to the variable a
int a = 5;
//the value of b (10) is assigned to a
int b = 10;
int a = b;
int a += 2; //a=a+2
You can combine write in short version such as instead of writing, int a = a+5, you can write it as a += 5.
Following are the list of assignment operators used in C#.
Operator
Description
=
Simple assignment operator, Assigns values from right side operands to left side operand. a = b + c;
+=
Add AND assignment operator, It adds the right operand to the left operand and assigns the result to the left operand. a += b
-=
Subtract AND assignment operator, It subtracts the right operand from the left operand and assigns the result to the left operand. a -= b
*=
Multiply AND assignment operator, It multiplies the right operand with the left operand and assigns the result to the left operand. a *= b
/=
Divide AND assignment operator, It divides left operand with the right operand and assigns the result to the left operand. a /= b
%=
Modulus AND assignment operator, It takes modulus using two operands and assigns the result to the left operand. a %= b
<<=
Left shift AND assignment operator. a <<= 2
>>=
Right shift AND assignment operator. a >>= 2 or a = a >> 2
&=
Bitwise AND assignment operator. a &= 2 or a = a & 2
^=
Bitwise exclusive OR and assignment operator. a ^= 2 or a = a ^ 2
|=
Bitwise inclusive OR and assignment operator. a |= 2 or a = a | 2
Click Here for example of Assignment Operators operators.
C# Relational Operators
These operators are used in a program to check the relationship between two operands and accordingly, it returns boolean values, true or false. These are used with loops and Decision-Making Statements during condition checking.
List of relational operators in C#:
Operator
Name
Example
==
Equal to.
A == B
!=
Not equal.
A != B
>
Greater than.
A > B
<
Less than.
A < B
>=
Greater than or equal to.
A >= B
<=
Less than or equal to.
A <= B
Click Here for example of Relational Operators operators.
C# Logical Operators
These operators are used to compute the logical operation in a program such as &&, || and !. They are used to evaluate the condition.
The following are the C# Logical Operators. Assume X holds the value 1 and Y holds 0
Operator
Description
Example
&& (logical and)
If both the operands are non-zero, then the condition becomes true.
(X && Y) is false
|| (logical or)
If any of the two operands are non-zero, then the condition becomes true.
(X || Y) is true
! (logical not)
Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.
!(X && Y) is true
Click Here for example of Logical Operators operators.
C# Unary Operators
These operators are the Increment and Decrement Operators. They operate on a single operand. They are ++ and -- operators. ++ is used to increase the value by 1 and — is used to decrease the value by 1.
Post-Increment or Post-Decrement: First, the value is used for operation and then incremented or decremented. Represented as a++ or a–.
Pre-Increment Pre-Decrement: Here First the value is incremented or decremented then used for the operation. Represented as ++a or –a.
Click Here for example of Unary Operators operators.
C# Bitwise Operators
Bitwise operators are used to perform a bit-level operation on operands. They are used in testing, setting, or shifting the actual bits in a program.
You can see the truth table below.
p
q
p & q
p | q
p ^ q
~p
0
0
0
0
0
1
0
1
0
1
1
1
1
1
1
1
0
0
1
0
0
1
1
0
Below are the list of Bitwise operators:
Operators
Name of operators
&
Bitwise AND
|
Bitwise OR
^
Bitwise XOR
~
Bitwise complement
<<
Shift left
>>
Shift right
Click Here for example of Bitwise Operators operators.
C# Ternary or Conditional Operator (?:)
It is a short-hand version of the if-else statement that operates on three operands. The ternary operator (or Conditional operator) returns a true or false after checking the condition.
Syntax of ternary operator:
//syntax
condition ? expression1 : expression2;
Explanation:
condition: It checks the condition for a true or false value.
expression1: If the condition is true expression1 is evaluated.
expression2: If the condition is false expression2 is evaluated.
Example of Ternary Operator in C#
using System;
namespace Operator
{
class TernaryOperator
{
public static void Main(string[] args)
{
int num = 10;
string result;
result = (num % 2 == 0) ? "Even Number" : "Odd Number";
Console.WriteLine("{0} is {1}", num, result);
}
}
}
Output:
15 is Odd Number
Miscellaneous Operators
Apart from the above operators, there are various other operators used in C# programming and they are:
sizeof()
It returns the size of a variable, constant, array, etc. sizeof is a keyword in C#. Example: sizeof(int); // returns 4
typeof()
Returns the type of a class Example: typeof(StreamReader);
&
This is a pointer operator, used to point the address of a variable, or we can say that it represents the memory address of the operand to which it points. Example: &a;, This points to the actual address of the variable a.
*
This is also a pointer variable, Indirection Operator. It returns the value of the variable that it points to.
is
This operator checks an object is of a certain type. Example: If(mercedes is Car) // checks if Mercedes is an object of the Car class.
as
This operator cast without raising an exception Example: Object ob = new StringReader("World"); StringReader r = ob as StringReader;
Operator Precedence in C#
In a program, there may be an expression that uses more than one operator, in such case operator precedence determines which is to be evaluated first and next.
Let us take an example:
int result = 10 + 5 * 10;
//Output:
60
The output of the above expression is 60 because the precedence of multiplication is higher than the addition. So first (5 * 10) is evaluated and then 10 is added to the result.
The following shows the precedence and associativity of C# operators:
Associativity refers to the direction of the operators to be evaluated first and next. It may be right to left or left to right.
Before we begin further in this tutorial, it is important to know the basic building of C# programming. You need to have the basic knowledge on what C# program structure contain of.
C# Program Structure
Let us check the basic program written in C#.
using System;
/* Hello World Program */
namespace HelloWorldApplication
{
public class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
After execution of the above program, following output will be displayed.
Hello World!
Now let us understand each of these parts individually:
using System; This is first-line, “using” is a keyword in C# that is used to include the System namespace in the program. If System is included before in the program, then we do not need to specify a system for accessing the class of this namespace. In the above program, we use the Console without specifying the System.
/* Hello World Program */: This is the comment section of the program. These lines are not included during execution but these are for the programmer to comment on the necessary section as required. It is considered to be good practice for coders. However, you can also use // for single line comment and /*…*/ is used for multiple line comment.
namespace: Next is a namespace, It is the collection of classes that is we can create a class inside the namespace in order to maintain the classes in categories. We need to give that namespace name (above eg:- “HelloWorldApplication”).
public class:public is one of the modifiers used in C#. Making the class public means that it can be accessed from outside the class. class in C# contains all the data and methods used in a program and multiple methods can be created inside the class (above example, Main() is the method inside HelloWorld class).
Main: The main method is an entry point of the program when executed. The execution of the program starts from the Main method.
Console.WriteLine("Hello World!"); The Console class is defined in the namespace as used on first line of the program and WriteLine is the method of the Console class that displays the message on the screen.
{...}: This curly braces signifies the extent of the particular function. The blocks under the { } cannot be used outside the curly braces.
Compilation and Execution of C# Program
Go through the following step to compile and run the C# programs using the command-line.
First, open a text editor(eg notepad) on your computer and write your C# code.
Then, save the file as file_name.cs
Then open a command prompt and go to the directory where you have saved the file.
And on the command prompt type “csc file_name.cs” and press enter to compile your code. If there is no error then the command prompt takes you to the next line and the file_name.exe executable file will be created.
Type file_name toexecute the program.
Then Hello world will be printed on the screen (considering the above code).
C# Basic Syntax
During the program, we use many programming components such as keywords, variables, member function, member variables, etc, which we will be studying in detail in further tutorial.
You can also write the C# program in 4 different ways as shown below.
using System;
class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
3. Using modifier (public)
using System;
public class HelloWorld
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
4. Using namespace
using System;
/* Hello World Program */
namespace HelloWorldApplication
{
public class HelloWorld
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
You can write C# program in any one of the above ways in a program according to your need and your comfortability.