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

Programs

This document contains 8 code examples demonstrating various VB.NET concepts: 1. Defining a class with properties and methods and creating an object of that class 2. Using a Select Case statement to execute different code blocks based on an integer value 3. Using a Do While loop that continues until a condition is met 4. Creating a dynamic array using a List 5. Defining and using a Point structure with properties and a method 6. Demonstrating optional arguments in a function 7. Using a constructor and destructor in a class 8. Validating a string using regular expressions with the RegEx class

Uploaded by

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

Programs

This document contains 8 code examples demonstrating various VB.NET concepts: 1. Defining a class with properties and methods and creating an object of that class 2. Using a Select Case statement to execute different code blocks based on an integer value 3. Using a Do While loop that continues until a condition is met 4. Creating a dynamic array using a List 5. Defining and using a Point structure with properties and a method 6. Demonstrating optional arguments in a function 7. Using a constructor and destructor in a class 8. Validating a string using regular expressions with the RegEx class

Uploaded by

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

1.

program to demonstrate use of class and object

This program will define a class named `Car` with some properties and methods, and
then create an object of this class to use its features.

Public Class Car


' Properties
Public Property Make As String
Public Property Model As String
Public Property Color As String

' Constructor
Public Sub New(make As String, model As String, color As String)
Me.Make = make
Me.Model = model
Me.Color = color
End Sub

' Method
Public Function GetCarDetails() As String
Return "Make: " & Make & ", Model: " & Model & ", Color: " & Color
End Function
End Class

Sub Main()
' Create an object of the Car class
Dim myCar As New Car("Toyota", "Corolla", "Red")

' Use the method of the Car class


Console.WriteLine(myCar.GetCarDetails())

Console.ReadLine() ' To keep the console window open


End Sub
```

In this program:
- A `Car` class is defined with properties like `Make`, `Model`, and `Color`.
- A constructor is used to initialize these properties.
- A method `GetCarDetails` is added to return the details of the car.
- In the `Main` method, an object `myCar` is created using the `Car` class, and its
method `GetCarDetails` is called to display the details of the car.

2. demonstrate use of switch function

This program will take an integer input and output a string based on the value of
the integer:
Module Module1
Sub Main()
' Prompt user for input
Console.WriteLine("Enter a number between 1 and 5:")
Dim number As Integer = Convert.ToInt32(Console.ReadLine())

' Select Case to handle different values


Select Case number
Case 1
Console.WriteLine("You entered One.")
Case 2
Console.WriteLine("You entered Two.")
Case 3
Console.WriteLine("You entered Three.")
Case 4
Console.WriteLine("You entered Four.")
Case 5
Console.WriteLine("You entered Five.")
Case Else
Console.WriteLine("Invalid number.")
End Select

Console.ReadLine() ' To keep the console window open


End Sub
End Module
```

In this program:
- The `Select Case` statement checks the value of `number`.
- Based on the value, it executes the code block in the corresponding `Case`
statement.
- If the number is not between 1 and 5, the `Case Else` block is executed.

3. program for do while

In this example, the program will prompt the user to enter numbers. The loop will
continue until the user enters a number greater than 10:

Module Module1
Sub Main()
Dim number As Integer

Do
Console.Write("Enter a number (Enter a number greater than 10 to stop):
")
number = Convert.ToInt32(Console.ReadLine())
Loop While number <= 10
Console.WriteLine("You entered a number greater than 10. Exiting loop.")

Console.ReadLine() ' To keep the console window open


End Sub
End Module
```

In this program:
- The `Do` loop starts.
- Inside the loop, the user is prompted to enter a number.
- The `Loop While` statement checks if the number is less than or equal to 10.
- If the user enters a number greater than 10, the loop terminates.
- A message is displayed after exiting the loop.

4. dynamic array in vb.net

Creating a dynamic array in VB.NET typically involves using a `List`, as it allows


for dynamic resizing and easy manipulation of elements. Here's a simple example
program that demonstrates how to use a `List(Of T)` to create a dynamic array. In
this example, the program will add numbers to the list and then display them:

Imports System.Collections.Generic

Module Module1
Sub Main()
' Create a dynamic array using List
Dim numbers As New List(Of Integer)()

' Adding elements to the list


numbers.Add(1)
numbers.Add(2)
numbers.Add(3)

' Displaying the elements in the list


Console.WriteLine("Numbers in the list:")
For Each number In numbers
Console.WriteLine(number)
Next

' Adding another element


numbers.Add(4)
Console.WriteLine("After adding another number:")
' Displaying the elements in the list again
For Each number In numbers
Console.WriteLine(number)
Next

Console.ReadLine() ' To keep the console window open


End Sub
End Module
```

In this program:
- A dynamic array `numbers` is created using `List(Of Integer)`.
- Elements are added to the list using the `Add` method.
- The `For Each` loop is used to iterate over the elements in the list and display
them.
- After adding another element, the contents of the list are displayed again to
show the dynamic nature of the `List`.

5. Structures in vb.net
create a `Point` structure that represents a point in a 2D space with `X` and `Y`
coordinates. The structure will include a method to calculate the distance from
another point:

Module Module1

' Define the Point structure


Structure Point
Public X As Double
Public Y As Double

' Constructor-like method to initialize the structure


Public Sub New(xValue As Double, yValue As Double)
X = xValue
Y = yValue
End Sub

' Method to calculate distance from another point


Public Function DistanceTo(otherPoint As Point) As Double
Return Math.Sqrt((X - otherPoint.X) ^ 2 + (Y - otherPoint.Y) ^ 2)
End Function
End Structure

Sub Main()
' Create two Point instances
Dim point1 As New Point(5, 5)
Dim point2 As New Point(10, 10)

' Calculate and display the distance


Console.WriteLine("Distance between point1 and point2: " &
point1.DistanceTo(point2))

Console.ReadLine() ' To keep the console window open


End Sub
End Module
```

In this program:
- A `Point` structure is defined with `X` and `Y` coordinates.
- A method `New` initializes the `X` and `Y` values of a point.
- The `DistanceTo` method calculates the Euclidean distance between the current
point and another point.
- Two instances of `Point` are created in the `Main` method, and the distance
between them is calculated and displayed.

6. demonstrate use of optional arguments

In VB.NET, you can define optional parameters in a function or subroutine by


specifying a default value. Here's an example of a function that greets a user. The
function will have an optional argument for the time of day, which, if not
provided, defaults to "Day":

Module Module1
Sub Main()
' Call the function with the optional argument
GreetUser("Alice", "Morning")

' Call the function without the optional argument


GreetUser("Bob")

Console.ReadLine() ' To keep the console window open


End Sub

' Function with an optional argument


Sub GreetUser(name As String, Optional timeOfDay As String = "Day")
Console.WriteLine("Good " & timeOfDay & ", " & name & "!")
End Sub
End Module
```

In this program:
- The `GreetUser` subroutine has two parameters: `name` and an optional
`timeOfDay`.
- If `timeOfDay` is not provided when the subroutine is called, it defaults to
"Day".
- The `Main` method demonstrates calling `GreetUser` both with and without the
optional argument.
7. constructor and destructor

we'll create a `Person` class. The constructor will set the person's name, and the
destructor will display a message when the object is being destroyed:

Public Class Person


Private Name As String

' Constructor
Public Sub New(name As String)
Me.Name = name
Console.WriteLine(Name & " has been created.")
End Sub

' Destructor
Protected Overrides Sub Finalize()
Console.WriteLine(Name & " is being destroyed.")
MyBase.Finalize()
End Sub
End Class

Module Module1
Sub Main()
' Create a new Person object
Dim person1 As New Person("John")

' Object is used here


' ...

' End of the Main method, person1 will be out of scope


Console.WriteLine("End of Main method.")
Console.ReadLine()
End Sub
End Module
```

In this program:
- The `Person` class has a constructor that takes a name as a parameter and prints
a creation message.
- It also has a destructor (finalizer) that prints a destruction message.
- In the `Main` method, when the `Person` object `person1` goes out of scope (i.e.,
when the program ends or `person1` is no longer needed), the destructor will be
called. Note that in .NET, the exact timing of destructor calls is determined by
the garbage collector, so it might not run immediately as the object goes out of
scope.
8.program for RegEx Class

In VB.NET, the `System.Text.RegularExpressions` namespace provides the RegEx class


for working with regular expressions. Here's a simple example where we use a
regular expression to validate an email address:

Imports System.Text.RegularExpressions

Module Module1
Sub Main()
' Email address to validate
Dim emailAddress As String = "[email protected]"

' Regular expression for email validation


Dim emailPattern As String = "^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\
w+)*$"
Dim emailRegex As New Regex(emailPattern)

' Validate the email


If emailRegex.IsMatch(emailAddress) Then
Console.WriteLine(emailAddress & " is a valid email address.")
Else
Console.WriteLine(emailAddress & " is not a valid email address.")
End If

Console.ReadLine() ' To keep the console window open


End Sub
End Module
```

In this program:
- We import `System.Text.RegularExpressions`.
- Define an email pattern using a regular expression.
- Create an instance of `Regex` with the email pattern.
- Use the `IsMatch` method of the `Regex` class to validate an email address.

9. multilevel inheritance
We'll create a basic hierarchy of classes: a base class `Animal`, a derived class
`Mammal` which inherits from `Animal`, and another derived class `Dog` which
inherits from `Mammal`.

Public Class Animal


Public Sub Eat()
Console.WriteLine("Animal is eating.")
End Sub
End Class

Public Class Mammal


Inherits Animal
Public Sub Breathe()
Console.WriteLine("Mammal is breathing.")
End Sub
End Class

Public Class Dog


Inherits Mammal
Public Sub Bark()
Console.WriteLine("Dog is barking.")
End Sub
End Class

Module Module1
Sub Main()
Dim myDog As New Dog()

' Dog class methods


myDog.Bark()

' Mammal class methods


myDog.Breathe()

' Animal class methods


myDog.Eat()

Console.ReadLine() ' To keep the console window open


End Sub
End Module
```

In this program:
- `Animal` is the base class with a method `Eat`.
- `Mammal` is derived from `Animal` and adds its own method `Breathe`.
- `Dog` is derived from `Mammal` and adds its own method `Bark`.
- In the `Main` method, an instance of `Dog` is created. This instance can use
methods from all classes in its inheritance hierarchy (`Dog`, `Mammal`, and
`Animal`).

10. overloading
Method overloading in VB.NET allows you to have multiple methods in the same scope,
with the same name but different parameters. Here's a simple example that
demonstrates method overloading. We'll create a class `Calculator` with multiple
overloaded methods named `Add`, which will differ in their parameters and behavior:
Public Class Calculator
' Method to add two integers
Public Function Add(a As Integer, b As Integer) As Integer
Return a + b
End Function

' Overloaded method to add three integers


Public Function Add(a As Integer, b As Integer, c As Integer) As Integer
Return a + b + c
End Function

' Overloaded method to add two doubles


Public Function Add(a As Double, b As Double) As Double
Return a + b
End Function
End Class

Module Module1
Sub Main()
Dim calc As New Calculator()

' Using the first Add method


Console.WriteLine("Addition of two integers: " & calc.Add(5, 10))

' Using the second Add method


Console.WriteLine("Addition of three integers: " & calc.Add(5, 10, 15))

' Using the third Add method


Console.WriteLine("Addition of two doubles: " & calc.Add(5.5, 10.5))

Console.ReadLine() ' To keep the console window open


End Sub
End Module
```

In this program:
- The `Calculator` class has three methods named `Add`.
- Each `Add` method has a different signature (i.e., different parameter list).
- In the `Main` method, each version of the `Add` method is called with different
types and numbers of arguments.

11. Overriding
Method overriding in VB.NET allows a derived class to provide a specific
implementation for a method that is already defined in its base class. This is
achieved using the `Overrides` keyword. Here's a simple example to demonstrate
method overriding. We'll create a base class `Shape` with a virtual method `Draw`,
and a derived class `Circle` that overrides this method:

Public Class Shape


' Virtual method in the base class
Public Overridable Sub Draw()
Console.WriteLine("Drawing a shape.")
End Sub
End Class

Public Class Circle


Inherits Shape
' Overriding the Draw method in the derived class
Public Overrides Sub Draw()
Console.WriteLine("Drawing a circle.")
End Sub
End Class

Module Module1
Sub Main()
Dim myShape As Shape = New Shape()
Dim myCircle As Circle = New Circle()

' Call Draw method on Shape instance


myShape.Draw()

' Call Draw method on Circle instance


myCircle.Draw()

Console.ReadLine() ' To keep the console window open


End Sub
End Module
```

In this program:
- The `Shape` class has a virtual method `Draw`.
- The `Circle` class, which inherits from `Shape`, overrides the `Draw` method to
provide a specific implementation for circles.
- In the `Main` method, we create instances of both `Shape` and `Circle` and call
their `Draw` methods to see the difference in behavior.

12. intertace
an interface defines a contract that can be implemented by classes or structures.
Interfaces can contain definitions for methods, properties, and events. Here's a
simple example demonstrating how to define and implement an interface. We'll create
an interface `IVehicle` with a method `Drive` and then create a `Car` class that
implements this interface:
' Define the interface
Public Interface IVehicle
Sub Drive()
End Interface

' Implement the interface in a class


Public Class Car
Implements IVehicle

Public Sub Drive() Implements IVehicle.Drive


Console.WriteLine("Car is driving.")
End Sub
End Class

Module Module1
Sub Main()
Dim myCar As IVehicle = New Car()

' Call the Drive method


myCar.Drive()

Console.ReadLine() ' To keep the console window open


End Sub
End Module
```

In this program:
- `IVehicle` is an interface with a `Drive` method.
- `Car` is a class that implements the `IVehicle` interface. The `Drive` method of
`IVehicle` is implemented in `Car`.
- In the `Main` method, an instance of `Car` is created as an `IVehicle` type and
the `Drive` method is called.

13. Exception handling


Exception handling in VB.NET is done using `Try`, `Catch`, `Finally`, and `End Try`
blocks. Here's a simple example that demonstrates how to handle exceptions. The
program will attempt to divide two numbers and catch any division-by-zero errors:

Module Module1
Sub Main()
Try
' Prompt for and read input values
Console.Write("Enter the numerator: ")
Dim numerator As Integer = Convert.ToInt32(Console.ReadLine())
Console.Write("Enter the denominator: ")
Dim denominator As Integer = Convert.ToInt32(Console.ReadLine())
' Perform division
Dim result As Integer = numerator / denominator
Console.WriteLine("Result: " & result)

Catch ex As DivideByZeroException
' Handle division by zero exception
Console.WriteLine("Error: Cannot divide by zero.")

Catch ex As FormatException
' Handle format exception if input is not an integer
Console.WriteLine("Error: Please enter a valid integer.")

Finally
' This block runs regardless of whether an exception was thrown
Console.WriteLine("Operation completed.")
End Try

Console.ReadLine() ' To keep the console window open


End Sub
End Module
```

In this program:
- The code in the `Try` block is where the exception might occur.
- The `Catch` blocks handle specific types of exceptions (`DivideByZeroException`
and `FormatException`).
- The `Finally` block runs regardless of whether an exception occurred, and is
often used for clean-up code. In this example, it simply notifies that the
operation is completed.

14. Multithreading
Creating a simple VB.NET program with multithreading involves using the
`System.Threading` namespace. This allows you to create and manage threads,
enabling concurrent execution paths within your application. Here's an example that
demonstrates basic multithreading:

Imports System.Threading

Module Module1

Sub Main()
' Create a new thread and assign a method to be executed by the thread
Dim thread1 As New Thread(AddressOf PrintNumbers)
thread1.Name = "Thread1"

' Start the thread


thread1.Start()
' Main thread continues to execute concurrently
For i As Integer = 1 To 5
Console.WriteLine("Main Thread: " & i)
Thread.Sleep(500) ' Pause for 500 milliseconds
Next

Console.ReadLine() ' To keep the console window open


End Sub

' Method to be executed by the thread


Sub PrintNumbers()
For i As Integer = 1 To 5
Console.WriteLine(thread1.Name & ": " & i)
Thread.Sleep(1000) ' Pause for 1000 milliseconds
Next
End Sub
End Module
```

In this program:
- We import `System.Threading`.
- In the `Main` method, we create a new thread (`thread1`) that will execute the
`PrintNumbers` method.
- We start `thread1`, and then the main thread executes its own loop.
- Both the main thread and `thread1` execute concurrently, each printing numbers to
the console.
- `Thread.Sleep` is used to pause execution for a specified time, simulating work
being done.

15. write a file in file handling

In VB.NET, you can use the `System.IO` namespace to handle files. To write to a
file, you can use the `StreamWriter` class. Here's a simple example that
demonstrates how to write text to a file:

Imports System.IO

Module Module1
Sub Main()
Dim filePath As String = "C:\example\testfile.txt"

' Ensure the directory exists


Dim directoryPath As String = Path.GetDirectoryName(filePath)
If Not Directory.Exists(directoryPath) Then
Directory.CreateDirectory(directoryPath)
End If
' Create a StreamWriter instance to write to the file
Using writer As StreamWriter = New StreamWriter(filePath)
writer.WriteLine("Hello, world!")
writer.WriteLine("This is a test file.")
' Data is automatically flushed and file closed at the end of Using
block
End Using

Console.WriteLine("File written successfully to " & filePath)


Console.ReadLine() ' To keep the console window open
End Sub
End Module
```

In this program:
- The `Imports System.IO` statement is used to include the `System.IO` namespace.
- The `filePath` variable specifies the path to the file you want to write to.
- The `Directory.CreateDirectory` method ensures the directory exists before
writing the file.
- A `StreamWriter` instance is created and used within a `Using` block, which
ensures the file is properly closed and resources are freed after writing.
- `writer.WriteLine` methods are used to write lines of text to the file.
- After the `Using` block, the file is automatically closed and flushed.

16. read file


Reading a file in VB.NET can be efficiently done using the `StreamReader` class,
which is part of the `System.IO` namespace. Here's a simple example that
demonstrates how to read text from a file:

Imports System.IO

Module Module1
Sub Main()
Dim filePath As String = "C:\example\testfile.txt"

' Check if the file exists


If File.Exists(filePath) Then
' Create a StreamReader instance to read from the file
Using reader As StreamReader = New StreamReader(filePath)
Dim line As String

' Read and display lines from the file until the end of the file is
reached
While Not reader.EndOfStream
line = reader.ReadLine()
Console.WriteLine(line)
End While
End Using
Else
Console.WriteLine("File not found: " & filePath)
End If

Console.ReadLine() ' To keep the console window open


End Sub
End Module
```

In this program:
- The `Imports System.IO` statement includes the `System.IO` namespace.
- The `filePath` variable specifies the path to the file you want to read.
- The `File.Exists` method checks if the file exists at the given path.
- A `StreamReader` instance is created within a `Using` block, ensuring proper
disposal of resources after reading the file.
- The `ReadLine` method reads each line of the file until the end of the file is
reached, and each line is printed to the console.

You might also like