C# Notes
C# Notes
C# Notes
What is C#
By the help of C# programming language, we can develop different types of secured and
robust applications:
o Window applications
o Web applications
o Distributed applications
o Web service applications
o Database applications etc.
C# is approved as a standard by ECMA and ISO. C# is designed for CLI (Common Language
Infrastructure). CLI is a specification that describes executable code and runtime
environment.
Web applications.
Window applications.
Other Desktop software.
Distributed applications.
Database programs.
Hardware-level programming.
Virus and Malware.
GUI based applications.
Features of C#
There are various features of C# which makes the programming language different and
Programming Features of C#
Java vs C#
There are many differences and similarities between Java and C#. A list of top differences
between Java and C# are given below:
No Java C#
.
C# History
It is based on C++ and Java, but it has many additional extensions used to perform
component oriented programming approach.
C# has evolved much since their first release in the year 2002. It was introduced with .NET
Framework 1.0 and the current version of C# is 7.0. the important features introduced in
each version of C# are given below.
C# Example: Hello World
o Simple Example
o Using System
o Using public modifier
o Using namespace
C# Simple Example
1. class Program
2. {
3. static void Main(string[] args)
4. {
5. System.Console.WriteLine("Hello World!");
6. }
7. }
Output:
Hello World!
Description
Program: is the class name. A class is a blueprint or template from which objects are
created. It can have data members and methods. Here, it has only Main method.
static: is a keyword which means object is not required to access static members. So it
saves memory.
void: is the return type of the method. It does't return any value. In such case, return
statement is not required.
Main: is the method name. It is the entry point for any C# program. Whenever we run the
C# program, Main() method is invoked first before any other method. It represents start up
of the program.
string[] args: is used for command line arguments in C#. While running the C# program,
we can pass values. These values are known as arguments which we can use in the
program.
System.Console.WriteLine("Hello World!"): Here, System is the namespace. Console is
the class defined in System namespace. The WriteLine() is the static method of Console
class which is used to write the text on the console.
1. using System;
2. class Program
3. {
4. static void Main(string[] args)
5. {
6. Console.WriteLine("Hello World!");
7. }
8. }
Output:
Hello World!
We can also specify public modifier before class and Main() method. Now, it can be accessed
from outside the class also.
1. using System;
2. public class Program
3. {
4. public static void Main(string[] args)
5. {
6. Console.WriteLine("Hello World!");
7. }
8. }
Output:
Hello World!
We can create classes inside the namespace. It is used to group related classes. It is used
to categorize classes so that it can be easy to maintain.
1. using System;
2. namespace ConsoleApplication1
3. {
4. public class Program
5. {
6. public static void Main(string[] args)
7. {
8. Console.WriteLine("Hello World!");
9. }
10. }
11. }
Output:
Hello World!
Table of Contents
2. Types of C# Variables
3. Define Variables in C#
4. Initializing Variables in C#
Variables are specific names given to locations in the memory for storing and dealing with
data. Values of a variable can be changed or reused as many times as possible. Every
variable name has a specific type that resolves the size and layout of memory the variable
will hold as well as the range of values that variable within your program can hold. Also,
programmers can determine what type of operations that variable can be applied for.
Types of C# Variables
Type Description
Integral types sbyte, byte, short, ushort, int, uint, long, ulong, and char
C# also permits programmers to define other types of variables and their values like the
Define Variables in C#
For implementing variables in a C# program, you have to define them before using. To do
Syntax:
<data_type> <variable_names>;
Here data_types will be a valid data type (such as char, int, float, double or any other user-
defined data type) of C# and the variable_names will be the set of variable names which
Example:
char s, chrr;
int a, b, c;
double aadharno;
Initializing Variables in C#
A C #variable gets initialized using the assignment operator which is the equal sign. We will
learn more about different operators in the subsequent chapters. The syntax for initializing
a variable in C# is:
Syntax:
<data_type> <variable_name> = value;
Example:
char ch = 'g';
byte b = 22;
double pi = 3.14159;
There is a particular function of the Console class that provides the function Readline() to
take input from the user for storing them in a variable, which is ultimately a named memory
location.
Let us see how to use this function name with any variable to fetch (using the keyboard)
Example:
double sal;
sal = Convert.ToDouble(Console.ReadLine());
In the above code snippet, the first line will declare a variable as a double type. The second
line will first execute the right side which will wait for the user to input any number and will
convert the input values to double using the Convert.ToDouble() and will finally assign that
C# Data Types
As you have already known that while declaring a variable in C#, you have to specify the data type
with the variable name. This is how you tell the compiler what type of data the variable will hold.
Almost all programming language needs the concept of the data type. Since C# is a strongly typed
language, it is essential to inform the compiler what kind of data these memory locations will hold.
A data type specifies the type of data that a variable can store such as integer, floating, character
etc.
The value data types are integer-based and floating-point based. C# language supports both signed
and unsigned literals.
The memory size of data types may change according to 32 or 64 bit operating system.
Let's see the value data types. It size is given according to 32 bit OS.
The reference data types do not contain the actual data stored in a variable, but they contain a
reference to the variables.
If the data is changed by one of the variables, the other variable automatically reflects this change in
value.
The pointer in C# language is a variable, it is also known as locator or indicator that points to an
address of a value.
These types of variables are used for storing the address of any memory location which is of another
type. Pointers are considered a separate data type kind because they do not hold the actual value or
data; rather they are meant to store the actual memory location. The concept of pointers came in C#
Syntax:
type* identifier;
Example:
Symbols used in pointer
Declaring a pointer
int * a; //pointer to int
char * c; //pointer to char
1. 32-bit single (7-digit) precision floating point type declared using the keyword float.
For initializing any variable with a float, you have to mention a 'f' or 'F' after the value. For
example: float g = 62.4f; In case you do not use the suffix, then compiler treats the value
as double.
2. 64-bit (14-15 digit) precision floating point type declared using the keyword double.
For initializing any variable with double, you have to mention a 'd' or 'D' after the value.
For example, double ks =8.403122d;
Decimal Types
There is another type of variable that is used for extensive calculations which are of 128-bit
used for calculating huge economic data. It uses' or 'M' as the suffix; otherwise, the value
will be treated as double.
Character Types
This is used for representing 16-bit Unicode character used for storing a single character.
Keywords are reserved words having special meaning whose meaning is already defined to
the compiler. The keywords in C# are categorized under various groups. These are:
Type Keywords
Modifier Keywords abstract, async, const, event, extern, new, override, partial, readonly,
sealed, static, unsafe, virtual, volatile
Access Modifier public, private, protected, internal
Keywords
Statement if, else, switch, case, do, for, foreach, in, while, break, continue,
Keywords default, goto, return, yield, throw, try, catch, finally, checked,
unchecked, fixed, lock
Operator as, await, is, new, sizeof, typeof, stackalloc, checked, unchecked
Keywords
Type Keywords bool, byte, char, class, decimal, double, enum, float, int, long, sbyte,
short, string, struct, uint, ulong, ushort
Query Keywords from, where, select, group, into, orderby, join, let, in, on, equals, by,
ascending, descending
Some identifiers which have special meaning in context of code are called as Contextual Keywords.
Operators are symbols in a programming language that tells the compiler or interpreter to
perform specific operations on operands for producing the final output or result.
There are six different types of operators provided by C#. These are:
Arithmetic Operators
Logical Operators
Relational Operators
Assignment Operators
Bitwise Operators
Misc Operators
Operator Description
Division The '/' operator is used to divide the first operand by the
second one. Like: x / y.
Modulus The '%' operator is used to return a remainder when the first
operand is divided by the second one. Like: x % y.
Operator Description
Logical AND (&&) Logical AND (&&) operator returns true if both the
conditions/operands satisfy; otherwise returns false.
Logical OR (||) Logical OR (||) operator returns true if anyone or even both
of the conditions/operands satisfy; otherwise returns false.
Logical NOT (!) Logical NOT (!) operator returns true if the condition is not
satisfied; otherwise returns false.
Operator Description
Equal To operator (==) Equal To operator (==) operator is used to check if two
operands are equal or not. If so, it returns true; otherwise
false. Like: 6==6 will return true.
Not Equal To (!=) Not Equal To (!=) operator is used to checking if two
operands are equal or not. If not, it returns true; otherwise
false. Like: 6!=2 will return true.
Greater Than (>) Greater than (>) operator is used to check whether the first
operand is larger than the second. If so, returns true;
otherwise false. Like: 8> four will return true.
Less Than (<) Less Than (<) operator is used to check if the first operand is
smaller than the second. If so, returns true; otherwise false.
Like: 8<1 will return false.
Greater Than Equal To (>=) Greater Than Equal To (>=) operator is used to check if the
first operand is larger than or equal to the second. If so,
returns true; otherwise false. Like: 2>=7 will return false.
Less Than Equal To Less Than Equal To (<=) operator is used to checking if the
first operand is smaller than or equal to the second. If so,
returns true; otherwise false. Like: 6<=6 will return true.
Operator Description
Bitwise AND (&) Bitwise AND (&) operator takes two operands and does AND
operation on every bit of those numbers.
Bitwise OR (|) Bitwise OR (|) operator takes two operands and does OR
operation on every bit of those numbers.
Bitwise XOR (^) Bitwise XOR (^) operator takes two operands and does XOR
operation on every bit of those numbers.
Bitwise Left Shift (<<) Bitwise Left Shift (<<) operator takes two operands and does
left shifting of bits on the two operands and determines the
number of places to shift.
Bitwise Right Shift (>>) Bitwise Right Shift (>>) operator takes two operands and
does right shifting of bits on the two operands and
determines the number of places to shift.
Operator Description
= operator = operator assigns the value of right side operand to its left
side operand. Like: g = s.
+= Operator += Operator adds the value of the variable on the left with
the value on the right which is (result) then assigned to the
variable that is on the left.
/= Operator /= Operator divides the value of the variable on the left with
the value on the right which is (result) then assigned to the
variable that is on the left.
<<= Operator <<= is the left shift assignment operator that will first left
shift the current value of the variable on the left with the
value on the right and the result is then assigned to the
variable that is on the left.
>>= Operator >>= is the right shift assignment operator that will first right
shift the current value of the variable on the left with the
value on the right and the result is then assigned to the
variable that is on the left.
&= Operator &= is the Bitwise AND operator that will first perform a
"Bitwise AND" with the current value of the variable on the
left with the value on the right, and the result is then
assigned to the variable that is on the left.
^= Operator ^= is a Bitwise Exclusive OR operator that will first perform a
"Bitwise Exclusive OR" with the current value of the variable
on the left with the value on the right and the result is then
assigned to the variable that is on the left.
Operator Description
Address of (&) operator: Address of (&) operator is used to return the variable's
address.
Conditional operator (?:) Conditional operator (?:) determines if any condition is true?
If yes then first value: otherwise second value.
C# Control
C# If Example
1. using System;
2. public class IfExample
3. {
4. public static void Main(string[] args)
5. {
6. int num = 10;
7. if (num % 2 == 0)
8. {
9. Console.WriteLine("It is even number");
10. }
11.
12. }
13. }
Output:
It is even number
C# If-else Example
1. using System;
2. public class IfExample
3. {
4. public static void Main(string[] args)
5. {
6. int num = 11;
7. if (num % 2 == 0)
8. {
9. Console.WriteLine("It is even number");
10. }
11. else
12. {
13. Console.WriteLine("It is odd number");
14. }
15.
16. }
17. }
Output:
It is odd number
C# If-else Example: with input from user
In this example, we are getting input from the user using Console.ReadLine() method. It returns string. For
numeric value, you need to convert it into int using Convert.ToInt32() method.
1. using System;
2. public class IfExample
3. {
4. public static void Main(string[] args)
5. {
6. Console.WriteLine("Enter a number:");
7. int num = Convert.ToInt32(Console.ReadLine());
8.
9. if (num % 2 == 0)
10. {
11. Console.WriteLine("It is even number");
12. }
13. else
14. {
15. Console.WriteLine("It is odd number");
16. }
17.
18. }
19. }
Output:
Enter a number:11
It is odd number
Output:
Enter a number:12
It is even number
Output:
Output:
using System;
namespace Dec_making
class IfConditions
if (number < 5)
else
else
}
C# Switch Example
1. using System;
2. public class SwitchExample
3. {
4. public static void Main(string[] args)
5. {
6. Console.WriteLine("Enter a number:");
7. int num = Convert.ToInt32(Console.ReadLine());
8.
9. switch (num)
10. {
11. case 10: Console.WriteLine("It is 10"); break;
12. case 20: Console.WriteLine("It is 20"); break;
13. case 30: Console.WriteLine("It is 30"); break;
14. default: Console.WriteLine("Not 10, 20 or 30"); break;
15. }
16. }
17. }
Output:
Enter a number:
10
It is 10
Output:
Enter a number:
55
Not 10, 20 or 30
class Program
{
static void Main(string[] args)
{
string title = "student";
int grade = 1;
switch( title ) {
case "teacher":
Console.WriteLine("You are a teacher.");
break;
case "student":
Console.WriteLine("You are a student.");
switch( grade ){
case 1:
Console.WriteLine(" You are in pre-school ");
break;
case 2:
Console.WriteLine(" You are in high-school ");
break;
case 3:
Console.WriteLine(" You are in college ");
break;
case 4:
Console.WriteLine(" You are in university ");
break;
default:
Console.WriteLine("Result Unknown");
break;
}
break;
default:
Console.WriteLine(" Office Staff ");
break;
}
Console.Read();
}
}
10. Infinite Loops
The loops in C# are basically of two types depending on their behavior. These are:
1. using System;
2. public class ForExample
3. {
4. public static void Main(string[] args)
5. {
6. for(int i=1;i<=10;i++){
7. Console.WriteLine(i);
8. }
9. }
10. }
Output:
1
2
3
4
5
6
7
8
9
10
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output:
C# While Loop
1. using System;
2. public class WhileExample
3. {
4. public static void Main(string[] args)
5. {
6. int i=1;
7. while(i<=10)
8. {
9. Console.WriteLine(i);
10. i++;
11. }
12. }
13. }
Output:
1
2
3
4
5
6
7
8
9
10
1. using System;
2. public class WhileExample
3. {
4. public static void Main(string[] args)
5. {
6. int i=1;
7. while(i<=3)
8. {
9. int j = 1;
10. while (j <= 3)
11. {
12. Console.WriteLine(i+" "+j);
13. j++;
14. }
15. i++;
16. }
17. }
18. }
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
C# Infinitive While Loop Example:
1. using System;
2. public class WhileExample
3. {
4. public static void Main(string[] args)
5. {
6. while(true)
7. {
8. Console.WriteLine("Infinitive While Loop");
9. }
10. }
11. }
Output:
1. using System;
2. public class DoWhileExample
3. {
4. public static void Main(string[] args)
5. {
6. int i = 1;
7.
8. do{
9. Console.WriteLine(i);
10. i++;
11. } while (i <= 10) ;
12.
13. }
14. }
Output:
1
2
3
4
5
6
7
8
9
10
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
C# Infinitive do-while Loop Example
1. using System;
2. public class WhileExample
3. {
4. public static void Main(string[] args)
5. {
6.
7. do{
8. Console.WriteLine("Infinitive do-while Loop");
9. } while(true);
10. }
11. }
Output:
C# provides programmers with five different types of jump statements. These are:
1. goto
2. break
3. continue
4. return
5. throw
C# Goto Statement
The C# goto statement is also known jump statement. It is used to transfer control to the
other part of the program. It unconditionally jumps to the specified label.
It can be used to transfer control from deeply nested loop or switch case label.
Currently, it is avoided to use goto statement in C# because it makes the program complex.
1. using System;
2. public class GotoExample
3. {
4. public static void Main(string[] args)
5. {
6. ineligible:
7. Console.WriteLine("You are not eligible to vote!");
8.
9. Console.WriteLine("Enter your age:\n");
10. int age = Convert.ToInt32(Console.ReadLine());
11. if (age < 18){
12. goto ineligible;
13. }
14. else
15. {
16. Console.WriteLine("You are eligible to vote!");
17. }
18. }
19. }
Output:
C# Break Statement
The C# break is used to break loop or switch statement. It breaks the current flow of the program at the given
condition. In case of inner loop, it breaks only inner loop.
1. using System;
2. public class BreakExample
3. {
4. public static void Main(string[] args)
5. {
6. for(int i=1;i<=3;i++){
7. for(int j=1;j<=3;j++){
8. if(i==2&&j==2){
9. break;
10. }
11. Console.WriteLine(i+" "+j);
12. }
13. }
14. }
15. }
Output:
1 1
1 2
1 3
2 1
3 1
3 2
3 3
C# Continue Statement
The C# continue statement is used to continue loop. It continues the current flow of the program and skips the
remaining code at specified condition. In case of inner loop, it continues only inner loop.
1. using System;
2. public class ContinueExample
3. {
4. public static void Main(string[] args)
5. {
6. for(int i=1;i<=3;i++){
7. for(int j=1;j<=3;j++){
8. if(i==2&&j==2){
9. continue;
10. }
11. Console.WriteLine(i+" "+j);
12. }
13. }
14. }
15. }
Output:
1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3
return
This jump statement is used to terminate any execution flow in any method and returns the control to calling
method. The value returned by this is optional and when the return type is void, the return statement can be
debarred.
Example:
using System;
class ProgEg {
int a = aa + aa;
return a;
{
int numb = 6;
Output:
Addition is: 12
throw
This is a concept of exception handling in C# which will be covered in the later chapters. But since it also jumps
program flows and executions by creating an object of valid exception class using the new
Example:
using System;
class ProgEg
if (s1 == null)
try
disp(s);
}
catch(Exception exp)
Console.WriteLine( exp.Message );
Output:
Exception Found.
The exception thrown by the throw statement will be taken care of by the catch statement which jumps the
execution flow directly from throw to catch.
C# Function