0% found this document useful (0 votes)
8 views35 pages

Unit1 - Notes Sa

Introduction to .NET

Uploaded by

Rama Subramanian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views35 pages

Unit1 - Notes Sa

Introduction to .NET

Uploaded by

Rama Subramanian
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

UNIT 1

Introduction

.NET is not a single technology. Rather it is a set of technologies that work together
seamlessly to solve your business problems

The .NET platform is much more than


 a new language
 software development kit (SDK),
 even an operating system.

It offers
 powerful new services,
 a new processor-independent binary format
 new managed languages,
 managed language extensions to existing languages

World has

server server services

intern
Change to intern

PC PC Smart devices
PC

Provides rich user


experience

The .NET platform is Microsoft’s answer to the challenges this change will provide for
software developers

Flavors of .NET

What type of applications can I develop?

1. ASP.NET Web applications: These include dynamic and data driven browser based
applications.
2. Windows Form based applications: These refer to traditional rich client applications.
3. Console applications: These refer to traditional DOS kind of applications like batch
scripts.
4. Component Libraries: This refers to components that typically encapsulate some
business logic.
5. Windows Custom Controls: As with traditional ActiveX controls, you can develop your
own windows controls.
6. Web Custom Controls: The concept of custom controls can be extended to web
applications allowing code reuse and modularization.
7. Web services: They are “web callable” functionality available via industry standards like
HTTP, XML and SOAP.
8. Windows Services: They refer to applications that run as services in the background. They
can be configured to start automatically when the system boots up.

.NET Framework SDK

 Complete Software Development Kit (SDK).


 provides classes, interfaces and language compilers necessary to program
for .NET.
 Contains excellent documentation and Quick Start tutorials that help you learn
.NET technologies with ease.
 available FREE of cost. At
http://msdn.microsoft.com/downloads/default.asp?url=/downloads/
sample.asp?url=/msdn-files/027/000/976/msdncompositedoc.xml
Development Tools
For rapid application development , we need Integrated Development Environment
(IDE). The new Visual Studio.NET is such an IDE.
features of VS.NET
- Drag and Drop design
- IntelliSense features
- Syntax highlighting and auto-syntax checking
- Excellent debugging tools
- Integration with version control software such as Visual Source Safe (VSS)
- Easy project management
.NET Redistributable
In order to run application developed using .NET Framework the machine must have certain
‘runtime’ files installed. They are collectively called as .NET redistributable. provides one
redistributable installer that contains the common language runtime(more on that later) and
Microsoft .NET Framework components that are necessary to run .NET Framework
applications.
.NET ARCHITECURE

The .NET Framework itself can be divided into three parts:

 The CLR A managed execution environment that handles memory allocation, error
trapping, and interacting with the operating-system services.
 The Base Class Library An extensive collection of programming components and
application program interfaces (APIs).
 Two top-level development targets One for Web applications (ASP.NET) and
another for regular Windows applications (Windows Forms).

The advantages offered by the .NET Framework include shorter development cycles (code
reuse, fewer programming surprises, support for multiple programming languages), easier
deployment, fewer data type–related bugs due to integral type safety, reduced memory leaks
thanks to the garbage collector, and, in general more scalable, reliable applications.

Constituents of .NET Platform

The .NET consists of the following three main parts


 .NET Framework – a completely re-engineered development environment.
 .NET Products – applications from MS based on the .NET platform, including
Office and Visual Studio.
 .NET Services – facilitates 3rd party developers to create services on the .NET
 Platform.
1. At the bottom of the diagram is your Operating
System above that sits the .NET framework that acts
as an interface to it.
2. The .NET wraps the operating system, insulating
software developed with .NET from most operating
system specifics such as file handling and memory
allocation.

The Common Language Runtime (CLR)

1. heart of the .NET framework


2. .NET applications are compiled to a common language known as Microsoft
Intermediate Language or “IL”.
3. The CLR, then, handles the compiling the IL to machine language, at which point the
program is executed.
4. The CLR environment is also referred to as a managed environment, in which
common services, such as garbage collection and security, are automatically provided.

Managed Code:

Code that you develop with a language compiler that targets the runtime is
called managed code. it benefits from features such as
1. cross-language integration
2. cross-language exception handling
3. enhanced security, versioning and deployment support
4. a simplified model for component interaction
5. Debugging and profiling services.
Features of CLR
a. It is a common runtime for all languages targeting the .NET platform.
b. It acts as an agent that manages code at execution time and also provides core
Services such as memory management, thread management and remoting.
c. It enforces strict type safety and other forms of code accuracy that ensure
security and robustness.
d. It is responsible for enabling and facilitating the Common Type System. The
Common Type System allows classes that are written in any .NET language to
interoperate with even inherit from, with overrides classes written in any
language. So your COBOL.NET program can interoperate with your C#,
VB.NET, Eiffel.NET and with any other .NET language programs.
It offers a mechanism for cross-language exception handling.
e. It provides a more elegant way for resolving the versioning issues (also referred
to as the Dll Hell in our classic COM).
f. It provides a simplified model for component interaction.

The following figure illustrates the flow of activities from the source code to its execution
Common Type System:

The Common Type System defines how data types are declared, used, and managed in the
runtime, and is also an important part of the runtime’s support for the Cross- Language
Integration.

The common type system performs the following functions:

• Establishes a framework that enables cross-language integration, type safety, and


high performance code execution.
• Provides an object-oriented model that supports the complete implementation of
many programming languages.
• Defines rules that languages must follow, which helps ensure that objects written in
different languages can interact with each other.

CORE C# Structure of c#

A C# program consists of the following parts −

 Namespace declaration
 A class
 Class methods
 Class attributes
 A Main method
 Statements and Expressions
 Comments
Let us look at a simple code that prints the words "Hello World" −
using System;

namespace HelloWorldApplication {
class HelloWorld {
static void Main(string[] args) {
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}

When this code is compiled and executed, it produces the following result −
Hello World
Let us look at the various parts of the given program −
 The first line of the program using System; - the using keyword is used to include
the System namespace in the program. A program generally has
multiple using statements.
 The next line has the namespace declaration. A namespace is a collection of classes.
The HelloWorldApplication namespace contains the class HelloWorld.
 The next line has a class declaration, the class HelloWorld contains the data and
method definitions that your program uses. Classes generally contain multiple
methods. Methods define the behavior of the class. However, the HelloWorld class
has only one method Main.
 The next line defines the Main method, which is the entry point for all C# programs.
The Main method states what the class does when executed.
 The next line /*...*/ is ignored by the compiler and it is put to add comments in the
program.
 The Main method specifies its behavior with the
statement Console.WriteLine("Hello World");
WriteLine is a method of the Console class defined in the System namespace. This
statement causes the message "Hello, World!" to be displayed on the screen.
 The last line Console.ReadKey(); is for the VS.NET Users. This makes the program
wait for a key press and it prevents the screen from running and closing quickly
when the program is launched from Visual Studio .NET.
It is worth to note the following points −
 C# is case sensitive.
 All statements and expression must end with a semicolon (;).
 The program execution starts at the Main method.
 Unlike Java, program file name could be different from the class name.
Compiling and Executing the Program

If you are using Visual Studio.Net for compiling and executing C# programs, take the
following steps −
 Start Visual Studio.
 On the menu bar, choose File -> New -> Project.
 Choose Visual C# from templates, and then choose Windows.
 Choose Console Application.
 Specify a name for your project and click OK button.
 This creates a new project in Solution Explorer.
 Write code in the Code Editor.
 Click the Run button or press F5 key to execute the project. A Command Prompt
window appears that contains the line Hello World.
You can compile a C# program by using the command-line instead of the Visual Studio IDE

 Open a text editor and add the above-mentioned code.
 Save the file as helloworld.cs
 Open the command prompt tool and go to the directory where you saved the file.
 Type csc helloworld.cs and press enter to compile your code.
 If there are no errors in your code, the command prompt takes you to the next line
and generates helloworld.exe executable file.
 Type helloworld to execute your program.
 You can see the output Hello World printed on the screen.

DATATYPES

The Common Type System can be divided into two general categories of types,
1. Reference type
2. Value type
each of which is further divided into subcategories.

Data Type System Architecture


Value types
1. directly contain the data
2. instances of value types are either allocated on the stack or allocated inline in a
structure.
3. Value types can be built-in (implemented by the runtime), user-defined, or
enumerations.
4. The core value types supported by the .NET platform reside within the root of the
System namespace. There types are often referred to as the .NET “Primitive Types”.
They include:
• Boolean
• Byte
• Char
• DateTime
• Decimal
• Double
Reference types
1. store a reference to the value's memory address, and are allocated on the heap.
2. Reference types can be self-describing types, pointer types, or interface types.

Variables and Types

"Variables" are simply storage locations for data. You can place data into them and retrieve
their contents as part of a C# expression. The interpretation of the data in a variable is
controlled through "Types".

C# is a "Strongly Typed" language. Thus all operations on variables are performed with
consideration of what the variable's "Type" is. There are rules that define what operations are
legal in order to maintain the integrity of the data you put in a variable.

The C# simple types consist of the Boolean type and three numeric types - Integrals, Floating
Point, Decimal, and String. The term "Integrals", which is defined in the C# Programming
Language Specification, refers to the classification of types that include sbyte, byte, short,
ushort, int, uint, long, ulong, and char. More details are available in the Integral Types section
later in this lesson. The term "Floating Point" refers to the float and double types, which are
discussed, along with the decimal type, in more detail in the Floating Point and Decimal
Types section later in this lesson. The string type represents a string of characters and is
discussed in The String Type section, later in this lesson. The next section introduces the
boolean type.

The Boolean Type


Boolean types are declared using the keyword, bool. They have two values: true or false. In
other languages, such as C and C++, boolean conditions can be satisfied where 0 means false
and anything else means true.

Boxing and Unboxing

Boxing and unboxing is a essential concept in .NET’s type system. With Boxing and
unboxing one can link between value-types and reference-types by allowing any value of a
value-type to be converted to and from type object. Boxing and unboxing enables a unified
view of the type system wherein a value of any type can ultimately be treated as an object.

Converting a value type to reference type is called Boxing. Unboxing is the opposite
operation and is an explicit operation.

.NET provides a unified type system. All types including value types derive from the type
object. It is possible to call object methods on any value, even values of primitive types such
as int.

class Test
{
static void Main() {
int i = 1;
object o = i; // boxing
int j = (int) o; // unboxing
}
}

An int value can be converted to object and back again to int.

This example shows both boxing and unboxing. When a variable of a value type needs to be
converted to a reference type, an object box is allocated to hold the value, and the value is
copied into the box.

Unboxing is just the opposite. When an object box is cast back to its original value type, the
value is copied out of the box and into the appropriate storage location.

FLOW CONTROL (1): LOOP STATEMENTS

C# provides a number of the common loop statements:


while
do-while
for
foreach

while loop

syntax: while (expression) statement[s]

A 'while' loop executes a statement, or a block of statements wrapped in curly braces,


repeatedly until the condition specified by the boolean expression returns false. For instance,
the following code

1. int a = 0;
2. while (a < 3)
3. {
4. System.Console.WriteLine(a);
5. a++;
6. }

produces the following output:

0
1
2

do-while loop

syntax: do statement[s] while (expression)

A 'do-while' loop is just like a 'while' loop except that the condition is evaluated after the
block of code specified in the 'do' clause has been run. So even where the condition is
initially false, the block runs once. For instance, the following code outputs '4':

1. int a = 4;
2. do
3. {
4. System.Console.WriteLine(a);
5. a++;
6. } while (a < 3);

for loop

syntax: for (statement1; expression; statement2) statement[s]3


The 'for' clause contains three parts. Statement1 is executed before the loop is entered. The
loop which is then executed corresponds to the following 'while' loop:

statement 1
while (expression) {statement[s]3; statement2}

'For' loops tend to be used when one needs to maintain an iterator value. Usually, as in the
following example, the first statement initialises the iterator, the condition evaluates it against
an end value, and the second statement changes the iterator value.

1. for (int a =0; a<5; a++)


2. {
3. System.Console.WriteLine(a);
4. }

foreach loops

syntax: foreach (variable1 in variable2) statement[s]

The 'foreach' loop is used to iterate through the values contained by any object which implements the IE
interface. When a 'foreach' loop runs, the given variable1 is set in turn to each value exposed by the object
variable2. As we have seen previously, such loops can be used to access array values. So, we could loop th
values of an array in the following way:

1. int[] a = new int[]{1,2,3};


2. foreach (int b in a)
3. System.Console.WriteLine(b);

The main drawback of 'foreach' loops is that each value extracted (held in the given example
by the variable 'b') is read-only.

OBJECTS AND TYPES

Since C# is an object-oriented language, program is designed using objects and classes in


C#.In C#, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.In
other words, object is an entity that has state and behavior. Here, state means data and
behavior means functionality.

Object is a runtime entity, it is created at runtime.

Object is an instance of a class. All the members of the class can be accessed through object.

Let's see an example to create object using new keyword.

1. Student s1 = new Student();//creating an object of Student


In this example, Student is the type and s1 is the reference variable that refers to the instance
of Student class. The new keyword allocates memory at runtime.

C# Class

In C#, class is a group of similar objects. It is a template from which objects are created. It
can have fields, methods, constructors etc.

Let's see an example of C# class that has two fields only.

1. public class Student


2. {
3. int id;//field or data member
4. String name;//field or data member
5. }

C# Object and Class Example

Let's see an example of class that has two fields: id and name. It creates instance of the class,
initializes the object and prints the object value.

1. using System;
2. public class Student
3. {
4. int id;//data member (also instance variable)
5. String name;//data member(also instance variable)
6.
7. public static void Main(string[] args)
8. {
9. Student s1 = new Student();//creating an object of Student
10. s1.id = 101;
11. s1.name = "Sonoo Jaiswal";
12. Console.WriteLine(s1.id);
13. Console.WriteLine(s1.name);
14.
15. }
16. }

Output:

101
Sonoo Jaiswal

CLASSES AND STRUCT


Class and Object are the basic concepts of Object-Oriented Programming which revolve
around the real-life entities. A class is a user-defined blueprint or prototype from which
objects are created. 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.

Declaration of class

Generally, a class declaration contains only keyword class, followed by


an identifier(name) of the class. But there are some optional attributes that can be used with
class declaration according to the application requirement. In general, class declarations can
include these components, in order:

Modifiers: A class can be public or internal etc. By default modifier of class is internal.

Keyword class: A class keyword is used to declare the type class.

Class Identifier: The variable of type class is provided. The identifier(or name of class)
should begin with a initial letter which should be capitalized by convention.

Base class or Super class: The name of the class’s parent (superclass), if any, preceded by
the : (colon). This is optional.

Interfaces: A comma-separated list of interfaces implemented by the class, if any, preceded


by the : (colon). A class can implement more than one interface. This is optional.

Body: The class body is surrounded by { } (curly braces).

Constructors in class are used for initializing new objects. Fields are variables that provide
the state of the class and its objects, and methods are used to implement the behavior of the
class and its objects.

Example:

// declaring public class

public class Geeks

// field variable

public int a, b;
// member function or method

public void display()

Console.WriteLine(“Class & Objects in C#”);

STRUCT

Structure in C#

In C#, a structure is a value type data type. It helps you to make a single variable hold related
data of various data types. The struct keyword is used for creating a structure.

Structures are used to represent a record. Suppose you want to keep track of your books in a
library. You might want to track the following attributes about each book:

 Title
 Author
 Subject
 Book ID

Defining a Structure

To define a structure, you must use the struct statement. The struct statement defines a new
data type, with more than one member for your program.

For example, here is the way you can declare the Book structure:

struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};

Features of C# Structures

You have already used a simple structure named Books. Structures in C# are quite different
from that in traditional C or C++. The C# structures have the following features:

 Structures can have methods, fields, indexers, properties, operator methods, and
events.
 Structures can have defined constructors, but not destructors. However, you cannot
define a default constructor for a structure. The default constructor is automatically
defined and cannot be changed.
 Unlike classes, structures cannot inherit other structures or classes.
 Structures cannot be used as a base for other structures or classes.
 A structure can implement one or more interfaces.
 Structure members cannot be specified as abstract, virtual, or protected.
 When you create a struct object using the New operator, it gets created and the
appropriate constructor is called. Unlike classes, structs can be instantiated without
using the New operator.
 If the New operator is not used, the fields remain unassigned and the object cannot be
used until all the fields are initialized.

Class versus Structure

Classes and Structures have the following basic differences:

 classes are reference types and structs are value types


 structures do not support inheritance

INHERITANCE

One of the most important concepts in object-oriented programming is inheritance.


Inheritance allows us to define a class in terms of another class, which makes it easier to
create and maintain an application. This also provides an opportunity to reuse the code
functionality and speeds up implementation time.

When creating a class, instead of writing completely new data members and member
functions, the programmer can designate that the new class should inherit the members of an
existing class. This existing class is called the base class, and the new class is referred to as
the derived class.

The idea of inheritance implements the IS-A relationship. For example, mammal IS A
animal, dog IS-A mammal hence dog IS-A animal as well, and so on.

Base and Derived Classes

A class can be derived from more than one class or interface, which means that it can inherit
data and functions from multiple base classes or interfaces.

The syntax used in C# for creating derived classes is as follows:

<acess-specifier> class <base_class>


{
...
}
class <derived_class> : <base_class>
{
...
}
he inheritance concept is based on a base class and derived class. Let us see the definition of
a base and derived class.

Base class: is the class from which features are to be inherited into another class.
Derived class: it is the class in which the base class features are inherited.

Singleinheritance

It is the type of inheritance in which there is one base class and one derived class.

This is the type of inheritance in which there are multiple classes derived from one base class.
This type of inheritance is used when there is a requirement of one class feature that is
needed inmultipleclasses.

Multilevelinheritance

When one class is derived from another derived class then this type of inheritance is called
multilevelinheritance.
POLYMORPHISM

The word polymorphism means having many forms. In object-oriented programming


paradigm, polymorphism is often expressed as 'one interface, multiple
functions'.Polymorphism can be static or dynamic. In static polymorphism, the response to a
function is determined at the compile time. In dynamic polymorphism, it is decided at run-
time

Static Polymorphism
The mechanism of linking a function with an object during compile time is called early
binding. It is also called static binding. C# provides two techniques to implement static
polymorphism. They are −Function overloading and operator overloading

Function overloading
Function overloading allows using the same name for two or more functions. Each
redefinition of a function must use different types of parameter, sequence of parameter and
number of parameter. The type, sequence and number of parameter for a function is
called function signature. When you have multiple functions with the same name ,the
compiler identifies the function based on the parameter to the functions.

Function signature

The number of parameter

void add(int);

void add(int,float);

Type of parameter

int add(int);

float add(int,float);

order of parameter

int add(int,float);

float add(float,int);
Dynamic Polymorphism
Dynamic polymorphism is implemented by abstract classes and virtual functions.
C# allows you to create abstract classes that are used to provide partial class
implementation of an interface. Implementation is completed when a derived class
inherits from it. Abstract classes contain abstract methods, which are implemented
by the derived class. The derived classes have more specialized functionality.
Here are the rules about abstract classes −
 You cannot create an instance of an abstract class
 You cannot declare an abstract method outside an abstract class
 When a class is declared sealed, it cannot be inherited, abstract classes
cannot be declared sealed.
 using System;

 abstract class Shape {
 public abstract int area();
 }

 class Rectangle: Shape {
 private int length;
 private int width;

 public Rectangle( int a = 0, int b = 0) {
 length = a;
 width = b;
 }
 public override int area () {
 Console.WriteLine("Rectangle class area :");
 return (width * length);
 }
 }
 class RectangleTester
 {
 static void Main()
 {
 Rectangle r = new Rectangle(10, 7);
 double a = r.area();
 Console.WriteLine("Area: {0}",a);
 Console.ReadKey();
 }
 }

OUTPUT

Rectangle class area :


Area: 70

Abstract methods are the methods without any body. When a derived class inherits
the abstract method from the abstract class, it must override the abstract methods.
The requirement is enforced at run time so it is called dynamic polymorphism.

USE OF VIRTUAL KEYWORD


When you have a function defined in a class that you want to be implemented in an
inherited class(es), you use virtual functions. The virtual functions could be
implemented differently in different inherited class and the call to these functions will
be decided at runtime.

using System;

class animal

public virtual void food()

Console.WriteLine(“good”);

}
class cat:animal

public override void food()

Console.WriteLine(“cat”);

class dog:animal

public virtual void food()

Console.WriteLine(“dog”);

class sample

public void call(animal a)

a.food();

class test

{
public static void Main()

sample s=new sample(); o/p

cat c=new cat(); cat

dog d=new dog(); dog

s.call(c);

s.cal(d);

In the code,base class animal has a virtual function named food().The derived
class cat and dog override the method food() of the base class animal and
implement their own functionality.The method named call() takes argument of
animal class and calls food() method to,which in turn will call the most
appropriate derived method.

ARRAY

A variable is used to store a literal value, whereas an array is used to store multiple literal
values.

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.
Here you will learn about the single-dimensional array.

The following figure illustrates an array representation.


Array Representation

Array Declaration and Initialization

An array can be declared using by specifying the type of its elements with square brackets.

Example: Array Declaration


int[] evenNums; // integer array

string[] cities; // string array


The following declares and adds values into an array in a single statement.

Example: Array Declaration & Initialization


int[] evenNums = new int[5]{ 2, 4, 6, 8, 10 };

string[] cities = new string[3]{ "Mumbai", "London", "New York" };


Above, evenNums array can store up to five integers. The number 5 in the square
brackets new int[5] specifies the size of an array. In the same way, the size of cities array is
three. Array elements are added in a comma-separated list inside curly braces { }.

Arrays type variables can be declared using var without square brackets.

Example: Array Declaration using var


var evenNums = new int[]{ 2, 4, 6, 8, 10};

var cities = new string[]{ "Mumbai", "London", "New York" };


If you are adding array elements at the time of declaration, then size is optional. The compiler
will infer its size based on the number of elements inside curly braces, as shown below.

Example: Short Syntax of Array Declaration


int[] evenNums = { 2, 4, 6, 8, 10};

string[] cities = { "Mumbai", "London", "New York" }


Example program
C# support multidimensional array as “arrays of arrays”.The above
statement creates array having different column size for each row.Variable
size arrays are called jagged array.
ARRAYLIST class

System.Collectionss namespace defines a class known as ArrayList that can


store dynamically sized array of objects.The ArrayList class includes a number
of methods to support operations such as sorting,removing and enumerating itc
contents.It is very similar to an array,except that it has the ability to grow
dynamically.We can create an array list by indicating initial capacity.

ArrayList c=new ArrayList(30);

It creates C with acapacity to store 30 objects.If we don not specify the size,it
defaults to 16.

METHODS/PROPERTY

Add()- Add an object to list

Clear()- Removes all the elements from the list

Contains()- Determines if an element in the list

CopyTo()- Copies list to another

Insert()- Insert an element to the list


Remove()- Remove the first occurrence of an element

RemoveAt()- Remove the element at the specified place

Sort() Sort the element

Capacity- gets or sets the element in the list

Count- Give the number of elements currently in thelist


TUPLES

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>


The following example creates a tuple with three elements:

Tuple<int, string, string> person =


new Tuple <int, string, string>(1, "Steve", "Jobs");
In the above example, we created an instance of the Tuple which holds a record of a person.
We specified a type for each element and passed values to the constructor. Specifying the
type of each element is cumbersome. So, C# includes a static helper class Tuple which
returns an instance of the Tuple<T> without specifying the type of each element, as shown
below.

var person = Tuple.Create(1, "Steve", "Jobs");


A tuple can only include maximum eight elements. It gives a compiler error when you try to
include more than eight elements.

var numbers = Tuple.Create(1, 2, 3, 4, 5, 6, 7, 8);


Accessing Tuple Elements

The elements of a tuple can be accessed with Item<elementNumber> properties e.g. Item1,
Item2, Item3 and so on up to Item7 property. The Item1 property returns the first element,
Item2 returns the second element and so on. The last element (the 8th element) will be
returned using the Rest property.

Example: Accessing Tuple Elements


var person = Tuple.Create(1, "Steve", "Jobs");
person.Item1; // returns 1
person.Item2; // returns "Steve"
person.Item3; // returns "Jobs"

var numbers = Tuple.Create("One", 2, 3, "Four", 5, "Six", 7, 8);


numbers.Item1; // returns "One"
numbers.Item2; // returns 2
numbers.Item3; // returns 3
numbers.Item4; // returns "Four"
numbers.Item5; // returns 5
numbers.Item6; // returns "Six"
numbers.Item7; // returns 7
numbers.Rest; // returns (8)
numbers.Rest.Item1; // returns 8

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

Implicit Casting

Implicit casting is done automatically when passing a smaller size type to a larger size type:

Example

int myInt = 9;

double myDouble = myInt; // Automatic casting: int to double


Console.WriteLine(myInt); // Outputs 9

Console.WriteLine(myDouble); // Outputs 9

Explicit Casting

Explicit casting must be done manually by placing the type in parentheses in front of the
value:

Example

double myDouble = 9.78;

int myInt = (int) myDouble; // Manual casting: double to int

Console.WriteLine(myDouble); // Outputs 9.78

Console.WriteLine(myInt); // Outputs 9

INDEXERS

An indexer allows an object to be indexed such as an array. When you define an indexer for
a class, this class behaves similar to a virtual array. You can then access the instance of this
class using the array access operator ([ ]).It is also called as smart array.

Syntax

A one dimensional indexer has the following syntax −


element-type this[int index] {

// The get accessor.


get {
// return the value specified by index
}

// The set accessor.


set {
// set the value specified by index
}
}

Use of Indexers

Declaration of behavior of an indexer is to some extent similar to a property. similar to the


properties, you use get and set accessors for defining an indexer. However, properties return
or set a specific data member, whereas indexers returns or sets a particular value from the
object instance. In other words, it breaks the instance data into smaller parts and indexes
each part, gets or sets each part.
Defining a property involves providing a property name. Indexers are not defined with
names, but with the this keyword, which refers to the object instance. The following
example demonstrates the concept −

using System;

namespace IndexerApplication {

class IndexedNames {
private string[] namelist = new string[size];
static public int size = 10;

public IndexedNames() {
for (int i = 0; i < size; i++)
namelist[i] = "N. A.";
}
public string this[int index] {
get {
string tmp;

if( index >= 0 && index <= size-1 ) {


tmp = namelist[index];
} else {
tmp = "";
}

return ( tmp );
}
set {
if( index >= 0 && index <= size-1 ) {
namelist[index] = value;
}
}
}
static void Main(string[] args) {
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";

for ( int i = 0; i < IndexedNames.size; i++ ) {


Console.WriteLine(names[i]);
}
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result −
Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.

You might also like