0% found this document useful (0 votes)
456 views

C# Programming - (Advanced Concepts)

Uploaded by

Rupali Sahu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
456 views

C# Programming - (Advanced Concepts)

Uploaded by

Rupali Sahu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

C# Programming - Advanced Concepts

Sealed Classes in C#
▪ You could restrict users form inheriting the class by sealing the class using the sealed keyword.

▪ The sealed keyword tells the compiler that the class is sealed, and therefore, cannot be extended.

▪ The following is an example of a sealed class:


sealed class FinalClass
{
private int x;
public void Method1()
{
}
}

▪ A method can also be sealed and in that case the method cannot be overridden.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 2


Exception Handling
▪ A runtime error is known as an exception.

▪ The exception will cause the abnormal termination of the program execution.

▪ Exceptions can be generated by the common language runtime (CLR), by the .NET Framework or any
third-party libraries, or by application code.

▪ Exception handling uses the try, catch, and finally keywords to try actions that may not succeed, to
handle failures when you decide that it is reasonable to do so, and to clean up resources afterward.

▪ Exceptions can be generated by the common language runtime (CLR), by the .NET Framework or any
third-party libraries, or by application code.

▪ Exceptions are created by using the throw keyword.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 3


Exception Handling
▪ Exceptions have the following properties:
▪ Exceptions are types that all ultimately derive from System.Exception.

▪ Use a try block around the statements that might throw exceptions.

▪ Once an exception occurs in the try block, the flow of control jumps to the first associated exception
handler that is present anywhere in the call stack. In C#, the catch keyword is used to define an
exception handler.

▪ If no exception handler for a given exception is present, the program stops executing with an error
message.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 4


Exception Handling
▪ If a catch block defines an exception variable, you can use it to obtain more information about the
type of exception that occurred.

▪ Exceptions can be explicitly generated by a program by using the throw keyword.

▪ Exception objects contain detailed information about the error, such as the state of the call stack and
a text description of the error.

▪ Code in a finally block is executed even if an exception is thrown. Use a finally block to release
resources, for example to close any streams or files that were opened in the try block.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 5


Exception Handling
▪ Some exceptions are thrown automatically by the .NET Framework's common language runtime (CLR)
are as follows:

▪ ArithmeticException: A base class for exceptions that occur during arithmetic operations, such as
DivideByZeroException and OverflowException.

▪ ArrayTypeMismatchException: Thrown when an array cannot store a given element because the
actual type of the element is incompatible with the actual type of the array.

▪ DivideByZeroException: Thrown when an attempt is made to divide an integral value by zero.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 6


Exception Handling
▪ IndexOutOfRangeException: Thrown when an attempt is made to index an array when the index is less
than zero or outside the bounds of the array.

▪ InvalidCastException: Thrown when an explicit conversion from a base type to an interface or to a


derived type fails at runtime.

▪ NullReferenceException: Thrown when an attempt is made to reference an object whose value is null.

▪ OutOfMemoryException: Thrown when an attempt to allocate memory using the new operator fails.
This indicates that the memory available to the common language runtime has been exhausted.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 7


Exception Handling
▪ try-catch block:
▪ The purpose of a try-catch block is to catch and handle an exception generated by working code.
Some exceptions can be handled in a catch block and the problem solved.

▪ finally block:
▪ The purpose of a finally statement is to ensure that the necessary cleanup of objects, usually objects
that are holding external resources, occurs immediately, even if an exception is thrown.

▪ throw keyword:
▪ The throw is a keyword and it is useful to throw an exception manually during the execution of the
program and we can handle those thrown exceptions using try-catch blocks based on our
requirements.
▪ The throw keyword will raise only the exceptions that are derived from the Exception base class.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 8


Exception Handling
▪ The try block:
▪ The try block guards statements that may throw an exception. Following is the syntax of try block
statement:
try
{
//statements that may cause an exception
}

▪ The try block governs statements that are enclosed within it and defines the scope of the exception-
handlers associated with it.
▪ A try block must have at least one catch block.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 9


Exception Handling
▪ The catch block:
▪ The catch statement of the catch block takes an object of the exception class as a parameter, which
refers to the raised exception.
▪ You can associate an exception-handler with the try block by providing one or more catch handlers,
immediately after the try block:
try
{
//statements that may cause an exception
}
catch (…)
{
//error handling code
}
©Larsen & Toubro Infotech Ltd. Privileged and Confidential 10
Exception Handling
▪ The finally block:
▪ The finally block is used to execute a given set of statements, whether an exception is
thrown or not thrown:
try
{
//statements that may cause an exception
}
catch (…)
{
//error handling code
}
finally
{
//statements to be executed
} ©Larsen & Toubro Infotech Ltd. Privileged and Confidential 11
Exception Handling
▪ Custom Exception:
▪ .NET provides a hierarchy of exception classes ultimately derived from the base class Exception.

▪ However, if none of the predefined exceptions meets your needs, you can create your own exception
classes by deriving from the Exception class.

▪ In C#, the exceptions are divided into two types such as

▪ System exception: An exception that is raised implicitly under a program by the exception manager.

▪ Application exception: An exception that is raised explicitly under a program based on our own
condition (i.e. user-defined condition) is known as an application exception.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 12


Exception Handling
▪ Custom Exception:
▪ When creating your own exceptions, end the class name of the user-defined exception with the word
"Exception", and implement the three common constructors.
using System;
public class EmployeeListNotFoundException : Exception {
public EmployeeListNotFoundException() { }
public EmployeeListNotFoundException(string message) : base(message)
{
}
public EmployeeListNotFoundException(string message, Exception inner)
: base(message, inner)
{
}
}

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 13


Implementing Reading and Writing in the Text Files
▪ The stream is a sequence of bytes traveling from a source to a destination over a communication
path.

▪ The two basic streams used are the input and output streams.

▪ An input stream is used for a read operation and an output stream is used for performing a write
operation.

▪ The System.IO namespace includes various classes, which are used to perform operations, such as file
creation, file deletion, and the read-write operations to files.

▪ To open an existing file or to create a new file, you need to create an object of type FileStream.

▪ Consider the following syntax for creating the object of type FileStream:
FileStream <object name> = new FileStream(<file Name>,<FileMode Enumerator>,<File Access
Enumerator>,<FileShare Enumerator>);

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 14


Implementing Reading and Writing in the Text Files
▪ FileMode enumerator defines various methods for opening files.

▪ The FileMode enumerator parameter is specified in many constructors for the FileStream.

▪ The parameters to FileMode checks whether a file is overwritten, created, or opened.

▪ FileAccess enumerator indicates whether you want to read data from the file, write to the file, or
perform both the operations.

▪ The members of the FileAccess enumerator are Read, ReadWrite, and Write.

▪ The FileShare enumerator contains constants for controlling the kind of access that the other
FileStream constructors can have to the same file.

▪ A typical use of this enumeration is to define whether two different applications can simultaneously
read from the same file.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 15


Implementing Reading and Writing in the Text Files
▪ The Stream class is used to read from and to write data in the text files.

▪ It is an abstract class, which supports reading and writing bytes into it.

▪ If data of a file is only text, then you can use the StreamReader class and the StreamWriter class
to accomplish the reading and writing tasks, respectively.

▪ The StreamReader class is inherited from the abstract class TextReader.

▪ The TextReader class represents a reader which can read a series of characters.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 16


Implementing Reading and Writing in the Text Files
▪ The following table describes some of the commonly used methods of the StreamReader
class.

Methods Description
Close Closes the object of StreamReader class and the underlying stream, and releases
any system resources associated with the reader
Peek Returns the next available character but does not consume it
Read Reads the next character or the next set of characters from the stream

ReadLine Reads a line of characters from the current stream and returns data as a string

Seek Allows the read/write position to be moved to any position within the file

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 17


Implementing Reading and Writing in the Text Files
▪ The StreamWriter class is inherited from the abstract class TextWriter.

▪ The TextWriter class represents a writer, which can write a series of characters.

▪ The following table describes some of the commonly used methods of the StreamWriter class.

Methods Description

Close Closes the current StreamWriter object and the underlying


stream
Flush Clears all buffers for the current writer and causes any buffered
data to be written to the underlying stream

Write Writes to the stream


WriteLine Writes data specified by the overloaded parameters, followed by
end of line

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 18


Implementing the Windows File System
▪ The ability to browse and locate files and directories for a specific directory is essential for
many programming tasks.

▪ Using classes such as the DirectoryInfo and FileInfo classes in combination is an efficient way
to gather the required information about files and directories in a specific location.

▪ The DirectoryInfo class is derived from the FileSystemInfo class.

▪ The FileInfo class is derived from FileSystemInfo class.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 19


Implementing the Windows File System
▪ The following table describes some of the commonly used properties of the DirectoryInfo class.

Property Description
Gets or sets attributes associated with the current file. This property is
Attributes
inherited from FileSystemInfo.
Gets or sets CreationTime of the current file. This property is inherited from
CreationTime
FileSystemInfo.
Exists Gets a Boolean value indicating whether the directory exist or not.
Gets a string containing the file extension. This property is inherited from
Extension
FileSystemInfo.
Gets a string containing the full path of the directory. This property is
FullName
inherited from FileSystemInfo.
Gets the last accessed time of the directory. This property is inherited from
LastAccessTime
FileSystemInfo.
Name Gets a string containing the name of a given file.
©Larsen & Toubro Infotech Ltd. Privileged and Confidential 20
Implementing the Windows File System
▪ The following table describes some of the commonly used methods of the DirectoryInfo class.

Method Description
Create Creates a directory.
CreateSubdirectory Creates a subdirectory.
Delete Deletes a directory.
Returns the directories in the current directory after matching
GetDirectories all the criteria. It also allows you to search subdirectories within
directories.
GetFiles Returns the files in the current directory.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 21


Implementing the Windows File System
▪ The following table describes some commonly used properties FileInfo class.
Property Description
Gets or sets attributes associated with the current file. This property is inherited from
Attributes
FileSystemInfo.
CreationTime Gets or sets CreationTime of the current file. This property is inherited from FileSystemInfo.
Directory Gets an instance of the directory which the file belongs to.
Exists Gets a boolean value indicating whether the file exists or not.
Extension Gets a string containing the file extension. This property is inherited from FileSystemInfo.
FullName Gets a string containing the full path of the file. This property is inherited from FileSystemInfo.
LastAccessTime Gets the last accessed time of the file. This property is inherited from FileSystemInfo.
Gets the time of the last written activity to the file. This property is inherited from
LastWriteTime
FileSystemInfo.
Length Gets the size of the file.
Name Gets a string containing the name of a given file.
©Larsen & Toubro Infotech Ltd. Privileged and Confidential 22
Implementing the Windows File System

▪ The following table describes some of the commonly used methods of the FileInfo class.

Method Description
Create Creates a file
AppendText Appends a text to the file represented by the FileInfo object
Delete Deletes a file
Open Opens file
OpenRead Opens a file in read-only mode

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 23


Generics
▪ Generics introduce the concept of type parameters to the .NET Framework, which make it possible to
design classes and methods that defer the specification of one or more types until the class or method
is declared and instantiated by client code.

▪ Generic classes and methods combine reusability, type safety, and efficiency in a way that their non-
generic counterparts cannot.

▪ Generics are most frequently used with collections and the methods that operate on them.

▪ The System.Collections.Generic namespace contains several generic-based collection classes.

▪ You can create your own generic interfaces, classes, methods, events, and delegates.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 24


Generics
public class GenericList<T>{
public void Add(T input) { }
}
class TestGenericList{
private class ExampleClass { }
static void Main() {
GenericList<int> list1 = new GenericList<int>();
list1.Add(1);
GenericList<string> list2 = new GenericList<string>();
list2.Add("");
GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
list3.Add(new ExampleClass());
}
}

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 25


Generics
▪ Generic Constraint:
▪ Constraints inform the compiler about the capabilities a type argument must have.
▪ Constraints specify the capabilities and expectations of a type parameter.
▪ Constraints are specified by using the where contextual keyword.
class EmployeeList<T> where T : Employee,
IEmployee,System.IComparable<T>, new()
{
// ...
}
Multiple constraints can be applied to the same type parameter, and the constraints themselves can
be generic types.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 26


Collections
▪ Collections provide a more flexible way to work with groups of objects.

▪ Unlike arrays, the group of objects you work with can grow and shrink dynamically as the needs of the
application change.

▪ A collection is a class, so you must declare an instance of the class before you can add elements to that
collection.

▪ If your collection contains elements of only one data type, you can use one of the classes in
the System.Collections.Generic namespace.

▪ A generic collection enforces type safety so that no other data type can be added to it.

▪ Some of the common collection classes are as follows:


▪ System.Collections.Generic classes
▪ System.Collections classes

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 27


Collections
▪ System.Collections.Generic classes:
▪ Dictionary<TKey,TValue>:
▪ Represents a collection of key/value pairs that are organized based on the key.
▪ List<T>:
▪ Represents a list of objects that can be accessed by index. Provides methods to search, sort, and
modify lists.
▪ Queue<T>:
▪ Represents a first in, first out (FIFO) collection of objects.
▪ SortedList<TKey,TValue>:
▪ Represents a collection of key/value pairs that are sorted by key based on the associated
IComparer<T> implementation.
▪ Stack<T>:
▪ Represents a last in, first out (LIFO) collection of objects.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 28


Collections
▪ System.Collections classes:
▪ ArrayList:
▪ Represents an array of objects whose size is dynamically increased as required.
▪ Hashtable:
▪ Represents a collection of key/value pairs that are organized based on the hash code of the key.
▪ Queue:
▪ Represents a first in, first out (FIFO) collection of objects.
▪ Stack:
▪ Represents a last in, first out (LIFO) collection of objects.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 29


Collections
▪ Iterators:
▪ An iterator is used to perform a custom iteration over a collection. An iterator can be a method or a
get accessor.
▪ You call an iterator by using a foreach statement.
▪ Each iteration of the foreach loop calls the iterator.

▪ IEnumerable:
▪ IEnumerable in C# is an interface that defines one method, GetEnumerator which returns an
IEnumerator interface.
▪ This allows readonly access to a collection then a collection that implements IEnumerable can be
used with a for-each statement.

©Larsen & Toubro Infotech Ltd. Privileged and Confidential 30

You might also like