C# is all-purpose and the robust programming language developed by Microsoft Corporation in the year 2000 as a deadly competitor to Java. It is most popular and a dominating programming language when it comes to both web development as well as desktop application development.
In this C# Tutorial, we will learn the following concepts.
C# Basics
- Introduction to C# Programming Language
- Features of C# Programming Language
- Installation
- C# Program Structure
- Datatypes
- Variables
- Operators
- Loops
- Conditional
- Strings
- Arrays
- Collections
- Structure
- Functions
Introduction to C# Programming Language
Back in the early 90s, Java was the leading programming language for web development, desktop application development and many other fields. Microsoft wanted to come up with a competitor with many advanced features that can leave Java far behind.
It was in the year 2000, Anders Hejlsberg and his Microsoft team in came up with the idea of C# popularly called as C-Sharp. This initiative was approved by the International Standards Organisation (ISO) and the European Computer Manufacturers Association (ECMA). and finally, The C# enters the world of software development.
Features of C# Programming Language
- Object-Oriented Programming Language
Object-Oriented Programming approach is what makes C# sharp to be the most programmer-friendly and easy to develop and maintain programming language.
- Type-Safe Language
The meaning of Type-Safe is that the compiler will be given access only to the memory location that has the permission to execute. This feature improves the code safety to an exponential level.
- Interoperability
The feature of Interoperability makes C# capable enough to do everything that is native to C++ in a more efficient way that can outperform C++ itself.
- Rich Library
C# provides access to multiple numbers of in-built libraries that provide preprogrammed functionalities to decrease the time spent in the development process.
- Scalable and Updateable
C# was designed to be superior amongst the other programming languages. Hence, it is always open to updates and it keeps itself highly scalable with its features.
- Component Oriented
The developers at Microsoft used the component-based approach to develope C#. This is the most predominant development methodology to keep C# highly scalable and updated.
- Structured Language
The Structured Programming approach is preferred during the software development life-cycle as it becomes easy to develop compile and deploy the software compared to the procedure-oriented programming approach.
- Fast
C# Programming happens to be faster in compilation and execution compared to C++ and other programming languages.
Installation
It is proven that Microsoft Visual Studio is the best in class Editor for C# Programming. We will install and Set up Microsoft Visual Studio for executing our C# Programs by following the steps mentioned below:
Step 1: Download Microsoft Visual Studio
Google for the latest version of Visual Studio and download the installer file into your local system and then run the installer file as an administrator.
Step 2: Select the .NET Desktop Development Package
Once you run the Installer, the Visual Studio Editor will be successfully downloaded into your local system, Later a dialogue box will be displayed on your desktop screen asking foe a particular package you need in your system. Here, you need to select the .NET Desktop Development package.
Step 3: Set C# Environment
Once your packages for .NET Development are downloaded, then another dialogue box will be displayed on your screen asking for the development environment you are looking for. Here, you need to select the environment for C#.
Step 4: Create your First Project
Once the environment is set, you are all good to go. Start your Visual Studio and select create new project option in the displayed dialogue box.
You will be redirected to the next dialogue box and there you need to select Class library as .NET Standard as shown below.
In the next dialogue box, you will be asked to Configure your project. Configure it and you are now in the Editor. Write your first program and run it. The output will be successfully displayed on the Command Prompt.
using System; class Edureka { static void Main(string[] args) { Console.WriteLine("Welcome to Edureka!, Happy Learning..!"); } }
//Output:
Let us execute our first C# Program.
C# Program Structure
Now that we have executed our first C# Program, let us understand its structure in detail. A simple C# program has the following parts.
using System; namespace ConsoleApplication1 { public class Edureka { public static void Main(string[] args) { Console.WriteLine("Welcome to Edureka!, Happy Learning..!"); } } }
//Output:
Welcome to Edureka!, Happy Learning..!
- class: class can be generally defined as a keyword that is used to define a class in the C# Program.
- Edureka: It is the name of the Class. Class is often considered as a blueprint that stores the members and methods related to the class.
- Main: Basically is the primary method of the whole C# Program, It acts as the gateway for the control to enter the program. It gets executed before any other method of the program is executed.
- void: This segment of the code is designated to the return type of the method. It can be any Datatype other than void. Void means the method does not have any data getting returned from it.
- static: This is a keyword which says the data members declared are static and a dedicated memory is been allocated to the members declared.
- String[] args: It resembles the command line arguments that we use in our program. While we execute our program, we basically pass some arguments, which will be accepted by the program because of this statement.
- System.Console.WriteLine(“Welcome to Edureka!, Happy Learning..!”); Here, System is the namespace. The console is that the category outlined in System namespace. The WriteLine() is that the static technique of Console category that is employed to write down the text on the console.
Now, let us learn the Datatypes available in C#.
Datatypes
The datatypes in C# are divided into three categories are described below.
Value Datatypes
The Value Datatypes are located in the System.ValueType Library and are always ready to be directly accessed and variables can be directly assigned to a particular value. The Value Datatypes are further classified into two types as shown below:
- Predefined Datatypes
- User-defined Datatypes
Predefined Datatypes: These are the ones which we normally use in our day to day programming. These Datatypes are predefined by the language developers and are kept ready to use for the programmers.
Example:
int, float, char, short double, etc
User-Defined Datatypes: There are situations where we might need to store different values from Datatypes into one single variable. In these cases, the Predefined Datatypes aren’t just enough. User-Defined Datatypes are like customizable datatypes for the user.
Example: Structure, Enum
Datatype | Range of the Memory Allocated | Memory Size |
signed char | -128 to 127 | 1 Byte |
unsigned char | 0 to 127 | 1 Byte |
char | -128 to 127 | 1 Byte |
signed short | -32,768 to 32,767 | 2 Bytes |
unsigned short | 0 to 65,535 | 2 Bytes |
short | -32,768 to 32,767 | 2 Bytes |
signed int | -2,147,483,648 to -2,147,483,647 | 4 Bytes |
unsigned int | 0 to 4,294,967,295 | 4 Bytes |
int | -2,147,483,648 to -2,147,483,647 | 4 Bytes |
signed long | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | 8 Bytes |
unsigned long | 0 to 18,446,744,073,709,551,615 | 8 Bytes |
long | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | 8 Bytes |
float | 1.5 * 10-45 – 3.4 * 1038, (7-digit precision) | 4 Bytes |
double | 5.0 * 10-324 – 1.7 * 10308, (15-digit precision) | 8 Bytes |
decimal | -7.9 * 10-28 – 7.9 * 1028, (28-digit precision) | 16 Bytes |
Pointer Datatype
Pointer Type is a simple datatype. Its functionality is completely similar to the Pointers in C. They are designed to store the address of another pointer.
float* ptr;
Reference Datatypes
The name is self-explanatory. The Reference Datatypes actually do not store the variables, instead, they store the reference value to that particular variable. In other words, they store the address of the actual variable.
The Reference Variables are classified into three different types as mentioned below:
- Object type
The Object Datatype is available in the System.Object Class. The object types can be assigned to the values of the other types, reference types, predefined, user-defined types. But, before assignment values, it requires type conversion.
object abc; abc = 50; //this is called boxing
- Dynamic Type
Dynamic Type variables are designed to store almost all types of values. It is called as Dynamic Type because the type-checking of values takes place in run-time
dynamic x=10;
- String Type
The String Type is available in System.String class. The String Type is designed to store string literals. The String Literals are stored in two forms in two forms
- quoted
- @quoted.
String S = "Edureka";
- The @quoted string literal looks like
@"Edureka";
Now let us understand the variables.
Variables
Variables are the names allotted for the memory location that store certain data given by the user and that data is easily accessible by using the variable name. There are five types of variables available in C#
Type | Example |
Null | Null data |
Boolean | True and False |
Integer | Int, Char, Byte, Short, Long |
Float | Float and Double |
Decimal | Decimal |
Example:
int a, b; double x; float p; char abc;
Rules to be followed to declare variables in C#
- A variable can include alphabets, digits and underscores.
- A variable name can only start with an alphabet or an underscore only.
- Variables can not start with a digit or special character.
- White spaces are not allowed in between the variable name.
- Reserved keywords are restricted from being used as variable names.
Operators
An Operator can be defined as a special symbol that explains the computer to perform a particular Mathematical are a Logical Operation upon a set of variables. C# includes a variety of Operators which are mentioned as below.
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Bitwise Operators
- Assignment Operators
Arithmetic Operators
Operator | Example | Description |
+ | A + B | Adds two Operands |
– | A – B | Substracts two Operands |
* | A * B | Multiples two Operands |
/ | A / B | Divides two Operands |
% | A % B | The remainder of Two Operands |
++ | A++ | Increment Operation |
— | A– | Decrement Operation |
Relational Operators
Operator | Example | Description |
== | A == B | True, if both operands are equal, Else False |
!= | A != B | True, if both operands are not equal, Else False |
> | A > B | True, if A is Greater, Else False |
< | A < B | True, if B is Greater, Else False |
>= | A >= B | True, if A is Greater or equal, Else False |
<= | A <= B | True, id B is Greater equal, Else False |
Logical Operators
Operator | Example | Description |
&& | A && B | True, if both operands are true, Else False |
|| | A || B | True, if one of the operands is true, Else False |
! | A ! B | Reverses the logical state of the operand |
Bitwise Operators
A | B | A & B | A | B | A ^ B |
1 | 1 | 1 | 1 | 0 |
1 | 0 | 0 | 1 | 1 |
0 | 1 | 0 | 1 | 1 |
0 | 0 | 0 | 0 | 0 |
Operator | Example | Description |
~ | (~A) | Binary One’s Complement Operator is unary and has the effect of ‘flipping’ bits. |
<< | A<<2 | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. |
>> | A>>2 | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. |
Assignment Operators
Loops
A loop statement is used for executing a block of statements repeatedly until a particular condition is satisfied. The C# Language consists of the following Loop Statements.
- For Loop
- While Loop
- Do While Loop
For Loop
The for loop is used to execute a particular code segment for multiple times until the given condition is satisfied.
Syntax
for(initialization; condition; increment/decrement) { //code segment }
FlowChart:
Example:
using System; public class ForExample { public static void Main(string[] args) { for (int i = 1; i<= 5; i++) { Console.WriteLine(i); } } }
//Output:
1
2
3
4
5
While Loop
The While loop is used to execute a code segment for multiple numbers of times until a specific condition is satisfied.
Syntax
while(condition) { //code to be executed }
FlowChart:
Example:
using System; namespace Loops { class Program { static void Main(string[] args) { int x = 5; while (x<= 10) { Console.WriteLine("The value of a: {0}", x); x++; } Console.ReadLine(); } } }
//Output:
The value of a: 5
The value of a: 6
The value of a: 7
The value of a: 8
The value of a: 9
The value of a: 10
Do While Loop
Do while loop is completely similar to While Loop but the only difference is that the condition is placed at the end of the loop. Hence, the loop is executed at least for once.
Syntax
do { //code to be executed }while(condition);
FlowChart:
Example:
using System; namespace Edureka { class DoWhileLoop { public static void Main(string[] args) { int i = 1, n = 5, product; do { product = n * i; Console.WriteLine("{0} * {1} = {2}", n, i, product); i++; } while (i<= 10); } } }
//Output:
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Conditional
Conditional statements are used to execute statement or group of statements based on some condition. If the condition is true then C# statements are executed otherwise the next statement will be executed.
Different types of Conditional Statements in C++ Language are as follows:
- If statement
- If-Else statement
- Nested If-else statement
- If-Else If ladder
- Switch statement
If statement
The single if statement in C# language is used to execute the code if a condition is true. It is also called one-way selection statement.
Syntax
if (boolean-expression) { // statements executed if boolean-expression is true }
FlowChart:
Example:
using System; namespace Conditional { class IfStatement { public static void Main(string[] args) { int number = 2; if (number<5) { Console.WriteLine("{0} is less than 5", number); } Console.WriteLine("This statement is always executed."); } } }
//Output:
2 is less than 5
This statement is always executed.
If-Else statement
The if-else statement in C language is used to execute the code if the condition is true or false. It is also called two-way selection statement.
Syntax
if (boolean-expression) { // statements executed if boolean-expression is true } else { // statements executed if boolean-expression is false }
FlowChart:
Example:
using System; namespace Conditional { class IfElseStatement { public static void Main(string[] args) { int number = 12; if (number<5) { Console.WriteLine("{0} is less than 5", number); } else { Console.WriteLine("{0} is greater than or equal to 5", number); } Console.WriteLine("This statement is always executed."); } } }
//Output:
12 is greater than or equal to 5
This statement is always executed.
Nested If-else statement
The nested if-else statement is used when a program requires more than one test expression. It is also called a multi-way selection statement. When a series of the decision are involved in a statement, we use if-else statement in nested form.
Syntax
if (boolean-expression) { if (nested-expression-1) { // code to be executed } else { // code to be executed } } else { if (nested-expression-2) { // code to be executed } else { // code to be executed } }
FlowChart:
Example:
using System; namespace Conditional { class Nested { public static void Main(string[] args) { int first = 7, second = -23, third = 13; if (first > second) { if (first<third) { Console.WriteLine("{0} is the largest", first); } else { Console.WriteLine("{0} is the largest", third); } } else { if (second<third) { Console.WriteLine("{0} is the largest", second); } else { Console.WriteLine("{0} is the largest", third); } } } } }
//Output:
13 is the largest
Else-if Ladder
The if-else-if statement is used to execute one code from multiple conditions. It is also called multipath decision statement. It is a chain of if..else statements in which each if statement is associated with else if statement and last would be an else statement.
Syntax
if(condition1) { // code to be executed if condition1 is true } else if(condition2) { // code to be executed if condition2 is true } else if(condition3) { // code to be executed if condition3 is true } ... else { // code to be executed if all the conditions are false }
FlowChart:
Example:
using System; class Edureka { public static void Main(String[] args) { int i = 20; if (i == 10) Console.WriteLine("i is 10"); else if (i == 15) Console.WriteLine("i is 15"); else if (i == 20) Console.WriteLine("i is 20"); else Console.WriteLine("i is not present"); } }
//Output:
i is 20
Switch statement
Switch statement acts as a substitute for a long if-else-if ladder that is used to test a list of cases. A switch statement contains one or more case labels which are tested against the switch expression. When the expression match to a case then the associated statements with that case would be executed.
Syntax
switch (variable/expression) { case value1: // Statements executed if expression(or variable) = value1 break; case value2: // Statements executed if expression(or variable) = value1 break; ... ... ... ... ... ... default: // Statements executed if no case matches }
FlowChart:
Example:
using System; namespace Conditional { class SwitchCase { public static void Main(string[] args) { char ch; Console.WriteLine("Enter an alphabet"); ch = Convert.ToChar(Console.ReadLine()); switch (Char.ToLower(ch)) { case 'a': Console.WriteLine("Vowel"); break; case 'e': Console.WriteLine("Vowel"); break; case 'i': Console.WriteLine("Vowel"); break; case 'o': Console.WriteLine("Vowel"); break; case 'u': Console.WriteLine("Vowel"); break; default: Console.WriteLine("Not a vowel"); break; } } } }
//Output:
Strings
String Datatype is a member of System.String Class. It is capable to store character type of data. We can perform various operations on Stings such as concatenation, comparison, getting substring, search, trim, replacement and many more.
The analogy of String and string
In C# String and string are equivalent. The word string is a keyword and acts as the System.String class. We can use either of the versions to declare strings.
Syntax:
string s1 = "Edureka";//creating string using string keyword String s2 = "Happy Learning";//creating string using String class
Example:
using System; public class StringExample { public static void Main(string[] args) { string s1 = "Edureka"; char[] ch = { 'C', 's', 'h', 'a', 'r', 'p',' ','T','u','t','o','r','i','a','l' }; string s2 = new string(ch); Console.WriteLine(s1); Console.WriteLine(s2); } }
//Output:
Edureka
Csharp Tutorial
String Methods in C#
Method | Description |
Clone() | Used to return a reference to this instance of String. |
Compare(String, String) | Used to compare two specified String objects. |
Concat(String, String) | Concatenate two specified instances of String. |
Contains(String) | Return a value indicating a specified sub-string |
Copy(String) | Used to create a new instance of String with the same value |
CopyTo(Int, Char[], Int, Int) | Copies characters from a specified position |
Equals(String, String) | Determines that two String objects have the same value. |
Format(String, Object) | Replace one or more format items in a specified string |
IndexOf(String) | Reports the zero-based index of the first occurrence |
Insert(Int32, String) | Returns a new string in which a string is inserted at an index. |
IsInterned(String) | Indicates that this string is in Unicode normalization form C. |
IsNullOrEmpty(String) | Indicates that the specified string is null or an empty string. |
IsNullOrWhiteSpace(String) | Used to indicate whether a specified string is null, empty, |
Join(String, String[]) | Used to concatenate all the elements of a string array |
LastIndexOf(Char) | Reports the zero-based index position of the last character |
LastIndexOfAny(Char[]) | Reports the zero-based index position of the last character |
Remove(Int32) | Returns a new string in which all the characters |
Replace(String, String) | Returns a new string in which all occurrences of a string |
Split(Char[]) | It is used to split a string into substrings |
StartsWith(String) | It is used to check whether the beginning of this string |
Substring(Int32) | It is used to retrieve a substring from this instance. |
ToCharArray() | Copies the characters in this instance to a Unicode array. |
ToString() | It is used to return the instance of String. |
Trim() | Trims the string |
Arrays
Similar to other programming languages, C# does have arrays. Arrays are the simple data structures that are designed to store the same datatype of elements in a contiguous memory location.
C# supports the following Array types.
- Single Dimensional Array
- Multidimensional Array
- Jagged Array
Single Dimensional Array
Single Dimensional Array stores elements in the form of one single row.
Syntax
int[] arr = new int[5];//creating array
Example:
using System; public class ArrayExample { public static void Main(string[] args) { int[] arr = new int[5]; arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50; for (int i = 0; i < arr.Length; i++) { Console.WriteLine(arr[i]); } } }
//Output:
10
20
30
40
50
Multidimensional Array
Multidimensional Array stores elements in the form of multiple dimensions like a matrix and a cube etc.
Syntax
int val = a[2,3];
Example:
using System; namespace ArrayApplication { class MyArray { static void Main(string[] args) { int[,] a = new int[5, 2] { { 0, 0 }, { 1, 2 }, { 2, 4 }, { 3, 6 }, { 4, 8 } }; int i, j; for (i = 0; i < 5; i++) { for (j = 0; j < 2; j++) { Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i, j]); } } Console.ReadKey(); } } }
//Output:
a[0,0] = 0
a[0,1] = 0
a[1,0] = 1
a[1,1] = 2
a[2,0] = 2
a[2,1] = 4
a[3,0] = 3
a[3,1] = 6
a[4,0] = 4
a[4,1] = 8
Jagged Array
Jagged Array is simply an array of arrays.
Example:
using System; namespace ArrayApplication { class MyArray { static void Main(string[] args) { int[][] a = new int[][]{new int[]{0,0},new int[]{1,2}, new int[]{2,4},new int[]{ 3, 6 }, new int[]{ 4, 8 } }; int i, j; for (i = 0; i < 5; i++) { for (j = 0; j < 2; j++) { Console.WriteLine("a[{0}][{1}] = {2}", i, j, a[i][j]); } } Console.ReadKey(); } } }
//Output:
a[0][0] = 0
a[0][1] = 0
a[1][0] = 1
a[1][1] = 2
a[2][0] = 2
a[2][1] = 4
a[3][0] = 3
a[3][1] = 6
a[4][0] = 4
a[4][1] = 8
Collections
Collection can be simply considered as a group of objects collected together so as to apply some functions upon the collected data. The operations that once ca possibly perform on a collection are,
- store object
- update object
- delete object
- retrieve object
- search object, and
- sort object
Types of Collections
There are three different possibilities to work with collections. The three namespaces are mentioned below:
- System.Collections.Generic classes
- System.Collections classes
- System.Collections.Concurrent classes
The System.Collections.Generic Class has the following varieties of classes:
- List
- Stack
- Queue
- LinkedList
- HashSet
- SortedSet
- Dictionary
- SortedDictionary
- SortedList
The System.Collections classes are considered as legacy classes. they include the following classes.
- ArrayList
- Stack
- Queue
- Hashtable
The System.Collections.Concurrent classes namespace provides classes for thread-safe operations. Now multiple threads will not create a problem for accessing the collection items. the classes available in this are,
- BlockingCollection
- ConcurrentBag
- ConcurrentStack
- ConcurrentQueue
- ConcurrentDictionary<tkey, tvalue=””></tkey,>
- Partitioner
- Partitioner
- OrderablePartitioner
List
The list is considered as a data structure available in System.Collection.Generics namespace. It can store and fetch elements. The list is capable to store duplicate elements.
Example:
using System; using System.Collections.Generic; public class Edureka { public static void Main(string[] args) { var names = new List<string>(); names.Add("Sandhya"); names.Add("Arun"); names.Add("Prashanth"); names.Add("Kiran"); foreach (var name in names) { Console.WriteLine(name); } } }
//Output:
Hash Set
C# HashSet category is often accustomed store, take away or read components. It doesn’t store duplicate components. it’s urged to use HashSet category if you’ve got to store solely distinctive components. it’s found in System.Collections.Generic namespace.
Example:
using System; using System.Collections.Generic; public class Edureka { public static void Main(string[] args) { var names = new HashSet<string>(); names.Add("Sunil"); names.Add("Amar"); names.Add("Pujari"); names.Add("Imran"); names.Add("karan"); foreach (var name in names) { Console.WriteLine(name); } } }
//Output:
Sorted Set
C# SortedSet class are often accustomed store, remove or read elements. It maintains ascending order and doesn’t store duplicate elements. it’s prompt to use SortedSet category if you’ve got to store distinctive components and maintain ascending order. it’s found in System.Collections.Generic namespace.
Example:
using System; using System.Collections.Generic; public class Edureka { public static void Main(string[] args) { var names = new SortedSet<string>(); names.Add("Sanjay"); names.Add("Anuradha"); names.Add("Praveen"); names.Add("Ravi"); names.Add("Kajol"); foreach (var name in names) { Console.WriteLine(name); } } }
//Output:
Anuradha
Kajol
Praveen
Ravi
Sanjay
Stack
The stack is a simple collection that follows FILO or first in last out procedure while processing the elements stored in it.
Example:
using System; using System.Collections.Generic; public class Edureka { public static void Main(string[] args) { Stack<string> names = new Stack<string>(); names.Push("Chandan"); names.Push("Pooja"); names.Push("James"); names.Push("Rajesh"); names.Push("kumar"); foreach (string name in names) { Console.WriteLine(name); } Console.WriteLine("Peek element: " + names.Peek()); Console.WriteLine("Pop: " + names.Pop()); Console.WriteLine("After Pop, Peek element: " + names.Peek()); } }
//Output:
kumar
Rajesh
James
Pooja
Chandan
Peek element: kumar
Pop: kumar
After Pop, Peek element: Rajesh
Queue
The queue is completely similar to Stack but the only difference is that the Queue follows FIFO or first in and first out principle while processing the elements stored in it.
Example:
using System; using System.Collections.Generic; public class Edureka { public static void Main(string[] args) { Queue<string> names = new Queue<string>(); names.Enqueue("Srujan"); names.Enqueue("Prajat"); names.Enqueue("John"); names.Enqueue("Raju"); names.Enqueue("Hari"); foreach (string name in names) { Console.WriteLine(name); } Console.WriteLine("Peek element: " + names.Peek()); Console.WriteLine("Dequeue: " + names.Dequeue()); Console.WriteLine("After Dequeue, Peek element: " + names.Peek()); } }
//Output:
Srujan
Prajat
John
Raju
Hari
Peek element: Srujan
Dequeue: Srujan
After Dequeue, Peek element: Prajat
Linked List
The linked list is a dynamic memory collection. The elements in the Linked list are stored by accessing the memory from the heap and storing the elements in a continuous order by linking their addresses.
Example:
using System; using System.Collections.Generic; public class Edureka { public static void Main(string[] args) { var names = new LinkedList<string>(); names.AddLast("Rajat"); names.AddLast("Arun"); names.AddLast("Prakash"); names.AddLast("jay"); names.AddFirst("sai"); foreach (var name in names) { Console.WriteLine(name); } } }
//Output:
Dictionary
Dictionary category uses the idea of the hashtable. It stores values on the premise of the key. It contains distinctive keys solely. By the assistance of key, we will simply search or take away elements. it’s found in System.Collections.Generic namespace.
Example:
using System; using System.Collections.Generic; public class Edureka { public static void Main(string[] args) { Dictionary<string, string> names = new Dictionary<string, string>(); names.Add("1", "Shiva"); names.Add("2", "Prasad"); names.Add("3", "Preetam"); names.Add("4", "Roy"); names.Add("5", "Akash"); foreach (KeyValuePair<string, string> kv in names) { Console.WriteLine(kv.Key + " " + kv.Value); } } }
//Output:
1 Shiva
2 Prasad
3 Preetam
4 Roy
5
Akash
Sorted Dictionary
The SortedDictionary category uses the conception of the hashtable. It stores values on the idea of the key. It contains distinctive keys and maintains ascending order on the idea of the key. By the assistance of key, we will simply search or take away elements. it’s found in System.Collections.Generic namespace.
Example:
using System; using System.Collections.Generic; public class Edureka { public static void Main(string[] args) { SortedDictionary<string, string> names = new SortedDictionary<string, string>(); names.Add("1", "Arun"); names.Add("4", "Vishal"); names.Add("5", "Ramesh"); names.Add("3", "Vidya"); names.Add("2", "Pallavi"); foreach (KeyValuePair<string, string> kv in names) { Console.WriteLine(kv.Key + " " + kv.Value); } } }
//Output:
1 Shiva
2 Prasad
3 Preetam
4 Roy
5 Akash
Sorted List
The SortedList is an array of key/value pairs. It stores values on the premise of the key. The SortedList category contains distinctive keys and maintains ascending order on the premise of the key. By the assistance of key, we are able to simply search or remove elements. it’s found in System.Collections.Generic namespace.
Example:
using System; using System.Collections.Generic; public class Edureka { public static void Main(string[] args) { SortedDictionary<string, string> names = new SortedDictionary<string, string>(); names.Add("1", "Arun"); names.Add("4", "Vishal"); names.Add("5", "Ramesh"); names.Add("3", "Vidya"); names.Add("2", "Pallavi"); foreach (KeyValuePair<string, string> kv in names) { Console.WriteLine(kv.Key + " " + kv.Value); } } }
//Output:
1 Arun
2 Pallavi
3 Vidya
4 Vishal
5 Ramesh
Structure
The structure is a user-defined datatype designed to store multiple elements of the different datatype. The structure is declared using the keyword struct.
Example:
using System; struct Books { public string title; public string author; public string subject; public int book_id; }; public class Edureka { public static void Main(string[] args) { Books Book1; Books Book2; Book1.title = "C# Programming"; Book1.author = "Ramchandra Kumar"; Book1.subject = "C++ Programming Tutorial"; Book1.book_id = 95908978; Book2.title = "Telecom Billing"; Book2.author = "Karan"; Book2.subject = "Telecom Billing Tutorial"; Book2.book_id = 18674900; Console.WriteLine("Book 1 title: {0}", Book1.title); Console.WriteLine("Book 1 Author: {0}", Book1.author); Console.WriteLine("Book 1 subject: {0}", Book1.subject); Console.WriteLine("Book 1 book_id:{0}", Book1.book_id); Console.WriteLine("Book 2 title: {0}", Book2.title); Console.WriteLine("Book 2 Author: {0}", Book2.author); Console.WriteLine("Book 2 subject: {0}", Book2.subject); Console.WriteLine("Book 2 book_id: {0}", Book2.book_id); Console.ReadKey(); } }
//Output:
Book 1 title: C# Programming
Book 1 Author: Ramchandra Kumar
Book 1 subject: C++ Programming Tutorial
Book 1 book_id :95908978
Book 2 title: Telecom Billing
Book 2 Author: Karan
Book 2 subject: Telecom Billing Tutorial
Book 2 book_id: 18674900
Functions
The function is defined as a block of code of the main code. The function is used to execute statements specified in the code block. A function consists of the following components.
- Function name: It is a distinctive name that is used to make a Function call.
- Return type: It specifies the data type of function return value.
- Body: It contains executable statements.
- Access specifier: It specifies function accessibility in the application.
- Parameters: It is a list of arguments that we can pass to the function during the call.
Syntax
<access-specifier><return-type>FunctionName(<parameters>) { // function body // return statement }
Example:
using System; namespace FunctionExample { class Edureka { public string Show(string message) { Console.WriteLine("Inside Show Function"); return message; } static void Main(string[] args) { Edureka program = new Edureka(); string message = program.Show("To Edureka"); Console.WriteLine("Welcome " + message); } } }
//Output:
Inside Show Function
Welcome To Edureka
Functions can be executed in 3 different ways:
- Call by Value
- Call by Reference
- Out Parameter
Call by Value
In C#, value-type parameters are that pass a replica of original value to the function instead of reference. It doesn’t modify the first value. An amendment created in passed value doesn’t alter the particular value. within the following example, we’ve got pass value throughout the call.
Example:
using System; namespace CallByValue { class Edureka { public void Show(int val) { val *= val; Console.WriteLine("The value inside the show function " + val); } static void Main(string[] args) { int val = 50; Edureka program = new Edureka(); Console.WriteLine("Value before calling the function " + val); program.Show(val); Console.WriteLine("Value after calling the function " + val); } } }
//Output:
Value before calling the function 50
The value inside the show function 2500
Value after calling the function 50
Call by Reference
In Call by Reference method, a ref keyword to pass the argument as reference-type. It passes the reference of arguments to the function rather than a copy of the original value. The changes in passed values are permanent and modify the original variable value.
Example:
using System; namespace CallByReference { class Edureka { public void Show(ref int val) { val *= val; Console.WriteLine("The value inside the show function " + val); } static void Main(string[] args) { int val = 50; Edureka program = new Edureka(); Console.WriteLine("Value before calling the function " + val); program.Show(ref val); Console.WriteLine("Value after calling the function " + val); } } }
//Output:
Value before calling the function 50
The value inside the show function 2500
Value after calling the function 2500
Out Parameter
The Out Parameter provides out keyword to pass arguments as out-type. It is like reference-type, except that it does not require the variable to initialize before passing. We must use out keyword to pass the argument as out-type. It is useful when we want a function to return multiple values.
Example:
using System; namespace OutParameter { class Edureka { public void Show(out int val) { int square = 5; val = square; val *= val; } static void Main(string[] args) { int val = 50; Edureka program = new Edureka(); Console.WriteLine("Value before passing out variable " + val); program.Show(out val); Console.WriteLine("Value after recieving the out variable " + val); } } }
//Output:
Value before passing out variable 50
Value
after recieving the out variable 25
Now let us move to Object-oriented programming
Object-Oriented Programming
Object-oriented programming System is a programming paradigm based on the concept of objects that contain data members and methods related to them. The primary purpose of object-oriented programming is to increase the flexibility and maintainability of programs
Features of object-oriented programming:
- It emphasis more on data rather than procedure.
- The programs are divided into objects thus making it easy to work with.
- Data structures are designed in such a way that they characterize the objects.
- Functions that work on the data of an object are placed together in the data structure.
- Data is hidden and cannot be accessed by external functions without permission.
- Communication between objects can take place with the help of functions.
- Adding new data and functions has become easy.
- Follows the bottom-up approach in program design.
The Object-Oriented Paradigms in C# are as follows
- Enumeration in C#
- Object-Oriented Programming Approach
- Overloading and Overriding
- Namespace
- File Operations
- Events
- Generics
- Delegates
- Reflection
Enumeration in C#
Enum or also called as an enumeration in C# is used to store constant values without having to alter them during the entire execution of a C# Program. It is used to store a set of named constants such as season, days, month, size etc
Example:
using System; public class EnumExample { public enum week { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } public static void Main() { int x = (int)week.Monday; int y = (int)week.Friday; Console.WriteLine("Monday = {0}", x); Console.WriteLine("Friday = {0}", y); } }
//Output:
Object-Oriented Programming Approach
The Object-Oriented style of programming can be achieved by following the methods prescribed below.
Encapsulation
Encapsulation is a method to combine the methods along with their data members.
Example:
using System; namespace Edureka { class Rectangle { public double length; public double width; public double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } } class ExecuteRectangle { static void Main(string[] args) { Rectangle r = new Rectangle(); r.length = 50; r.width = 35; r.Display(); Console.ReadLine(); } } }
//Output:
Abstraction
Abstraction is a method to hide the complex coding part from the user by providing him with only the required information he needs.
Example:
using System; public abstract class Shape { public abstract void draw(); } public class Rectangle : Shape { public override void draw() { Console.WriteLine("drawing rectangle..."); } } public class Circle : Shape { public override void draw() { Console.WriteLine("drawing circle..."); } } public class TestAbstract { public static void Main() { Shape s; s = new Rectangle(); s.draw(); s = new Circle(); s.draw(); } }
//Output:
drawing rectangle...
drawing circle...
Interface
The interface is completely similar to Abstraction. The Functionality of an Interface is to hide the unimportant data from the user and provide him with the only important data he needs.
Example:
using System; public interface Drawable { void draw(); } public class Rectangle : Drawable { public void draw() { Console.WriteLine("drawing rectangle..."); } } public class Circle : Drawable { public void draw() { Console.WriteLine("drawing circle..."); } } public class TestInterface { public static void Main() { Drawable d; d = new Rectangle(); d.draw(); d = new Circle(); d.draw(); } }
//Output:
drawing rectangle...
drawing circle...
Polymorphism
Polymorphism is the combination of “poly” + “morphs” which means many forms. It is a greek word. It means the code segment can take up multiple forms. We have two types of Polymorphism.
- Compile Time Polymorphism
- Run Time Polymorphism
Example:
using System; public class Animal { public string color = "white"; } public class Dog : Animal { public string color = "black"; } public class TestSealed { public static void Main() { Animal d = new Dog(); Console.WriteLine(d.color); } }
//Output:
Inheritance
Inheritance is a process in which one object acquires all the properties and behaviours of its parent object automatically. You can reuse, extend or modify the attributes and behaviours which is defined in other class. the class which inherits the members of another class is called derived class and the class whose members are inherited is called the base class. The derived class is the specialized class for the base class.
Example for Single Level Inheritance
using System; namespace RectangleApplication { class Rectangle { protected double length; protected double width; public Rectangle(double l, double w) { length = l; width = w; } public double GetArea() { return length * width; } public void Display() { Console.WriteLine("Length: {0}", length); Console.WriteLine("Width: {0}", width); Console.WriteLine("Area: {0}", GetArea()); } } class Tabletop : Rectangle { private double cost; public Tabletop(double l, double w) : base(l, w) { } public double GetCost() { double cost; cost = GetArea() * 70; return cost; } public void Display() { base.Display(); Console.WriteLine("Cost: {0}", GetCost()); } } class ExecuteRectangle { static void Main(string[] args) { Tabletop t = new Tabletop(4.5, 7.5); t.Display(); Console.ReadLine(); } } }
//Output:
Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5
Example of Multi-Level Inheritance
using System; namespace InheritanceApplication { class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int height; } public interface PaintCost { int getCost(int area); } class Rectangle : Shape, PaintCost { public int getArea() { return (width * height); } public int getCost(int area) { return area * 70; } } class RectangleTester { static void Main(string[] args) { Rectangle Rect = new Rectangle(); int area; Rect.setWidth(5); Rect.setHeight(7); area = Rect.getArea(); Console.WriteLine("Total area: {0}", Rect.getArea()); Console.WriteLine("Total paint cost: ${0}", Rect.getCost(area)); Console.ReadKey(); } } }
//Output:
Total area: 35
Total paint cost: $2450
Overloading
Overloading is a situation where we have two or members declared using the same name. Overloading is also possible when we declare two or more methods with the same name as well. Let us check examples of both.
Member Overloading
Example:
using System; public class Edureka { public static int add(int a, int b) { return a + b; } public static int add(int a, int b, int c) { return a + b + c; } } public class TestMemberOverloading { public static void Main() { Console.WriteLine(Edureka.add(12, 23)); Console.WriteLine(Edureka.add(12, 23, 25)); } }
//Output:
35
60
Method Overloading
Example:
using System; public class Edureka { public static int add(int a, int b) { return a + b; } public static float add(float a, float b) { return a + b; } } public class TestMemberOverloading { public static void Main() { Console.WriteLine(Edureka.add(12, 23)); Console.WriteLine(Edureka.add(12.4f, 21.3f)); } }
//Output:
35
33.699997
Overriding
Overriding is a situation where child class defines the same method which the parent is defining as well. Let us understand this through a small example.
Example:
using System; public class Edureka { public virtual void eat() { Console.WriteLine("Eating "); } } public class Dog : Edureka { public override void eat() { Console.WriteLine("Eating food"); } } public class Overriding { public static void Main() { Dog d = new Dog(); d.eat(); } }
//Output:
Namespace
The namespace is basically used to handle multiple classes present in the program. The namespace is available in different ways.
- System.Console: Here, the System becomes the namespace
- To access the class of a namespace, we need to use namespacename.classname.
- We can use the using keyword as well.
Example:
using System; using First; using Second; namespace First { public class Edureka { public void sayWelcome() { Console.WriteLine("Welcome To Edureka"); } } } namespace Second { public class Happy_Learning { public void sayWishes() { Console.WriteLine("Happy Learning"); } } } public class Namespace { public static void Main() { Edureka h1 = new Edureka(); Happy_Learning w1 = new Happy_Learning(); h1.sayWelcome(); w1.sayWishes(); } }
//Output:
Welcome To Edureka
Happy Learning
File Operations
The file operations available in C# are as follows:
Operation | Description |
BinaryReader | Reads primitive data from a binary stream. |
BinaryWriter | Writes primitive data in binary format. |
BufferedStream | Temporary storage for a stream of bytes. |
Directory | Helps in manipulating a directory structure. |
DirectoryInfo | Used for performing operations on directories. |
DriveInfo | Provides information for the drives. |
File | Helps in manipulating files. |
FileInfo | Used for performing operations on files. |
FileStream | Used to read from and write to any location in a file. |
MemoryStream | Used for random access to streamed data stored in memory. |
Path | Performs operations on path information. |
StreamReader | Used for reading characters from a byte stream. |
StreamWriter | Is used for writing characters to a stream. |
StringReader | Is used for reading from a string buffer. |
StringWriter | Is used for writing into a string buffer. |
FileMode
The FileMode is an enumerator which defines multiple file opening methods. The members of the FileMode Enumerator are described as follows:
- Append: It opens an existing file and puts the cursor at the end of file, or creates the file if the file does not exist.
- Create: It is designed to create a new file.
- CreateNew: It is designed to specify to the operating system, that it should create a new file.
- Open: It is designed to open an existing file.
- OpenOrCreate: It is designed to specify the operating system that it should open a file if it exists, otherwise it should create a new file.
- Truncate: Truncate opens an existing file and truncates its size to zero bytes.
FileAccess
FileAccess Enumerator is used to gaining access to a particular file. It has the following members.
- Read
- Write
- ReadWrite
FileShare
The Fileshare Enumerator is used to share a particular file. It has the following members.
- Inheritable: Inheritable allows a filehandle to pass an inheritance to the child processes.
- None: None declines sharing of the current file
- Read: Read allows opening the file for reading.
- ReadWrite: ReadWrite allows opening the file for reading and writing.
- Write: Write allows opening the file for writing.
Events
An Event is generally known as an action that is generated by the user. It might be a click of the mouse and even a single keystroke from the keyboard. Similarly, C# programs also have events. The generator of the event is called the publisher and the receiver of the event is called the subscriber.
Publisher
A publisher contains the definition of the event and the delegate. The event-delegate association is defined in this object. A publisher class object invokes the event and it is notified to other objects.
Subscriber
A subscriber accepts the event and provides an event handler. The delegate in the publisher class invokes the method /event handler of the subscriber class.
Example:
using System; namespace Edureka { public delegate string Del(string str); class EventBlock { event Del NewEvent; public EventBlock() { this.NewEvent += new Del(this.WelcomeUser); } public string WelcomeUser(string username) { return "Welcome To Edureka. " + username; } static void Main(string[] args) { EventBlock obj1 = new EventBlock(); string result = obj1.NewEvent("Happy Learning"); Console.WriteLine(result); } } }
//Output:
Welcome To Edureka. Happy Learning
Generics
Generics is a concept of providing the members and methods of a class with place holders in Run-time. We can define Generics using <> brackets. Let us check out the following examples.
Generics in a Class
using System; namespace Edureka { class GenericClass<T> { public GenericClass(T msg) { Console.WriteLine(msg); } } class Program { static void Main(string[] args) { GenericClass<string> gen = new GenericClass<string>("This message is from generic class"); GenericClass<int> genI = new GenericClass<int>(123); GenericClass<char> getCh = new GenericClass<char>('E'); } } }
//Output:
This message is from generic class
123
E
Generics in a Method
using System; namespace Edureka { class GenericClass { public void Show<T>(T msg) { Console.WriteLine(msg); } } class Program { static void Main(string[] args) { GenericClass genC = new GenericClass(); genC.Show("This message is from the generic method"); genC.Show(321); genC.Show('H'); } } }
//Output:
This message is from the generic method
321
H
Delegates
The Delegate acts as a reference to the method. Basically it’s same as a function pointer in C and C++ but far better and type-safe. The Delegate in static method encapsulates method only. While the delegate in the instance method encapsulates both method and instance. The best use of delegate is to use as an event.
Example:
using System; delegate int Calculator(int n); public class Edureka { static int number = 25; public static int add(int n) { number = number + n; return number; } public static int mul(int n) { number = number * n; return number; } public static int getNumber() { return number; } public static void Main(string[] args) { Calculator c1 = new Calculator(add); Calculator c2 = new Calculator(mul); c1(20); Console.WriteLine("After calculator one delegate, the new Number is: " + getNumber()); c2(3); Console.WriteLine("After calculator two delegate, the new Number is: " + getNumber()); } }
//Output:
After calculator one delegate, the new Number is: 45
After calculator two delegate, the new Number is: 135
Reflection
The Reflection is required to obtain the metadata in run-time. The Reference is available in System.Reflection namespace. It requires the following classes to execute.
- Type
- MemberInfo
- ConstructorInfo
- MethodInfo
- FieldInfo
- PropertyInfo
- TypeInfo
- EventInfo
- Module
- Assembly
- AssemblyName
- Pointer
Type class
C# Type class represents type declarations for class types, interface types, enumeration types, array types, value types
Type Properties
A list of important properties of Type classes is mentioned below.
Property | Description |
Assembly | Gets the Assembly for this type. |
AssemblyQualifiedName | Gets the Assembly qualified name for this type. |
Attributes | Gets the Attributes associated with the type. |
BaseType | Gets the base or parent type. |
FullName | Gets the fully qualified name of the type. |
IsAbstract | is used to check if the type is Abstract. |
IsArray | is used to check if the type is Array. |
IsClass | is used to check if the type is Class. |
IsEnum | is used to check if the type is Enum. |
IsInterface | is used to check if the type is Interface. |
IsNested | is used to check if the type is Nested. |
IsPrimitive | is used to check if the type is Primitive. |
IsPointer | is used to check if the type is Pointer. |
IsNotPublic | is used to check if the type is not Public. |
IsPublic | is used to check if the type is Public. |
IsSealed | is used to check if the type is Sealed. |
IsSerializable | is used to check if the type is Serializable. |
MemberType | is used to check if the type is Member type of Nested type. |
Module | Gets the module of the type. |
Name | Gets the name of the type. |
Namespace | Gets the namespace of the type. |
Property | Description |
GetConstructors() | Returns all the public constructors for the Type. |
GetConstructors(BindingFlags) | Returns all the constructors for the Type with specified BindingFlags. |
GetFields() | Returns all the public fields for the Type. |
GetFields(BindingFlags) | Returns all the public constructors for the Type with specified BindingFlags. |
GetMembers() | Returns all the public members for the Type. |
GetMembers(BindingFlags) | Returns all the members for the Type with specified BindingFlags. |
GetMethods() | Returns all the public methods for the Type. |
GetMethods(BindingFlags) | Returns all the methods for the Type with specified BindingFlags. |
GetProperties() | Returns all the public properties for the Type. |
GetProperties(BindingFlags) | Returns all the properties for the Type with specified BindingFlags. |
GetType() | Gets the current Type. |
GetType(String) | Gets the Type for the given name. |
Reflection Examples:
Get Type
Example:
using System; public class GetType { public static void Main() { int a = 10; Type type = a.GetType(); Console.WriteLine(type); } }
//Output:
System.Int32
Finally block example
using System; public class FinalExecption { public static void Main(string[] args) { try { int a = 10; int b = 0; int x = a / b; } catch (Exception e) { Console.WriteLine(e); } finally { Console.WriteLine("Finally block is executed"); } Console.WriteLine("Catch block is executed"); } }
//Output:
System.DivideByZeroException: Attempted to divide by zero.
at FinalExecption.Main(String[] args) in F:C# TutorialC# ProgramsConsoleApp1ConsoleApp1Program.cs:line 10
Finally block is executed
Catch block is executed
System Exception Signature
[SerializableAttribute] [ComVisibleAttribute(true)] public class SystemException : Exception
System Exception Constructors
Constructor | Description |
SystemException() | It is used to initialize a new instance of the SystemException class. |
SystemException (SerializationInfo,StreamingContext) | It is used to initialize a new instance of the SystemException class with serialized data. |
SystemException(String) | It is used to initialize a new instance of the SystemException class with a specified error message. |
SystemException(String,Exception) | It is used to initialize a new instance of the SystemException class with a specified error message and a reference to the inner exception that is the cause of this exception. |
System Exception Properties
Property | Description |
Data | It is used to get a collection of key/value pairs that provide additional user-defined information about the exception. |
HelpLink | It is used to get or set a link to the help file associated with this exception. |
HResult | It is used to get or set HRESULT, a coded numerical value that is assigned to a specific exception. |
InnerException | It is used to get the Exception instance that caused the current exception. |
Message | It is used to get a message that describes the current exception. |
Source | It is used to get or set the name of the application that causes the error. |
StackTrace | It is used to get a string representation of the immediate frames on the call stack. |
TargetSite | It is used to get the method that throws the current exception. |
System Exception Methods
Methods | Description |
Equals(Object) | It is used to check that the specified object is equal to the current object or not. |
Finalize() | It is used to free resources and perform cleanup operations. |
GetBaseException() | It is used to get root exception. |
GetHashCode() | It is used to get the hash code. |
GetObjectData (SerializationInfo,StreamingContext) | It is used to get object data. |
GetType() | It is used to get the runtime type of the current instance. |
MemberwiseClone() | It is used to create a shallow copy of the current Object. |
ToString() | It is used to create and return a string representation of the current exception. |
System Exception Example
using System; namespace CSharpProgram { class SystemExceptionExample { static void Main(string[] args) { try { int[] arr = new int[5]; arr[10] = 25; } catch (SystemException e) { Console.WriteLine(e); } } } }
//Output:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at CSharpProgram.SystemExceptionExample.Main(String[] args) in F:C# TutorialC# ProgramsConsoleApp1ConsoleApp1Program.cs:line 11
1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
10
10