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

C Sharp

Uploaded by

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

C Sharp

Uploaded by

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

C#

C#
C# (C-Sharp) is a programming language developed by Microsoft that runs on the .NET
Framework.

C# is pronounced "C-Sharp".

C# has roots from the C family, and the language is close to other popular languages
like C++ and Java.

The first version was released in year 2002. The latest version, C# 12, was released in
November 2023.

C# is used for:

• Mobile applications
• Desktop applications
• Web applications
• Web services
• Web sites
• Games
• VR
• Database applications
• And much, much more!

Applications written in C# use the .NET Framework, so it makes sense to use Visual Studio,
as the program, the framework, and the language, are all created by Microsoft.

Why Use C#?


• It is one of the most popular programming languages in the world
• It is easy to learn and simple to use
• It has huge community support
• C# is an object-oriented language which gives a clear structure to programs and
allows code to be reused, lowering development costs
• As C# is close to C, C++ and Java, it makes it easy for programmers to switch to C#
or vice versa

Comments
can be used to explain C# code, and to make it more readable. It can also be used to
prevent execution when testing alternative cod

Single-line Comments
Single-line comments start with two forward slashes (//).

Multi-line Comments
Multi-line comments start with /* and ends with */.

Namespace
Namespaces play an important role in managing related classes in C#. The .NET
Framework uses namespaces to organize its built-in classes. For example, there
are some built-in namespaces in .NET such as System, System.Linq,
System.Web, etc. Each namespace contains related classes.

A namespace is a container for classes and namespaces.

C# Variables
Variables are containers for storing data values.

• Variable names must be unique.


• Variable names can contain letters, digits, and the underscore _ only.
• Variable names must start with a letter.
• Variable names are case-sensitive,

In C#, there are different types of variables (defined with different keywords), for example:

• int - stores integers (whole numbers), without decimals, such as 123 or -123
• double - stores floating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
• string - stores text, such as "Hello World". String values are surrounded by double
quotes
• bool - stores values with two states: true or false

var
C# 3.0 introduced var keyword to declare method level variables without
specifying a data type explicitly.
var can be used to declare any built-in data type or a user-defined type or an
anonymous type variable.

The keyword var is used to declare implicit type variables in C#

Constants
which means unchangeable and read-only:
you can add the const keyword in front of the variable type. PI (3.14159...).

You cannot declare a constant variable without assigning the value.

Struct
C#, struct is the value type data type that represents data structures. It can
contain a parameterized constructor, static constructor, constants, fields,
methods, properties, indexers, operators, events, and nested types.

can be used to hold small data values that do not require inheritance, e.g.
struct
coordinate points, key-value pairs, and complex data structure.

When to Use Structs in C# Structs are best used when you need to represent
simple data types, such as integers, strings, or other basic data types. They are
also useful when you need to work with large datasets, such as arrays or lists,
where performance is critical.

Use struct

• If all the member fields are value types.


• If instances of the type are small and short-lived or embedded to other
instances.
• If it logically denotes a single value, same as primitive types like int, double,
etc.
• If the size of the instance is below 16 bytes.
• If it will not be boxed and unboxed again and again.

Display Variables
The WriteLine() method is often used to display variable values to the console window.

To combine both text and a variable, use the + character:


Declare Many Variables
To declare more than one variable of the same type, use a comma-separated list:

int x = 5, y = 6, z = 50;

Console.WriteLine(x + y + z);

C# Identifiers
All C# variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).

Note: It is recommended to use descriptive names in order to create understandable and


maintainable code:

C# Data Types
As explained in the variables chapter, a variable in C# must be a specified data type:

int myNum = 5; // Integer (whole number)

double myDoubleNum = 5.99D; // Floating point number

char myLetter = 'D'; // Character

bool myBool = true; // Boolean

string myText = "Hello"; // String

C# Type Casting
Type casting is when you assign a value of one data type to another type.

In C#, there are two types of casting:

• Implicit Casting (automatically) - converting a smaller type to a larger type size


char -> int -> long -> float -> double

• Explicit Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char
Why Casting Conversion?
• Many times, there's no need for type conversion. But sometimes you have to. Take a
look at the next chapter, when working with user input, to see an example of this.

User Input
• You have already learned that Console.WriteLine() is used to output (print) values. Now
we will use Console.ReadLine() to get user input.
• In the following example, the user can input his or hers username, which is stored in
the variable userName.
• The Console.ReadLine() method returns a string.
Console.WriteLine("Enter your age:");
int age = Console.ReadLine();

Operators
Operators are used to perform operations on variables and values.

+Addition, - Subtraction,*Multiplication, / Division, % Modulus, ++ Increment ,--


Decrement.

Assignment Operators
Assignment operators are used to assign values to variables.

=:, =+, =- ,=*,=%

Comparison Operators
Comparison operators are used to compare two values (or variables).

The return value of a comparison is either True or False.

Console.WriteLine(x > y);

Logical Operators
As with comparison operators, you can also test for True or False values with logical
operators.

&& logicl and ,|| logical or ,=! Logical not


Math
The C# Math class has many methods that allows you to perform mathematical tasks on
numbers

Math.Max(x,y) , Math.Min(x,y) , Math.Sqrt(x) , Math.Round(), Math.Abs(x)

C# Strings
Strings are used for storing text.

A string variable contains a collection of characters surrounded by double quotes:

You can also use the string.Concat() method to concatenate two strings:

String Interpolation ; string name = $"My full name is: {firstName} {lastName}";

Access Strings ;\
string myString = "Hello";

Console.WriteLine(myString[1]); // Outputs "e"

Console.WriteLine(myString.IndexOf("e")); // Outputs "1"

string lastName = name.Substring(myString);

Another useful method is Substring(), which extracts the characters from a string, starting
from the specified character position/index, and returns a new string. This method is often
used together with IndexOf() to get the specific character position:

StringBuilder
The StringBuilder doesn't create a new object in the memory but dynamically
expands memory to accommodate the modified string.
This behavior would hinder the performance if the original string changed
multiple times by replacing, appending, removing, or inserting new strings in
the original string.

1. StringBuilder is mutable.
2. StringBuilder performs faster than string when appending multiple string
values.
3. Use StringBuilder when you need to append more than three or four strings.
4. Use the Append() method to add or append strings to the StringBuilder object.
5. Use the ToString() method to retrieve a string from the StringBuilder object.

Difference between String and string


Essentially, there is no difference between string and String (capital S) in C#.

String (capital S) is a class in the .NET framework in the System namespace. The
fully qualified name is System.String. Whereas, the lower case string is an alias
of System.String.

Difference between String and StringBuilder


both string and StringBuilder are used to represent text.
a string is immutable.
It means a string cannot be changed once created. For example, a new string,
"Hello World!" will occupy a memory space on the heap.
Now, changing the initial string "Hello World!" to "Hello World! from Tutorials
Teacher" will create a new string object on the memory heap instead of
modifying an original string at the same memory address.
This impacts the performance if you modify a string multiple times by
replacing, appending, removing, or inserting new strings in the original string.
StringBuilder

StringBuilder sb = new StringBuilder("Hello World!");


sb.Append("from Tutorials Teacher.");

C# Booleans
C# has a bool data type, which can take the values true or false.

• YES / NO
• ON / OFF
• TRUE / FALSE

Nullable types
Nullable types represent the Null value as well the actual range of that data type.
Anonymous Type
Example: Anonymous Type
var student = new { Id = 1, FirstName = "James", LastName = "Bond" };

• an anonymous type is a type (class) without any name that can contain
public read-only properties only. It cannot contain other members, such as
fields, methods, events, etc.
• You create an anonymous type using the new operator with an object
initializer syntax. The implicitly typed variable- var is used to hold the
reference of anonymous types.

Dynamic Types
• C# 4.0 (.NET 4.5) introduced a new type called dynamic that avoids compile-
time type checking. A dynamic type escapes type checking at compile-time;
instead, it resolves type at run time.
• A dynamic type variables are defined using the dynamic keyword.

Example: dynamic Variable


dynamic MyDynamicVar = 1;
Console.WriteLine(MyDynamicVar.GetType());

Asynchronous Programming?
In asynchronous programming, the code gets executed in a thread without having
to wait for an I/O-bound or long-running task to finish.

Microsoft recommends Task-based Asynchronous Pattern to implement


asynchronous programming in the .NET Framework or .NET Core applications
using async , await keywords and Task or Task<TResult> class.

async, await, and Task


An async keyword is a method that performs asynchronous tasks such as
fetching data from a database, reading a file, etc

Use async along with await and Task if the async method returns a value back to the
calling code. We used only the async keyword in the above program to
demonstrate the simple asynchronous void method.

The await keyword waits for the async method until it returns a value. So the main
application thread stops there until it receives a return value.
The Task class represents an asynchronous operation
and Task<TResult> generic class represents an operation that can return a value.
In the above example, we used await Task.Delay(4000) that started async operation
that sleeps for 4 seconds and await holds a thread until 4 seconds.

the difference between const and static readonly in C#


eclared using the static keyword. Declared using the readonly keyword. Declred using the const keyword.

The difference is that the value of a static readonly field is set at run time,
and can thus be modified by the containing class, whereas the value of a
const field is set to a compile-time constant

Value of the static members can be modified Readonly variable cannot be modified Constant variables
using ClassName.StaticMemberName . at run-time. It can only be initialized or cannot be modified after
changed in the constructor. declaration.

Value Type and Reference Type


In C#, these data types are categorized based on how they store their value in
the memory. C# includes the following categories of data types:

1. Value type
2. Reference type
3. Pointer type

Value Type
A data type is a value type if it holds a data value within its own memory
space. It means the variables of these data types directly contain values.

All the value types derive from System.ValueType, which in-turn, derives from System.Object.

For example, consider integer variable int i = 100;

Reference Type
a reference type doesn't store its value directly. Instead, it stores the address
where the value is being stored. In other words, a reference type contains a
pointer to another memory location that holds the data.

For example, consider the following string variable:

string s = "Hello World!!";


ref Keyword
C# supports value type and reference type data types. By default, the value type
variable is passed by value, and the reference type variable is passed by
reference from one method to another method in C#. Pointers
Pointers are defined as a variable that contains the memory address of another
variable.

out keyword
The out keyword can be used with variables and method parameters. The
out paramters are always passed by reference for both, the value type and
the reference type data types.
What is boxing?
Boxing is the process of converting a value type to the object type or any interface
type implemented by this value type. Boxing is implicit.

Boxing

int i = 10;
object o = i; //performs boxing

why is it named as boxing?

As you know, all the reference types stored on heap where it contains the address
of the value and value type is just an actual value stored on the stack

What is Unboxing?
Unboxing is the reverse of boxing. It is the process of converting a reference type
to value type. Unboxing extract the value from the reference type and assign it
to a value type.

Unboxing is explicit. It means we have to cast explicitly.

Example: Unboxing

object o = 10;
int i = (int)o; //performs unboxing
Note:
Boxing and unboxing degrade the performance. So, avoid using it. Use generics to avoid
boxing and unboxing. For example, use List instead of ArrayList.

Managed code and unmanaged code ;

Managed code is compiled to an intermediate language called Common


Intermediate Language (CIL) or Microsoft Intermediate Language (MSIL), which is
then executed by the CLR. Unmanaged Code is compiled directly to native code,
which is executed by the Operating System

Conditions and If Statements


• Use if to specify a block of code to be executed, if a specified condition is true
• Use else to specify a block of code to be executed, if the same condition is false
• Use else if to specify a new condition to test, if the first condition is false
• Use switch to specify many alternative blocks of code to be executed

Short Hand If...Else (Ternary Operator)


includes a decision-making operator ?: which is called the conditional operator
or ternary operator. It is the short form of the if else conditions.
variable = (condition) ? expressionTrue : expressionFalse;

Switch Statements
Use the switch statement to select one of many code blocks to be executed.

This is how it works:

• The switch expression is evaluated once


• The value of the expression is compared with the values of each case
• If there is a match, the associated block of code is executed
• The break and default keywords will be described later in this chapter

The break Keyword


• When C# reaches a break keyword, it breaks out of the switch block.
• This will stop the execution of more code and case testing inside the block.
• When a match is found, and the job is done, it's time for a break. There is no need for
more testing.
The default Keyword
• The default keyword is optional and specifies some code to run if there is no case
match:

While Loop
Loops
• Loops can execute a block of code as long as a specified condition is reached.
• Loops are handy because they save time, reduce errors, and they make code more
readable.

While Loop
• The while loop loops through a block of code as long as a specified condition is True:
• the code in the loop will run, over and over again, as long as a variable (i) is less than

Note: Do not forget to increase the variable used in the condition, otherwise the loop
will never end!

Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.

Do not forget to increase the variable used in the condition, otherwise the loop will
never end!

For Loop
When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:
for (statement 1; statement 2; statement 3)

// code block to be executed

Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

Nested Loops
It is also possible to place a loop inside another loop. This is called a nested loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

The foreach Loop


There is also a foreach loop, which is used exclusively to loop through elements in
an array:

foreach (type variableName in arrayName)

// code block to be executed

Break
You have already seen the break statement used in an earlier chapter of this tutorial. It was
used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.

Array
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.

To declare an array, define the variable type with square brackets:

Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
An array is the data structure that stores a fixed number of literal values
(elements) of the same data type. Array elements are stored contiguously in the
memory.

In C#, an array can be of three types: single-dimensional, multidimensional, and


jagged array.

Sort an Array
There are many array methods available, for example Sort(), which sorts an array
alphabetically or in an ascending order:

Two-Dimensional Arrays
To create a 2D array, add each array within its own set of curly braces, and insert a comma
(,) inside the square brackets:

multidimensional arrays.

A multidimensional array is basically an array of arrays.

Arrays can have any number of dimensions. The most common are two-dimensional arrays
(2D).

Jagged Arrays ; An array of array


A jagged array is an array of array. Jagged arrays store arrays instead of literal
values.

A jagged array is initialized with two square brackets [][].

Array and arraylist ;


The main differences between Array and ArrayList in C# are: Array is fixed
size, whereas ArrayList is dynamically sized. Array can only store items of a
single, specified type, whereas ArrayList can store items of any type.

Methods
A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as functions.

Why use methods? To reuse code: define the code once, and use it many times…

The Main() Method ;


The Main() method is an entry point of console and windows
applications on the .NET or .NET Core platform. It is also an entry
of ASP.NET Core web applications.

When you run an application, it starts the execution from


the Main() method. So, a program can have only one Main() method as
an entry point. However, a class can have multiple Main() methods, but
any one of them can be an entry point of an application.

Parameters and Arguments


Information can be passed to methods as parameter. Parameters act as variables inside the
method.

They are specified after the method name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.

Default Parameter Value


You can also use a default parameter value, by using the equals sign (=).

static void MyMethod(string country = "Norway")

Console.WriteLine(country);

}
Return Values
In the previous page, we used the void keyword in all examples, which indicates that the
method should not return a value.

If you want the method to return a value, you can use a primitive data type (such
as int or double) instead of void, and use the return keyword inside the method:

Named Arguments
It is also possible to send arguments with the key: value syntax.

Method Overloading
With method overloading, multiple methods can have the same name with different
parameters:

Note: Multiple methods can have the same name as long as the number and/or type of
parameters are different.

Classes and Objects


A class is a user-defined blueprint or prototype from which objects are created.
A class can contain one or more constructors, fields, methods, properties,
delegates, and events. They are called class members. A class and its members
can have access modifiers such as public, private, protected, and internal, to
restrict access from other parts of the program.

Basically, a class combines the fields and methods(member function which


defines actions) into a single unit. In C#, classes support polymorphism,
inheritance and also provide the concept of derived classes and base classes.

An object is basically a block of memory that has been allocated and configured
according to the blueprint.

Class Members
Fields and methods inside classes are often referred to as "Class Members":

Access Modifiers
Modifier Description

public The code is accessible for all classes

private The code is only accessible within the same class

protected The code is accessible within the same class, or in a class that is inherited

From that class

internal The code is only accessible within its own assembly, but not from another assemb

Why Access Modifiers?


To control the visibility of class members (the security level of each individual class and
class member).

To achieve "Encapsulation" - which is the process of making sure that "sensitive" data is
hidden from users. This is done by declaring fields as private. You will learn more about this
in the next chapter.

Properties

A property is a member that provides a flexible mechanism to read, write, or


compute the value of a private field. Properties can be used as if they're public
data members, but they're special methods called accessors.
C# also provides a way to use short-hand / automatic properties, where you do not have to
define the field for the property, and you only have to write get; and set; inside the
property.

Enums
An enum is a special "class" that represents a group
of constants (unchangeable/read-only variables).
To create an enum, use the enum keyword (instead of class or interface), and
separate the enum items with a comma:

Enum is short for "enumerations", which means "specifically listed"

Working With Files


The File class from the System.IO namespace, allows us to work with files:

Exceptions
When executing C# code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.

.NET includes built-in exception classes for every possible error.


The Exception class is the base class of all the exception classes.

When an error occurs, C# will normally stop and generate an error message. The technical
term for this is: C# will throw an exception (throw an error).

Exception Handling
exception handling in C# using try, catch, and finally blocks.

Exceptions in the application must be handled to prevent crashing of the program


and unexpected result, log exceptions and continue with other functionalities. C#
provides built-in support to handle the exception using try, catch & finally blocks.

try and catch


The try statement allows you to define a block of code to be tested for errors while it is
being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in
the try block.

Finally
The finally statement lets you execute code, after try...catch, regardless of the result:
The throw keyword
The throw statement allows you to create a custom error.

The throw statement is used together with an exception class. There are many exception
classes available in
C#: ArithmeticException, FileNotFoundException, IndexOutOfRangeException, TimeOutException, etc:

An exception can be raised manually by using the throw keyword. Any type of
exceptions which is derived from Exception class can be raised using the throw
keyword.

Custom exceptions
Custom exceptions are a powerful feature of . NET C# that allows you to handle
errors and unexpected situations in your application in a more specific way.

IndexOutOfRangeException

An IndexOutOfRangeException exception is thrown when an invalid index is


used to access a member of an array or a collection, or to read or write from a
particular location in a buffer. This exception inherits from the Exception class but
adds no unique members.

NullReferenceException

A NullReferenceException exception is thrown when you try to access a member


on a type whose value is null. A NullReferenceException exception typically
reflects developer error and is thrown in the following scenarios: You've forgotten
to instantiate a reference type.

Compile time and Run time


Compile time is the period when the programming code (such as C#, Java, C,
Python) is converted to the machine code (i.e. binary code). Runtime is the
period of time when a program is running and generally occurs after compile
time.

Interface
In the human world, a contract between the two or more humans binds them to
act as per the contract. In the same way, an interface includes the declarations
of related functionalities. The entities that implement the interface must provide
the implementation of declared functionalities.

In C#, an interface can be defined using the interface keyword. An interface can
contain declarations of methods, properties, indexers, and events. However, it
cannot contain instance fields.

1. Interface can contain declarations of method, properties, indexers, and


events.
2. Interface cannot include private, protected, or internal members. All the
members are public by default.
3. Interface cannot contain fields, and auto-implemented properties.
4. A class or a struct can implement one or more interfaces implicitly or
explicitly. Use public modifier when implementing interface implicitly,
whereas don't use it in case of explicit implementation.
5. Implement interface explicitly using InterfaceName.MemberName.

6. An interface can inherit one or more interfaces.


A class or a Struct can implement one or more interfaces using colon :.
Interface members must be implemented with the public modifier; otherwise, the compiler will
give compile-time errors.

Partial Classes and Methods


In C#, you can split the implementation of a class, a struct, a method, or an
interface in multiple .cs files using the partial keyword. The compiler will combine
all the implementation from multiple .cs files when the program is compiled.

Rules for Partial Classes


• All the partial class definitions must be in the same assembly and namespace.
• All the parts must have the same accessibility like public or private, etc.
• If any part is declared abstract, sealed or base type then the whole class is
declared of the same type.
• Different parts can have different base types and so the final class will inherit
all the base types.
• The Partial modifier can only appear immediately before the
keywords class, struct, or interface.
• Nested partial types are allowed.

Rules for Partial Methods


• Partial methods must use the partial keyword and must return void.
• Partial methods can have in or ref but not out parameters.
• Partial methods are implicitly private methods, so cannot be virtual.
• Partial methods can be static methods.
• Partial methods can be generic.

Static Class, Methods, Constructors, Fields


static means something which cannot be instantiated. You cannot create an
object of a static class and cannot access static members using an object.

Static classes in C# cannot be instantiated and are limited to static


members only, making them sealed and inaccessible for inheritance.
Rules for Static Methods ;

Static methods can be defined using the static keyword before a return type and after
an access modifier. Static methods can be overloaded but cannot be overridden. Static
methods can contain local static variables. Static methods cannot access or call non-
static variables unless they are explicitly passed as parameters.

Static constructors have the following properties:


• A static constructor doesn't take access modifiers or have parameters.
• A class or struct can only have one static constructor.
• Static constructors cannot be inherited or overloaded.

Indexers ;
Indexers allow instances of a class or struct to be indexed just like arrays.
An indexer is a special type of property that allows a class or a structure to be
accessed like an array for its internal collection. C# allows us to define custom
indexers, generic indexers, and also overload indexers.

An indexer can be defined the same way as property with this keyword and square
brackets [].

public string this[int index]


{

Note:
Indexer does not allow ref and out paramters.

Generics
generic means not specific to a particular data type.

C# allows you to define generic classes, interfaces, abstract classes, fields,


methods, static methods, properties, events, delegates, and operators using
the type parameter and without the specific data type. A type parameter is a
placeholder for a particular type specified when creating an instance of the
generic type.

Define Generic Class


class DataStore<T>
{
public T Data { get; set; }
}

A generic type is declared by specifying a type parameter in an angle brackets


after a type name, e.g. TypeName<T> where T is a type parameter.

Generic Class Characteristics


• A generic class increases the reusability. The more type parameters mean
more reusable it becomes. However, too much generalization makes code
difficult to understand and maintain.
• A generic class can be a base class to other generic or non-generic classes or
abstract classes.
• A generic class can be derived from other generic or non-generic interfaces,
classes, or abstract classes.
Advantages of Generics
1. Generics increase the reusability of the code. You don't need to write code to
handle different data types.
2. Generics are type-safe. You get compile-time errors if you try to use a
different data type than the one specified in the definition.
3. Generic has a performance advantage because it removes the possibilities of
boxing and unboxing.

Generic & Non-generic Collections


C# includes specialized classes that store series of values or objects are called
collections.

• List: In Generic List, we have to specify a data type to its contents, and all elements will have
the same datatype. ...
• Dictionary , Sorted List , Stack: ...
• Queue , ArrayList , HashTable ,Sorted List:

There are two types of collections available in C#: non-generic collections and
generic collections.

The System.Collections namespace contains the non-generic collection types


and System.Collections.Generic namespace includes generic collection types.

In most cases, it is recommended to use the generic collections because they


perform faster than non-generic collections and also minimize exceptions by
giving compile-time errors.

Tuple
The Tuple<T> class was introduced in .NET Framework 4.0. A tuple is a data
structure that contains a sequence of elements of different data types. It can be
used where you want to have a data structure to hold an object with properties,
but you don't want to create a separate type for it.

Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>

USES ;
Tuples in C# are utilized for returning multiple values from methods, passing multiple values as a single
parameter, and temporary storage without defining a separate class.

Tuple Limitations:
Tuples in C# are reference types, allocated on the heap, potentially leading to CPU-
intensive operations; limited to eight elements and require nested tuples for additional
elements, risking ambiguity; accessed via properties with naming patterns like
Item<elementNumber>, which might not be intuitive.

Delegates
What if we want to pass a function as a parameter? How does C# handles the
callback functions or event handler? The answer is - delegate.

The delegate is a reference type data type that defines the method signature.
You can define variables of delegate, just like other data type, that can refer to
any method with the same signature as the delegate.

There are three steps involved while working with delegates:

1. Declare a delegate
2. Create an instance and reference a method
3. Invoke a delegate

Example: Declare a Delegate


public delegate void MyDelegate(string msg);

1. Delegate is the reference type data type that defines the signature.
2. Delegate type variable can refer to any method with the same signature as
the delegate.

Action Delegate
Action is a delegate type defined in the System namespace. An Action type delegate
is the same as Func delegate except that the Action delegate doesn't return a
value. In other words, an Action delegate can be used with a method that has a
void return type.
Anonymous Method
1. Anonymous method can be defined using the delegate keyword
2. Anonymous method must be assigned to a delegate.
3. Anonymous method can access outer variables or functions.
4. Anonymous method can be passed as a parameter.
5. Anonymous method can be used as event handlers.

Events

An event is a wrapper around a delegate. It depends on the delegate.

Use "event" keyword with delegate type variable to declare an event.

1. Use built-in delegate EventHandler or EventHandler<TEventArgs> for


common events.
2. The publisher class raises an event, and the subscriber class registers for an
event and provides the event-handler method.
3. Name the method which raises an event prefixed with "On" with the event
name.
1. The signature of the handler method must match the delegate signature.

Delegate Event
A delegate is declared using the delegate keyword. An event is declared using the event
keyword.
Delegate is a function pointer. It holds the reference of The event is a notification mechanism that
one or more methods at runtime. depends on delegates

Covariance and Contravariance in C#


Covariance and contravariance allow us to be flexible when dealing with class
hierarchy.
Consider the following class hierarchy before we learn about covariance and
contravariance:

Example: Class Hierarchy


public class Small
{

}
public class Big: Small
{

}
public class Bigger : Big
{

Extension Method
Extension methods are a powerful feature in C# that allows you to add new
functionality to existing types without modifying their source code.
Points to Remember :

1. Extension methods are additional custom methods which were originally not
included with the class.
2. Extension methods can be added to custom, .NET Framework or third party
classes, structs or interfaces.
3. The first parameter of the extension method must be of the type for which
the extension method is applicable, preceded by the this keyword.
4. Extension methods can be used anywhere in the application by including the
namespace of the extension method.

Stream
C# includes following standard IO (Input/Output) classes to read/write from
different sources like files, memory, network, isolated storage, etc.

Stream: System.IO.Stream is an abstract class that provides standard methods


to transfer bytes (read, write, etc.) to the source. It is like a wrapper class to
transfer bytes. Classes that need to read/write bytes from a particular source
must implement the Stream class.
The following classes inherit Stream class to provide the functionality to
Read/Write bytes from a particular source:

FileStream reads or writes bytes from/to a physical file, whether it is a .txt,


.exe, .jpg, or any other file. FileStream is derived from the Stream class.

MemoryStream: MemoryStream reads or writes bytes that are stored in


memory.

BufferedStream: BufferedStream reads or writes bytes from other Streams to


improve certain I/O operations' performance.

NetworkStream: NetworkStream reads or writes bytes from a network socket.

PipeStream: PipeStream reads or writes bytes from different processes.

CryptoStream: CryptoStream is for linking data streams to cryptographic


transformations.

Working with Files & Directories


C# provides the following classes to work with the File system. They can be used
to access directories, access files, open files for reading or writing, create a new
file or move existing files from one location to another, etc.

File
C# includes static File class to perform I/O operation on physical file system. The
static File class includes various utility method to interact with physical file of any
type e.g. binary, text etc.

Points to Remember :

1. File is a static class to read\write from physical file with less coding.
2. Static File class provides functionalities such as create, read\write, copy,
move, delete and others for physical files.
3. Static Directory class provides functionalities such as create, copy, move,
delete etc for physical directories with less coding.
4. FileInfo and DirectoryInfo class provides same functionality as static File and
Directory class.
Thus you can use FileInfo, StreamReader and StreamWriter class to read/write
contents from physical file.
Object Initializer Syntax
C# 3.0 (.NET 3.5) introduced Object Initializer Syntax, a new way to initialize an
object of a class or collection. Object initializers allow you to assign values to the
fields or properties at the time of creating an object without invoking a
constructor.

Collection initializer Syntax


IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName =
"John"} ,
null
};

Advantages of Initializers
• Initializer syntax makes a code more readable, easy to add elements into the
collection.
• Useful in multi-threading.

Design Principle
SOLID design principles in C# are basic design principles. SOLID stands
for Single Responsibility Principle (SRP), Open closed Principle (OSP),
Liskov substitution Principle (LSP), Interface Segregation Principle (ISP), and
Dependency Inversion Principle (DIP).

Design Pattern
Design Pattern provides low-level solutions related to implementation, of
commonly occurring object-oriented problems. In other words, design
pattern suggests a specific implementation for the specific object-oriented
programming problem.

For example, if you want to create a class that can only have one
object at a time, then you can use the Singleton design pattern which
suggests the best way to create a class that can only have one object.

Design patterns are tested by others and are safe to follow, e.g. Gang of
Four patterns: Abstract Factory, Factory, Singleton, Command, etc.
How to calculate the code execution time

As a programmer, we may need to find out the execution time used by a


particular segment of the C# code, in order to optimize the performance.
For example, we may want to know how much time is taken for reading
multiple files in the file system, or fetching data from the database, or
executing some business logic.

How to read file using StreamReader


Visit Stream I/O to know more about Stream class heirarchy.

Use the StreamReader class to read a physical file in C#.

Difference between Hashtable and Dictionary


Hashtables and Dictionaries are two commonly used
collection type for storing and retrieving key-value pairs.

Hashtable Dictionary
Hashtable is included in Dictionary is included in
the System.Collections namespace. the System.Collections.Generic namespace.

Hashtable is a loosely typed (non- Dictionary is a generic collection. So it can


generic) collection, this means it store key-value pairs of specific data types.
stores key-value pairs of any data
types.
Hashtable is thread safe. Only public static members are thread safe in
Dictionary.

You might also like