C# pronounce as C Sharp is a one of the best and powerful Object Oriented Programming language. Created by Microsoft first released in year 2002. C# Require .Net Framework Runtime. Till now 8.0 is the latest version of C#.
C# is the best programming language for Console, Web, Desktop and Mobile application development. Now Microsoft also released .Net Core Framework for cross platform support. So C# runs also on Mac OS and Linux.
In this article we will learn following things of C#
01. C# Syntax
02. C# Comments
03. C# Keywords
04. C# Variables & Data Types
05. C# Type Casting
06. C# User Input
07. C# Operators
08. C# Special Characters & preprocessor directives
09. C# Strings
10. C# Conditional Statement if .. else
11. C# Switch statement
12. C# Loops
13. break/continue
14. Array
01. C# Syntax
Minimum code block for running a C# application is given below
using System; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
Code analysis line by line
1: using System; // is used for importing builtin library functionalities. Here also we can import namespace of our class libraries. 3: namespace HelloWorld // namespace groups multiple class into a single group so that if we include that namespace into top of our code with using keyword then it includes all class library of that namespace. 4: { .. } //curly braces {} marks the beginning and the end of a block of code. 5: class HelloWorld // C# is a Object Oriented Programming language. So we must write our method/function inside a class always. 7: static void Main(string[] args) //Every C# program has static Main method. Application starts from that method. 9: Console.WriteLine("Hello World!"); //Will print Hello World! at black console window.
02. C# Comments
Two types of commenting system is supported by c#. Single line comment and multi line comment. Commented line does not execute.
Single line comment start with double front slash //
Multi Line comment starts with /* and ends with */
Example:
// This is an example of single line comment //Console.WriteLine("Hello World"); Console.WriteLine("learnersheaven.com"); Multi Line comment example /* var url = "https://learnersheaven.com"; var html = WebClient.DownloadText(url); */ var webClient = new System.Net.WebClient(); var html = webClient.DownloadString("https://learnersheaven.com");
03. 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 | int | interface | internal |
is | lock | long | namespace |
new | null | object | operator |
out | 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 | virtual | void |
volatile | while |
Contextual keywords
add | alias | ascending |
async | await | by |
descending | dynamic | equals |
from | get | global |
group | into | join |
let | nameof | on |
orderby | partial (type) | partial (method) |
remove | select | set |
unmanaged (generic type constraint) | value | var |
when (filter condition) | where (generic type constraint) | where (query clause) |
yield |
Details uses of each keyword we will learn at another article.
04. C# Variables & Data Types
Variables are containers for storing different types of data. C# supports following primitive data types
int - stores integers (whole numbers), without decimals, such as 103 or -103 double - stores floating point numbers, with decimals, such as 10.99 or -20.99 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes string - stores text, such as "Hello World". bool - stores values with two states: true or false
Variable deceleration syntax
Data type then variable name. If we want to initialize then have to set value by using assignment operator =
int totalValue = 10; double sum = 20.50; char firstChar = 'A'; string firstName = "Learners"; bool isDone = true;
Size of Data Type
Data Type | Size | Description |
---|---|---|
int | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647 |
long | 8 bytes | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
float | 4 bytes | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits |
double | 8 bytes | Stores fractional numbers. Sufficient for storing 15 decimal digits |
bool | 1 bit | Stores true or false values |
char | 2 bytes | Stores a single character/letter, surrounded by single quotes |
string | 2 bytes per character | Stores a sequence of characters, surrounded by double quotes |
05. C# Type Casting
Type casting is required when we want to assign a value of one data type to another type. C# supports two types of type casting.
- Implicit Casting (automatically) – converting a smaller type to a larger type size
char
->int
->long
->float
->double
Example:
int myInt = 12; double myDouble = myInt; // Automatic casting: int to double Console.WriteLine(myInt); // Outputs 12 Console.WriteLine(myDouble); // Outputs 12
- Explicit Casting (manually) – converting a larger type to a smaller size type
double
->float
->long
->int
->char
Example:
double myDouble = 10.78; int myInt = (int) myDouble; // Manual casting: double to int Console.WriteLine(myDouble); // Output 10.78 Console.WriteLine(myInt); // Output 10
06. C# User Input
We have already learned that Console.WriteLine()
is used to output (print) values. Now we will use Console.ReadLine()
to get user input.
/* String input */ // Type your username and press enter Console.WriteLine("Enter username:"); // Create a string variable and get user input from the keyboard and store it in the variable string userName = Console.ReadLine(); // Print the value of the variable (userName), which will display the input value Console.WriteLine("Username is: " + userName); /* Number input */ Console.WriteLine("Enter your age:"); int age = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Your age is: " + age);
07. C# Operators
Operators are used to perform operations on variables and values. In the example below, we use the +
o add together two values:
int x = 100 + 50; // 150 (100 + 50) int sum1 = x + 250; // 400 (150 + 250) int sum2 = x + sum1; // 800 (400 + 400)
C# Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations:
Operator | Name | Description |
---|---|---|
+ | Addition | Adds together two values |
– | Subtraction | Subtracts one value from another |
* | Multiplication | Multiplies two values |
/ | Division | Divides one value from another |
% | Modulus | Returns the division remainder |
++ | Increment | Increases the value of a variable by 1 |
— | Decrement | Decreases the value of a variable by 1 |
C# Assignment operators
Operator | Example | Same As |
---|---|---|
= | x = 5 | x = 5 |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x – 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
%= | x %= 3 | x = x % 3 |
&= | x &= 3 | x = x & 3 |
|= | x |= 3 | x = x | 3 |
^= | x ^= 3 | x = x ^ 3 |
>>= | x >>= 3 | x = x >> 3 |
<<= | x <<= 3 | x = x << 3 |
C# Comparison Operators
Operator | Name | Example |
---|---|---|
== | Equal to | x == y |
!= | Not equal | x != y |
> | Greater than | x > y |
< | Less than | x < y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
C# Logical Operators
Operator | Name | Description | Example |
---|---|---|---|
&& | Logical and | Returns true if both statements are true | x < 5 && x < 10 |
|| | Logical or | Returns true if one of the statements is true | x < 5 || x < 4 |
! | Logical not | Reverse the result, returns false if the result is true | !(x < 5 && x < 10) |
08. C# Special Characters & preprocessor directives
Special characters are predefined, contextual characters that modify the program element (a literal string, an identifier, or an attribute name) to which they are prepended. C# supports the following special characters:
- @, the verbatim identifier character.
- $, the interpolated string character.
Preprocessor directives
#if
#else
#elif
#endif
#define
#undef
#warning
#error
#line
#region
#endregion
#pragma
#pragma warning
#pragma checksum
09. C# Strings
Strings are used for storing text.
A string
variable contains a collection of characters surrounded by double quotes:
string txt = "Hello World"; Console.WriteLine(txt.ToUpper()); // Outputs "HELLO WORLD" Console.WriteLine(txt.ToLower()); // Outputs "hello world" //String Concatenation string firstName = "John "; string lastName = "Wick"; string name = firstName + lastName; Console.WriteLine(name); // Outputs John Wick //String Interpolation string firstName = "John"; string lastName = "Wick"; string name = $"My full name is: {firstName} {lastName}"; Console.WriteLine(name); // Outputs My full name is: John Wick // Special Characters inside string // Special characters are used inside a string after a back slash \ string txt = "We are learning \"C#\" at learnersheaven.com";
10. C# Conditional Statement if .. else
C# supports the usual logical conditions from mathematics:
- Less than: a < b
- Less than or equal to: a <= b
- Greater than: a > b
- Greater than or equal to: a >= b
- Equal to a == b
- Not Equal to: a != b
Syntax:
if (condition) { // block of code to be executed if the condition is True } else{ // block of code to be executed if the condition is False }
Example:
int time = 20; if (time < 10) { Console.WriteLine("Good morning."); } else if (time <= 20) { Console.WriteLine("Good day."); } else { Console.WriteLine("Good evening."); } // Outputs "Good day."
11. C# Switch statement
Use the switch
statement to select one of many code blocks to be executed.
Syntax:
switch(expression) { case x: // code block break; case y: // code block break; default: // code block break; }
Example:
int day = 4; switch (day) { case 1: Console.WriteLine("Monday"); break; case 2: Console.WriteLine("Tuesday"); break; case 3: Console.WriteLine("Wednesday"); break; case 4: Console.WriteLine("Thursday"); break; case 5: Console.WriteLine("Friday"); break; case 6: Console.WriteLine("Saturday"); break; case 7: Console.WriteLine("Sunday"); break; } // Outputs "Thursday" (day 4)
12. C# Loops
C# supports for, while, do while loop and foreach loop.
Syntax:
for(int i = 0; i < 100; i++){ // code block to be execute } int i = 1; while (i < 10) { // code block to be executed i++; }
int j = 0; do { // code block to be executed j++; }while(j < 10) var list = new[]{1,2,3,4,5,6,7,8,9,10}; foreach( var i in list){ // Code block to be execute }
13. C# break/continue
You have already seen the break
statement used in an earlier chapter of this tutorial. It was used to “jump out” of a switch
statement. The break
statement can also be used to jump out of a loop. This example jumps out of the loop when i
is equal to 4
:
for (int i = 0; i < 10; i++) { if (i == 4) { break; } Console.WriteLine(i); }
Example of “continue”:
for (int i = 0; i < 10; i++) { if (i == 4) { continue; } Console.WriteLine(i); }
14. C# Array
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type with square brackets:
string[] cars; string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
Access the Elements of an Array
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; Console.WriteLine(cars[0]); foreach( var c in cars){ Console.WriteLine(c); }
Conclusion
C# is a very powerful and rich programming language. This article has given a brief idea about C# programming language. Thank you for your patience.