0% found this document useful (0 votes)
138 views43 pages

UNIT-1 - .Net Notes

.NET is a developer platform comprising tools, languages, and libraries for building various applications, featuring components like CLR, BCL, and support for multiple programming languages. The .NET Framework provides a common platform for applications built in different languages, primarily for Windows, while VB.NET enhances development with object-oriented programming and modern features. Key topics covered include differences between VB6 and VB.NET, object-oriented programming concepts, data types, and various components of the .NET ecosystem.

Uploaded by

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

UNIT-1 - .Net Notes

.NET is a developer platform comprising tools, languages, and libraries for building various applications, featuring components like CLR, BCL, and support for multiple programming languages. The .NET Framework provides a common platform for applications built in different languages, primarily for Windows, while VB.NET enhances development with object-oriented programming and modern features. Key topics covered include differences between VB6 and VB.NET, object-oriented programming concepts, data types, and various components of the .NET ecosystem.

Uploaded by

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

lOMoARcPSD|57027414

UNIT-1 - .net notes

Bsc information technology (Bharathiar University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by vani K ([email protected])
lOMoARcPSD|57027414

UNIT-1
CONTENTS:
 Introduction to .Net
 Dot Net Framework
 Difference between VB6 and VB.Net
 Object-Oriented Programming and VB.Net
 Data Types
 Variables
 Operators
 Arrays
 Conditional Logic

1. Introduction to .Net
What is .NET?

.NET is a developer platform made up of tools, programming languages, and


libraries for building different types of applications. It provides a consistent
programming model and extensive framework to simplify and speed up
development.

Key Components/Features of .NET:

1. Common Language Runtime (CLR):


o The CLR is the runtime environment that manages the execution of
.NET programs. It provides services such as memory management,
exception handling, and security.
2. Base Class Library (BCL):
o The BCL is a collection of reusable classes, types, and APIs that are
fundamental to .NET development. It includes classes for tasks like
file I/O, networking, and data access.
3. Languages:
o .NET supports multiple programming languages, including C#, Visual
Basic (VB.NET), F#, and others. These languages share a common set

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

of libraries and tools, allowing developers to choose the language they


are most comfortable with.
4. Integrated Development Environment (IDE):
o Visual Studio is the primary IDE for .NET development, offering a
rich set of tools for coding, debugging, and deploying applications.
Visual Studio Code is also popular for cross-platform .NET
development.
5. Frameworks:
o .NET includes different frameworks tailored for specific types of
applications:
 ASP.NET: For building web applications and services.
 Windows Forms and WPF: For building desktop applications
with rich user interfaces.
 Xamarin: For building cross-platform mobile applications.
 Entity Framework: For object-relational mapping (ORM) and
data access.

Cross-Platform and Open Source:

 With the introduction of .NET Core and later .NET 5/6, .NET became cross-
platform and open source. This means that developers can build and run
.NET applications on Windows, macOS, and Linux, enhancing flexibility
and scalability.

Package Management:

 NuGet: NuGet is the package manager for .NET, allowing developers to


easily discover, install, and manage libraries and tools necessary for their
projects.

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

Characteristics of .NET:

2. Dot Net Framework


.Net Framework is a virtual machine that provide a common platform to run an
application that was built using the different language such as C#, VB.NET, Visual
Basic, etc. It is also used to create a form based, console-based, mobile and web-
based application or services that are available in Microsoft environment. But it is
not a platform independent as the Java. So, its application runs only to the windows
platform.

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

Components of .NET Framework


There are following components of .NET Framework:

1. CLR (Common Language Runtime)


2. CTS (Common Type System)
3. BCL (Base Class Library)
4. CLS (Common Language Specification)
5. FCL (Framework Class Library)
6. .NET Assemblies
7. XML Web Services
8. Window Services

CLR (common language runtime)

It is an important part of a .NET framework that works like a virtual component of


the .NET Framework to execute the different languages program like c#, Visual
Basic, etc. A CLR also helps to convert a source code into the byte code, and this
byte code is known as CIL (Common Intermediate Language) or MSIL (Microsoft
Intermediate Language). After converting into a byte code, a CLR uses a JIT
compiler at run time that helps to convert a CIL or MSIL code into the machine or
native code.

CTS (Common Type System)

It specifies a standard that represent what type of data and value can be defined and
managed in computer memory at runtime. A CTS ensures that programming data
defined in various languages should be interact with each other to share information.
For example, in C# we define data type as int, while in VB.NET we define integer
as a data type.

BCL (Base Class Library)

The base class library has a rich collection of libraries features and functions that
help to implement many programming languages in the .NET Framework, such as
C #, F #, Visual C ++, and more. Furthermore, BCL divides into two parts:

1. User defined class library

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

o Assemblies - It is the collection of small parts of deployment an


application's part. It contains either the DLL (Dynamic Link Library)
or exe (Executable) file.
1. In LL, it uses code reusability, whereas in exe it contains only
output file/ or application.
2. DLL file can't be open, whereas exe file can be open.
3. DLL file can't be run individually, whereas in exe, it can run
individually.
4. In DLL file, there is no main method, whereas exe file has main
method.
2. Predefined class library
o Namespace - It is the collection of predefined class and method that
present in .Net. In other languages such as, C we used header files, in
java we used package similarly we used "using system" in .NET, where
using is a keyword and system is a namespace.

CLS (Common language Specification)

It is a subset of common type system (CTS) that defines a set of rules and regulations
which should be followed by every language that comes under the .net framework.
In other words, a CLS language should be cross-language integration or
interoperability. For example, in C# and VB.NET language, the C# language
terminate each statement with semicolon, whereas in VB.NET it is not end with
semicolon, and when these statements execute in .NET Framework, it provides a
common platform to interact and share information with each other.

Microsoft .NET Assemblies

A .NET assembly is the main building block of the .NET Framework. It is a small
unit of code that contains a logical compiled code in the Common Language
infrastructure (CLI), which is used for deployment, security and versioning. It
defines in two parts (process) DLL and library (exe) assemblies. When the .NET
program is compiled, it generates a metadata with Microsoft Intermediate Language,
which is stored in a file called Assembly.

FCL (Framework Class Library)

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

It provides the various system functionality in the .NET Framework that includes
classes, interfaces and data types, etc. to create multiple functions and different types
of application such as desktop, web, mobile application, etc. In other words, it can
be defined as, it provides a base on which various applications, controls and
components are built in .NET Framework.

3. Difference between VB6 and VB.Net


VB6:
Visual Basic 6.0 (VB6) was a programming language and integrated development
environment (IDE) developed by Microsoft in the late 1990s. It was widely used
for building Windows applications due to its simplicity, rapid application
development capabilities, and visual design tools. Here’s a short overview:

1. Programming Language: VB6 used the BASIC programming language


variant. It featured a straightforward syntax with English-like keywords,
making it easy for beginners to learn.
2. IDE (Integrated Development Environment): VB6 provided a visual
environment where developers could design user interfaces by dragging and
dropping controls (like buttons and textboxes) onto forms.
3. Event-Driven Programming: Applications were built around responding to
user actions and events (such as button clicks or form loading), making it
suitable for building interactive GUI applications.
4. Database Access: VB6 included support for data access through
technologies like ADO (ActiveX Data Objects) and DAO (Data Access
Objects), allowing developers to connect their applications to databases.
5. Component-Based Development: VB6 supported creating and using
reusable components known as ActiveX controls, facilitating modular and
scalable application development.
6. Legacy and Transition: Microsoft shifted focus to .NET Framework and
VB.NET in the early 2000s, leading to VB6 being phased out. Despite its
end of support in 2008, many legacy applications built with VB6 are still in
use today.

VB.NET:

VB.NET (Visual Basic .NET) is a modern, object-oriented programming language


and development environment introduced by Microsoft as part of the .NET
Framework. Here’s a short overview of VB.NET:

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

1. Object-Oriented Programming: VB.NET supports object-oriented


programming (OOP) concepts such as inheritance, encapsulation, and
polymorphism. This allows developers to write modular, reusable code and
build complex applications more efficiently.
2. Integration with .NET Framework: VB.NET is integrated with the .NET
Framework, providing access to a rich set of libraries and APIs for building
various types of applications, including web applications, desktop
applications, and services.
3. Event-Driven Programming: Similar to VB6, VB.NET uses an event-
driven programming model where developers write code to respond to user
actions and system events. This makes it suitable for building interactive and
responsive applications.
4. Language Features: VB.NET has modern language features such as
exception handling, generics, lambda expressions, and LINQ (Language
Integrated Query), which simplify common programming tasks and improve
code readability.
5. Tooling and IDE: VB.NET development is supported by Visual Studio,
Microsoft’s integrated development environment (IDE). Visual Studio
provides powerful tools for coding, debugging, testing, and deploying
applications.
6. Cross-Platform Development: With .NET Core and later versions (.NET
5/6), VB.NET applications can be developed to run cross-platform on
Windows, macOS, and Linux, enhancing flexibility and scalability.
7. Database Integration: VB.NET includes robust data access technologies
like ADO.NET for connecting to databases, enabling developers to build
database-driven applications with ease.
8. Web Development: VB.NET can be used to build web applications using
ASP.NET, a framework for creating dynamic and scalable web pages.
ASP.NET supports both Web Forms and MVC (Model-View-Controller)
patterns.
9. Community and Support: VB.NET benefits from a large community of
developers, extensive documentation, tutorials, and support resources
provided by Microsoft and the community.

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

4. Object-Oriented Programming and VB.Net


1. Classes and Objects
Class: A blueprint for creating objects. It defines properties, methods,
and events.
Object: An instance of a class.

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

2. Encapsulation
Encapsulation is the bundling of data and methods that operate on that
data within one unit (class), and restricting access to some of the object's
components.

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

3. Inheritance
Inheritance allows a class to inherit properties and methods from another
class.

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

4. Polymorphism
Polymorphism allows methods to do different things based on the object
it is acting upon, even though they share the same name.

VB.NET Implementation:
' Base class
Public Class Animal
Public Overridable Sub MakeSound()
Console.WriteLine("Some generic animal sound")
End Sub
End Class

' Derived class


Public Class Dog
Inherits Animal

Public Overrides Sub MakeSound()


Console.WriteLine("Woof")
End Sub
End Class

Public Class Cat


Inherits Animal

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

Public Overrides Sub MakeSound()


Console.WriteLine("Meow")
End Sub
End Class

' Using polymorphism


Dim animals As Animal() = {New Dog(), New Cat()}
For Each animal As Animal In animals
animal.MakeSound()
Next

5. Abstraction
Abstraction is the process of hiding the implementation details and
showing only the functionality to the user.

VB.NET Implementation:
' Abstract base class
Public MustInherit Class Shape
' Abstract method
Public MustOverride Function Area() As Double
End Class

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

' Derived class


Public Class Circle
Inherits Shape

Public Property Radius As Double

Public Sub New(radius As Double)


Me.Radius = radius
End Sub

Public Overrides Function Area() As Double


Return Math.PI * Math.Pow(Radius, 2)
End Function
End Class

' Using abstraction


Dim myCircle As New Circle(5)
Console.WriteLine("Area of the circle: " & myCircle.Area())

6. Constructors and Destructors


Constructor: A special method that is called when an object is
instantiated.
Destructor: A method that is called when an object is destroyed.

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

7. Interfaces
An interface defines a contract that can be implemented by classes and
structs. It specifies what methods and properties a class should
implement.

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

8. Method Overloading
Method overloading allows a class to have multiple methods with the
same name but different parameters.

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

5. Data Types
A Data Type refers to which type of data or value is assigning to a variable or
function so that a variable can hold a defined data type value. For example, when we
declare a variable, we have to tell the compiler what type of data or value is allocated
to different kinds of variables to hold different amounts of space in computer
memory.

Syntax:

Dim Variable_Name as DataType

VariableName: It defines the name of the variable that you assign to store values.

DataType: It represents the name of the data type that you assign to a variable.

a) Floating-Point Types

 Single: 32-bit single-precision floating-point (-3.402823E38 to


3.402823E38)
 Double: 64-bit double-precision floating-point (-1.79769313486232E308 to
1.79769313486232E308)

Example in VB.NET:

vb.net
Copy code
Dim f As Single = 3.14F
Dim d As Double = 3.14

b) Decimal Type

 Decimal: 128-bit precise decimal numbers with 28-29 significant digits


(used for financial calculations).

Example in VB.NET:

vb.net
Copy code
Dim dec As Decimal = 1000000.123456789D

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

c) Boolean Type

 Boolean: Represents true or false values.

Example in VB.NET:

vb.net
Copy code
Dim flag As Boolean = True

d) Character and String Types

 Char: Represents a single 16-bit Unicode character.


 String: Represents a sequence of Unicode characters.

Example in VB.NET:

vb.net
Copy code
Dim ch As Char = "A"c
Dim str As String = "Hello, World!"

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

6. Variables

Variable Declaration

In .NET, variables are declared using a specific syntax that includes the Dim
keyword in VB.NET, followed by the variable name and type.

Example in VB.NET:

Dim variableName As DataType

Example:

Dim age As Integer

Dim name As String

2. Variable Initialization

Variables can be initialized at the time of declaration or later in the code.


Initialization means assigning an initial value to the variable.

Example in VB.NET:

' Initialization at declaration


Dim age As Integer = 25
Dim name As String = "John"

' Initialization later


Dim height As Double
height = 5.9

3. Variable Types

Variables in .NET can be of different types, broadly categorized into:

a. Primitive Data Types:

 Integer: Dim number As Integer = 10


 Double: Dim price As Double = 9.99
 Boolean: Dim isTrue As Boolean = True

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

 String: Dim greeting As String = "Hello"

b. User-Defined Types:

 Enums: Dim today As DaysOfWeek = DaysOfWeek.Monday


 Structures: Dim point As New Point(10, 20)

c. Reference Types:

 Classes: Dim person As New Person()


 Arrays: Dim numbers() As Integer = {1, 2, 3}
 Delegates: Dim del As New MyDelegate(AddressOf MyMethod)

4. Scope and Lifetime of Variables

The scope of a variable defines the part of the program where the variable is
accessible, and the lifetime defines how long the variable exists in memory.

a. Local Variables:

 Declared within a method or a block.


 Scope is limited to the method or block.
 Lifetime ends when the method or block exits.

Example in VB.NET:

Sub ExampleMethod()
Dim localVar As Integer = 10
' localVar is accessible here
End Sub
' localVar is not accessible here

b. Class-Level Variables (Fields):

 Declared within a class but outside any method.


 Scope is the entire class.
 Lifetime is the duration of the object.

Example in VB.NET:

Public Class MyClass

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

Private classLevelVar As Integer = 20

Public Sub ShowValue()


Console.WriteLine(classLevelVar)
End Sub
End Class

c. Module-Level Variables:

 Declared within a module.


 Scope is the entire module.
 Lifetime is the duration of the application.

Example in VB.NET:

Module MyModule
Private moduleLevelVar As Integer = 30

Sub Main()
Console.WriteLine(moduleLevelVar)
End Sub
End Module

d. Static Variables:

 Declared with the Static keyword.


 Scope is limited to the method or block where it is declared.
 Lifetime is the duration of the application.

Example in VB.NET:

Sub ExampleMethod()
Static counter As Integer = 0
counter += 1
Console.WriteLine(counter)
End Sub

5. Variable Type Inference

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

VB.NET supports type inference, allowing the compiler to determine the type of a
variable based on the assigned value using the Dim keyword with the Option Infer
statement enabled.

Example in VB.NET:

Option Infer On

Dim inferredInteger = 42 ' Integer


Dim inferredString = "Hello" ' String
Dim inferredDouble = 3.14 ' Double

6. Constants

Constants are variables whose values cannot be changed once assigned. They are
declared using the Const keyword.

Example in VB.NET:

Const PI As Double = 3.14159


Const MaxSize As Integer = 100

7. Read-Only Variables

Read-only variables can be assigned a value only once, either at the time of
declaration or in the constructor (if within a class).

Example in VB.NET:

Public Class MyClass


Public ReadOnly CreationDate As Date

Public Sub New()


CreationDate = DateTime.Now
End Sub
End Class

8. Arrays

Arrays are collections of variables of the same type. They can be single-
dimensional, multi-dimensional, or jagged arrays.

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

Example in VB.NET:

' Single-dimensional array


Dim numbers() As Integer = {1, 2, 3, 4, 5}

' Multi-dimensional array


Dim matrix(2, 2) As Integer

' Jagged array


Dim jaggedArray()() As Integer = {New Integer() {1, 2}, New Integer() {3, 4, 5}}

9. Dynamic Variables

In VB.NET, dynamic variables can hold values of any type. They are declared
using the Object type.

Example in VB.NET:

Dim dynamicVar As Object


dynamicVar = 10
dynamicVar = "Now I am a string"
dynamicVar = New Date()

10. Nullable Types

Nullable types allow value types to be assigned a null value. They are useful for
database operations and other scenarios where a value might be missing.

Example in VB.NET:

Dim nullableInt As Nullable(Of Integer) = Nothing


If Not nullableInt.HasValue Then
Console.WriteLine("Value is null")
End If

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

7. Operators

Operator is a special symbol that tells the compiler to perform the specific logical
or mathematical operation on the data values. The data value itself (which can be
either a variable or a constant) is called an operand, and the Operator performs
various operations on the operand.

For example: In the expression,

3+2-1

The symbol + and - are the Operators, and the 3, 2, and 1 are operands.

Different Types of .NET Operators

Following are the different types of Operators available in .NET:

o Arithmetic Operators
o Comparison Operators
o Logical and Bitwise Operators
o Bit Shift Operators
o Assignment Operators
o Concatenation Operators
o Miscellaneous Operators

Arithmetic Operators Example

Sub Main()

' Declare and initialize variables

Dim num1 As Integer = 10

Dim num2 As Integer = 3

' Addition

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

Dim additionResult As Integer = num1 + num2

Console.WriteLine("Addition: {0} + {1} = {2}", num1, num2,


additionResult)

' Subtraction

Dim subtractionResult As Integer = num1 - num2

Console.WriteLine("Subtraction: {0} - {1} = {2}", num1, num2,


subtractionResult)

' Multiplication

Dim multiplicationResult As Integer = num1 * num2

Console.WriteLine("Multiplication: {0} * {1} = {2}", num1, num2,


multiplicationResult)

' Division

Dim divisionResult As Double = num1 / num2

Console.WriteLine("Division: {0} / {1} = {2}", num1, num2,


divisionResult)

' Integer Division

Dim integerDivisionResult As Integer = num1 \ num2

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

Console.WriteLine("Integer Division: {0} \ {1} = {2}", num1, num2,


integerDivisionResult)

' Modulus

Dim modulusResult As Integer = num1 Mod num2

Console.WriteLine("Modulus: {0} Mod {1} = {2}", num1, num2,


modulusResult)

' Exponentiation

Dim exponentiationResult As Double = num1 ^ num2

Console.WriteLine("Exponentiation: {0} ^ {1} = {2}", num1, num2,


exponentiationResult)

End Sub

End Module

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

Comparison Operators Example

Sub Main()

Dim a As Integer = 10

Dim b As Integer = 20

Dim result As Boolean

' Equal to

result = (a = b)

Console.WriteLine("a = b: " & result)

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

' Not equal to

result = (a <> b)

Console.WriteLine("a <> b: " & result)

' Greater than

result = (a > b)

Console.WriteLine("a > b: " & result)

' Less than

result = (a < b)

Console.WriteLine("a < b: " & result)

' Greater than or equal to

result = (a >= b)

Console.WriteLine("a >= b: " & result)

' Less than or equal to

result = (a <= b)

Console.WriteLine("a <= b: " & result)

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

End Sub

End Module

Logical and Bitwise Operators

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

Bit Shift Operators

Bit shift operators in .NET are used to shift the bits of a number to the left or right.
These operators are useful for low-level programming tasks such as manipulating
binary data, performing arithmetic operations efficiently, or encoding/decoding
information.

Types of Bit Shift Operators in .NET

1. Left Shift (<<): Shifts the bits of the number to the left by the specified
number of positions. Zeroes are shifted into the lower-order bits.
2. Right Shift (>>): Shifts the bits of the number to the right by the specified
number of positions. For signed integers, the sign bit is shifted into the
higher-order bits (arithmetic shift). For unsigned integers, zeroes are shifted
into the higher-order bits (logical shift).

Example in VB.NET

Module BitShiftExample
Sub Main()
Dim num As Integer = 8 ' Binary: 0000 1000
Dim leftShift As Integer
Dim rightShift As Integer

' Left shift by 2 positions


leftShift = num << 2 ' Result: 0010 0000 (32 in decimal)

' Right shift by 2 positions


rightShift = num >> 2 ' Result: 0000 0010 (2 in decimal)

Console.WriteLine("Original number: " & num)


Console.WriteLine("After left shift by 2 positions: " & leftShift)
Console.WriteLine("After right shift by 2 positions: " & rightShift)
End Sub
End Module

Explanation

1. Left Shift (<<):


o num << 2 shifts the bits of num (which is 8 or 0000 1000 in binary)
two positions to the left.

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

o The result is 0010 0000, which is 32 in decimal.


2. Right Shift (>>):
o num >> 2 shifts the bits of num two positions to the right.
o The result is 0000 0010, which is 2 in decimal.

Output

yaml
Copy code
Original number: 8
After left shift by 2 positions: 32
After right shift by 2 positions: 2

Assignment Operator

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

Concatenation Operator

Example

Miscellaneous Operators

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

8. Arrays
Arrays in .NET are a fundamental data structure used to store collections of
variables of the same type. They are useful for managing and manipulating lists of
data. Here’s a detailed look at arrays in .NET, covering their types, declarations,
initialization, and usage in VB.NET.
1. Types of Arrays
a. Single-Dimensional Arrays
The simplest form of arrays, where elements are accessed by a single index.
Example in VB.NET:
Dim numbers() As Integer = {1, 2, 3, 4, 5}
b. Multi-Dimensional Arrays
Arrays with more than one dimension, allowing for complex data structures like
matrices.
Example in VB.NET:
Dim matrix(2, 2) As Integer
' Initialize the 2D array
matrix(0, 0) = 1
matrix(0, 1) = 2
matrix(1, 0) = 3
matrix(1, 1) = 4
c. Jagged Arrays
Arrays of arrays, allowing for a non-uniform structure where each sub-array can
have a different length.
Example in VB.NET:
Dim jaggedArray()() As Integer = { _
New Integer() {1, 2, 3}, _
New Integer() {4, 5}, _

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

New Integer() {6, 7, 8, 9} _


}
2. Array Declaration and Initialization
a. Declaration
Arrays must be declared with a specific type and can be either initialized at the
time of declaration or separately.
Example in VB.NET:
Dim fruits(2) As String ' Array declaration with 3 elements (0, 1, 2)
Dim numbers() As Integer ' Declaration without initialization
b. Initialization
Arrays can be initialized with values during declaration or assigned later.
Example in VB.NET:
' Initialization during declaration
Dim colors() As String = {"Red", "Green", "Blue"}
' Initialization after declaration
Dim scores(4) As Integer
scores(0) = 100
scores(1) = 95
3. Accessing Array Elements
Elements are accessed using zero-based indexing.
Example in VB.NET:
Dim firstColor As String = colors(0) ' Accessing the first element
Console.WriteLine(firstColor) ' Output: Red
4. Array Length and Bounds
The `Length` property returns the total number of elements in a one-dimensional
array, while `GetLength` is used for multi-dimensional arrays.

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

Example in VB.NET:
Dim totalColors As Integer = colors.Length ' For single-dimensional arrays
Dim numRows As Integer = matrix.GetLength(0) ' For multi-dimensional arrays
Dim numCols As Integer = matrix.GetLength(1)
5. Iterating Through Arrays
- Arrays can be iterated using loops such as `For`, `For Each`, and `While`.
Example in VB.NET:
' Using For loop
For i As Integer = 0 To colors.Length - 1
Console.WriteLine(colors(i))
Next
' Using For Each loop
For Each color As String In colors
Console.WriteLine(color)
Next
6. Copying Arrays
Arrays can be copied using the `Array.Copy` method or the `Clone` method.
Example in VB.NET:
Dim newColors() As String = CType(colors.Clone(), String())
Array.Copy(colors, newColors, colors.Length)
7. Array Manipulation
Arrays can be manipulated with methods like `Sort`, `Reverse`, and `Resize`.
Example in VB.NET:
' Sorting an array
Array.Sort(colors)

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

' Reversing an array


Array.Reverse(colors)
' Resizing an array
ReDim Preserve colors(5) ' Resize array while preserving existing data
8. Using `Array` Class Methods
The `Array` class in .NET provides various static methods for array operations.
Example in VB.NET:
' Using Array class methods
Dim searchIndex As Integer = Array.IndexOf(colors, "Green") ' Find the index of
"Green"
Dim subArray() As String = Array.CreateInstance(GetType(String), 2) ' Create a
new array
9. Jagged Array Usage
Accessing elements of a jagged array involves specifying multiple indices.
Example in VB.NET:
Dim value As Integer = jaggedArray(2)(1) ' Accessing the element 7 in
jaggedArray
Console.WriteLine(value) ' Output: 7
10. Array Initialization Using `New` Keyword
Arrays can also be initialized using the `New` keyword, especially when
specifying the size without initial values.
Example in VB.NET:
Dim emptyArray(4) As Integer ' Initializes an array with 5 elements (default values
are 0)

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

9. Conditional Logic
Conditional logic in .NET allows you to execute different code paths based on
certain conditions. This is a fundamental aspect of programming, enabling you to
make decisions and control the flow of execution in your applications. Here’s an
overview of the primary ways to implement conditional logic in .NET using
VB.NET:
1. If...Then...Else Statements
The `If...Then...Else` statement is used to execute code based on a condition. You
can also use `ElseIf` to check multiple conditions.
Syntax:
If condition Then
' Code to execute if condition is True
ElseIf anotherCondition Then
' Code to execute if anotherCondition is True
Else
' Code to execute if none of the above conditions are True
End If
Example:
Dim age As Integer = 20
If age < 13 Then
Console.WriteLine("Child")
ElseIf age >= 13 AndAlso age < 20 Then
Console.WriteLine("Teenager")
Else
Console.WriteLine("Adult")
End If

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

2. Select Case Statements


The `Select Case` statement is useful when you need to handle multiple discrete
values. It provides a cleaner way to perform multiple conditional checks compared
to nested `If...Then...Else` statements.
Syntax:
Select Case expression
Case value1
' Code to execute if expression = value1
Case value2
' Code to execute if expression = value2
Case Else
' Code to execute if expression doesn't match any cases
End Select
Example:
Dim dayOfWeek As Integer = 3
Select Case dayOfWeek
Case 1
Console.WriteLine("Monday")
Case 2
Console.WriteLine("Tuesday")
Case 3
Console.WriteLine("Wednesday")
Case Else
Console.WriteLine("Other day")
End Select

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

3. Logical Operators
Logical operators are used to combine multiple conditions in `If` statements or
`Select Case` cases. Common logical operators include:
And: Returns `True` if both conditions are `True`.
Or: Returns `True` if at least one condition is `True`.
Not: Inverts the Boolean value of the condition.
AndAlso: Returns `False` as soon as one condition is `False` (short-circuiting).
OrElse: Returns `True` as soon as one condition is `True` (short-circuiting).
Example:
Dim x As Integer = 10
Dim y As Integer = 20
If x > 5 AndAlso y < 30 Then
Console.WriteLine("Both conditions are met.")
End If
4. Ternary Conditional Operator
VB.NET does not support the ternary conditional operator (`? :`) directly, but you
can achieve similar functionality using the `If` function.
Syntax:
Dim result As String = If(condition, trueValue, falseValue)
Example:
Dim score As Integer = 85
Dim result As String = If(score >= 60, "Pass", "Fail")
Console.WriteLine(result) ' Output: Pass
5. Error Handling with Try...Catch...Finally

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

Although not strictly a conditional statement, error handling with


`Try...Catch...Finally` can be used to manage exceptions and execute code
conditionally based on whether an error occurred.
Syntax:
Try
' Code that might throw an exception
Catch ex As Exception
' Code to handle the exception
Finally
' Code that always executes, regardless of whether an exception was thrown
End Try
Example:
Dim result As Integer
Try
result = 10 / 0 ' This will throw a DivideByZeroException
Catch ex As DivideByZeroException
Console.WriteLine("Cannot divide by zero.")
Catch ex As Exception
Console.WriteLine("An unexpected error occurred.")
Finally
Console.WriteLine("This always runs.")
End Try
6. Switch Expressions (VB.NET 16.9 and later)
VB.NET supports switch expressions for more concise conditional logic.
Syntax:
Dim result = Select Case expression

Downloaded by vani K ([email protected])


lOMoARcPSD|57027414

Case value1
' Result if expression = value1
Case value2
' Result if expression = value2
Case Else
' Default result
End Select
Example:
Dim month As Integer = 4
Dim season As String = Select Case month
Case 12, 1, 2
"Winter"
Case 3 To 5
"Spring"
Case 6 To 8
"Summer"
Case 9 To 11
"Fall"
Case Else
"Unknown"
End Select
Console.WriteLine(season) ' Output: Spring

Downloaded by vani K ([email protected])

You might also like