C Sharp .NET 4.5 Development
C# .NET 4.5 Overview |
C# is a type safe object oriented language that enables developers to build variety of secure and robust applications to execute on the .NET framework. C# is a modern, general-purpose, object-oriented programming language developed by Microsoft and approved by European Computer Manufacturers Association (ECMA) and International Standards Organization (ISO). C# was developed by Anders Hejlsberg and his team during the development of .Net Framework. User can create Windows client applications, XML web services, distributed components, client – server applications and database applications. C# constructs closely follow traditional high-level languages and has numerous strong programming features that make it powerful and attractive to a number of programmers worldwide.It helps the user to perform all work similar to the C++ application. C# supports encapsulation, inheritance, polymorphism. Pointers, interoperability feature, unsafe code for memory access and other powerful features like Automatic Garbage Collection, Multithreading, asynchronous programming, LINQ and Lambda Expressions, Delegates , Indexers ,Support for Integration with Windows. C# is designed for Common Language Infrastructure (CLI), which consists of the executable code and runtime environment that allows use of various high-level languages on different computer platforms and architectures. Although the.NET Framework originally was developed to run on the Windows operating system, but now there are some alternative versions available that work on other operating systems. Mono is an open-source version of the .NET Framework which includes a C# compiler and runs on several operating systems, including various flavors of Linux and Mac OS |
Release History of c# .Net Framework |
|||
Over the time many versions has been released in different packs of Visual studio which incorporates different versions of c# included on .Net framework version inside Visual studio.Below is the list of important version changes and some useful features - |
|||
Visual Studio Pack |
.Net framework |
C#version |
Description of features |
2002 |
1.0/1.1 |
1.0 |
First version of .net framework and includes basic object oriented features. |
2005 |
2.0 |
2.0 |
C# was packaged with features like Generics (with generic collection) Nullable Types, Support of IPv6 addresses in .net remoting, Nullables, Anonymous methods, Private setters (properties), iterators and Covariance and contravariance were added with new Common Language Runtime version 2.0. . |
2008 |
3.0\3.5 |
3.0 |
The major changes incorporated in this pack of visual studio, were the LINQ technique and Addin / Plugin Model in .Net framework 3.5 and c# 3.0 version was included with additional package changes with code package for Implicitly Typed Local Variables,Extension Methods, Lambda Expressions, Type Inference, Object and Collection Initializers, Anonymous Types, Automatically Implemented Properties, Expression Trees. |
2010 |
4.0 |
4.0 |
Some more useful features like Parallel Computing, Code Contracts,Dynamic Language Runtime,Background garbage collection,Generic Covariance and Contravariance with updated Common Language Runtime 4.0 were added in .Net framework 4.0 for Visual studio pack 2010 and package code in c# included support Support for Covariance and Contravariance, Optional parameters and named arguments handling,Support for Dynamic and DLR and Enhanced support for COM interop. |
2012/2013 |
5.0 |
4.5 |
More Advanced features from .Net platform were released with version 4.5 which included support for enhanced regular expressions,default culture for application domain,zip compression,support of array with size more than 2GB, asynchronous file operations, improvement in parallel computing and C# was included in this visual studio pack with release version 5 and included the package components for Async / Await Feature and support for caller information. |
2013/2015 |
4.6 |
6.0 |
This pack included the features Read-only auto-properties,Auto-property initializers:,await in catch and finally blocks,Improved overload resolution: |
2017 |
Core |
7.0 |
Improvement over features of Out variables,Tuples and deconstruction,Pattern matching, Local functions,Expanded expression bodied members, Ref locals and returns was incorporated in this pack |
Basics of c# programming |
||||||||||||||||||||||||||||||||||||||||||||||||
Variables |
||||||||||||||||||||||||||||||||||||||||||||||||
Name of a memory location for storing data on which set of operations can be applied and these are reusable in nature. Syntax of declaring variable in c# :- <data_type> <variable_list>; Examples -
We can store value in variable at the time of declaration, accordingly its format will be <data_type> <variable_name>=value; or at any other place at the accessible location using assignment expression without datatype in front of variable name. |
||||||||||||||||||||||||||||||||||||||||||||||||
Operators |
||||||||||||||||||||||||||||||||||||||||||||||||
To perform different set of operations on variables, many different category of operators like arithmetic, logical, bitwise etc. are available and are shown in chart below:. |
||||||||||||||||||||||||||||||||||||||||||||||||
Operator Precedence |
||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||
keyword |
||||||||||||||||||||||||||||||||||||||||||||||||
It is a reserved word which has a specific meaning and purpose in the c# terminology and these cannot be used as a variable name, constant name etc. There is a long list of reserved words, Some of theses are terms used for specifying data type like char, int float etc, decision making words if,else,for, while , switch and many other terms which has specific purpose. |
||||||||||||||||||||||||||||||||||||||||||||||||
Constants |
||||||||||||||||||||||||||||||||||||||||||||||||
These are fixed values(referred as literals) that the program may not alter during its execution. Keyword const is used to declare the variable as a constant. Syntax for declaration is : const <data_type> <constant_name> = value; The fixed value can be a string , int, float or character constants (includes escape or universal character along with plain characters) based on its data type specified. |
||||||||||||||||||||||||||||||||||||||||||||||||
Comments |
||||||||||||||||||||||||||||||||||||||||||||||||
Comments are the non-executable statements which are ignored by c# compiler and generally used for stating purpose ogram of specific blocks or lines of code. There are three ways through which we can add comments in C#—
|
||||||||||||||||||||||||||||||||||||||||||||||||
Static |
C# Data Types |
|
Categories of Data types -
Built in values - bool, byte char decimal double float int User defined value types : structures, enumerations
Built in types - String, dynamic and Object. User defined types :All arrays, even if their elements are value types, Classes and Interface
|
|
Some Useful built-in types in C#.Net |
|
Anonymous type ( var ) |
|
|
|
dynamic |
|
This was a new type introduced by C# 4.0 (.NET 4.5) that avoids compile time type checking. Instead, it resolves type at run time. A dynamic type can be defined using the dynamic keyword.
|
|
nullable |
|
C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null value. -Syntax for declaring a nullable type is as follows − < data_type> ? <variable_name> = null; For example, you can store any value from integer range plus null value for nullable int type as - Int? i=null; |
|
|
|
Arrays |
|
int[] intArray; // can store int values bool[] boolArray; // can store boolean values string[] stringArray; // can store string values double[] doubleArray; // can store double values byte[] byteArray; // can store byte values Student[] customClassArray; // can store instances of Student class Array Declaration & Initialization Examples :
int[] intArray1 = new int[5];
int[] intArray2 = new int[5]{1, 2, 3, 4, 5};
int[] intArray3 = {1, 2, 3, 4, 5}; Arrays initialized after declaration (Late Initialization) string[] strArray; strArray = {"1st Element","2nd Element","3rd Element","4th Element" };
Multi-dimensional - two dimensional series like rows and columns. Example of Multidimensional array : Jagged array - also known as "array of arrays" because its elements are arrays Example of Jagged Array : int[][] arr = new int[2][]; This jagged array that has two elements. The size of each element array can be different like this - arr[0] = new int[4]; arr[1] = new int[6]; One of the initialization approach of arrays can be like this -
|
|
Structures |
|
It is a value type data type and helps you to make a single variable hold related data of various data types. The struct keyword is used for creating a structure.
Simple Example - struct Student{ Example of creating object(or variable) of Structure data type : Student s1; Student s2; /* s1 specification */ s1.RollNumber = 6495407; |
|
Enums |
|
enum is a value type data type and is used to declare a list of named integer constants i.e to give a name to each constant so that the constant integer can be referred using its name. The general syntax of using enum data type is enum <enum_name> { Example- enum WeekDays { Monday = 0, Tuesday =1, Wednesday = 2, Thursday = 3, Friday = 4, Saturday =5, Sunday = 6 } You can check the enum value of Wednesday like this - Console.WriteLine(WeekDays.Thursday ); It will print 3 on console screen.
|
|
Control Statements |
|
C# provides many decision making statements that help regulate the flow of the C# program based on certain logical conditions. C# includes the decision making and control statements. |
|
if statements - if statement is used to test the condition and there are various types of if statements in C#. |
|
if statement |
if(condition) |
if else statement |
if(condition) |
if else if ladder |
if(condition1) else if(condition2) { // execute this code block if condition 2 evaluates to true } |
nested if statement |
If statements can also be created inside another if statements |
Ternary operator ?: |
|
special type of decision making operator. First part (before ?) includes conditional expression that returns boolean value true or false. Second part (after ? and before :) contains a statement which will be returned if the conditional expression in the first part evaluatesto true. The third part includes another statement which will be returned if the conditional expression returns false. SyntaxCondition Expression ? First Statement : Second StatementExample : int x = 20, y = 10; var result = x > y ? "x is greater than y" : "x is less than or equal to y"; Will result in true condition , so "x is greater than y" will be stored in result variable.
|
|
For loop |
|
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. for ( init; condition; increment ) { You can create as many nested loops |
|
While |
|
while(condition) { A while loop statement in C# repeatedly executes a target statement as long as a given condition is true. do { A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time. |
|
Break |
|
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. Syntax for writing break statement : break; |
|
continue |
|
To skip some operations from loops. It continues the current flow of the program and skips the remaining code at specified condition in loop. In case of inner loop, it continues only inner loop. |
|
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.public class class_name { public static void Main(string[] args) { Label_name: …………... if (condition){ goto Label_name; } } } |
Methods |
|
A method is a group of statements that together perform a task. Every C# program has at least one class with a method named Main. To use a method, you need to define the method and call the method. The basic format for using method is - <Access Specifier> <Return Type> <Method Name>(Parameter List) {
|
|
Passing Parameters to a Method |
|
Pass By Value : Syntax: <method_name>(int x,int y) |
This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. |
Pass By Reference : Class class_name{ <method_name>(ref int x, ref int y){ } Class main_class_name static void Main(string[] args) { class_name obj; /* calling a function to swap the values */ }} |
This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument. |
Output Parameters : Example of using out parameters - public void getValues(int a, int b, out int x, out int y ) { |
To return more than one value from method, out keyword is used for function parameters which stores the modified values from the method. |
Casting and Type Conversions |
||||||||||||||||||||||
Type conversion is converting one type of data to another type.However, you might sometimes need to copy a value into a variable or method parameter of another type. For example, you might have an integer variable that you need to pass to a method whose parameter is typed as double. Or you might need to assign a class variable to a variable of an interface type. These kinds of operations are called type conversions. In C#, you can perform the following kinds of conversions:
Example : double x = 1234.7;
|
||||||||||||||||||||||
Boxing and Unboxing |
||||||||||||||||||||||
There are 2 categories of Conversions- When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing. Boxing example : int i = 123; object o = i; int i = 123; Unboxing : Attempting to unbox null causes a NullReferenceException. Attempting to unbox a reference to an incompatible value type causes an InvalidCastException. |
||||||||||||||||||||||
Classes and Objects |
||||||||||||||||||||||
Class is a blueprint for a data type and it enables you to create your own custom types by grouping together variables of other types, methods and events.In object oriented programming, a class defines certain properties, fields, events, method etc. Object is an instance of a class and all the members of the class can be accessed through object. General format of class (along with constructors) : <access specifier> class class_name { <access specifier> <data type> variableN; class_name(){ …... } // constructor class_name (<data type> variableN){ …..} // parameterized contructor Access specifiers specify the access rules for the members as well as the class itself. If not mentioned, then the default access specifier for a class type is internal. Default access for the members is private. To access the class members, you use the dot (.) operator.
namespace mynamespace { class MyClass { } } |
||||||||||||||||||||||
Inheritance |
||||||||||||||||||||||
It is a process in which one object acquires all the properties and behaviors of its parent object automatically C# does not support multiple inheritance(multiple parents). However, you can use interfaces to implement multiple inheritance. Basic syntax : <access-specifier> class <base_class> { |
||||||||||||||||||||||
Generics |
||||||||||||||||||||||
Generics allow you to define a class with placeholders for the type of its fields, methods, parameters, etc. Generics replace these placeholders with some specific data type at compile time. Below is a simple generic class example format. class MyGenericClass<T> { private T genericMemberVariable; public MyGenericClass(T value) { genericMemberVariable = value; } public T genericMethod(T genericParameter) { …. return genericMemberVariable; } public T genericProperty { get; set; } } This class can be instantiated as- MyGenericClass<int> gebObj= new MyGenericClass<int>(10); int val = gebObj.genericMethod(200); |
||||||||||||||||||||||
Collections |
||||||||||||||||||||||
These are specialized classes that hold many values or objects in a specific series'. There are two types of collections available in C#: non-generic collections and generic collections. Non-generic collections - ArrayList - comes with additional capabilities than array where you can add and remove items specified position. It also allows dynamic memory allocation, adding, searching and sorting items in the list. Hashtable- Hashtable stores key and value pairs.The key is used to access the items in the collection. BitArray - It represents an array of the binary representation using the values 1 and 0. Items from the BitArray can be accessed using an integer index, which starts from zero. SortedList - It uses a key as well as an index to access the items in a list. A sorted list is a combination of an array and a hash table. Stack - Stack stores the values in LIFO style (Last In First Out). It provides a Push() method to add a value and Pop() & Peek() methods to retrieve values Queue- stores the values in First In First Out style. It keeps the order in which the values were added. It provides an Enqueue() method to add values and a Dequeue() method to retrieve values from the collection. The limitation of non-generic collections is that while retrieving items, you need to cast into the appropriate data type, otherwise the program will throw a runtime exception. C# also includes generic form of SortedList, Stack and queue collection (i.e the generic SortedList<TKey,TValue> , Stack<T> and Queue<T> collections) Other Generic Collection classes are - List<T> : contains elements of specified type. It grows automatically as you add elements in it. Dictionary<TKey,TValue> : contains key-value pairs. Hashset<T>: contains non-duplicate elements and eliminates duplicate elements. |
||||||||||||||||||||||
File Handling |
||||||||||||||||||||||
The System.IO namespace has various classes that are used for performing numerous operations with files, such as creating and deleting files, reading from or writing to a file, closing a file etc. Some of the useful file handling classes are :
|
||||||||||||||||||||||
File |
||||||||||||||||||||||
Important Methods of Static File ClassAppendAllText - open appends the specified string to the file ( creates new file if not exists) AppendText- Creates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist. Copy- Copies an existing file to a new file. Overwriting a file of the same name is not allowed., Create - Creates or overwrites a file in the specified path, CreateText -Creates or opens a file for writing UTF-8 encoded text. Exists - Determines whether the specified file exists., ReadAllBytes - Opens a binary file, reads the contents of the file into a byte array, and then closes the file.), ReadAllText - Opens a text file, reads all lines of the file, and then closes the file.), WriteAllBytes - Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten., WriteAllText - Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten. Replace -Replace the file contents. |
||||||||||||||||||||||
DirectoryInfo |
||||||||||||||||||||||
The DirectoryInfo class is derived from the FileSystemInfo class. It has various methods for creating, moving, and browsing through directories and subdirectories. This class cannot be inherited. It has properties like Attributes, CreationTime, Exists, Extension, FullName, LastAccessTime and Name and involves operational methods -Create(), CreateSubdirectory(string path), Delete(), GetDirectories() and GetFiles() |
||||||||||||||||||||||
FileStream |
||||||||||||||||||||||
This class from the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream.FileStream obj parameters in sequence are <file_name>, <FileMode Enumerator>,<FileAccess Enumerator> and<FileShare Enumerator> The FileMode enumeration defines various methods for opening files. The members of the FileMode enumerator are −
FileAccess enumerators have members: Read, ReadWrite and Write. FileShare enumerators have the following members −
|
||||||||||||||||||||||
FileInfo |
||||||||||||||||||||||
This class provides the same functionality as the static File class but you have more control on read/write operations on files by writing code manually for reading or writing bytes from a file. Important Properties of FileInfo:Directory - Gets an instance of the parent directory. DirectoryName - Gets a string representing the directory's full path. Name - Gets the name of the file. FullName -Gets the full path of the directory or file. Extension - Gets the string representing the file extension. Exists - indicates whether a file exists. IsReadOnly - Gets or sets a value that determines if the current file is read only. LastAccessTime - Gets the time the current file was last accessed. LastWriteTime - Gets the time of the last written activity of the file. Length- Gets the size, in bytes, of the current file. Important Methods of FileInfo:AppendText - Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo. CopyTo - Copies an existing file to a new file, disallowing the overwriting of an existing file. Create - Creates a file. CreateText - Creates a StreamWriter that writes a new text file. Delete - Deletes the specified file. Open - File can be Opened in a controlled manner based on the parameters passed. Various open file formats are
OpenRead - Creates a read-only FileStream Replace - Replaces the contents of a specified file with the file described by the current FileInfo object, deleting the original file, and creating a backup of the replaced file. |
*NOTE : "This study material is collected from multiple sources to make a quick refresh course available to students."