Programs
Programs
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.
' 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")
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.
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())
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.
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.")
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.
Imports System.Collections.Generic
Module Module1
Sub Main()
' Create a dynamic array using List
Dim numbers As New List(Of Integer)()
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
Sub Main()
' Create two Point instances
Dim point1 As New Point(5, 5)
Dim point2 As New Point(10, 10)
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.
Module Module1
Sub Main()
' Call the function with the optional argument
GreetUser("Alice", "Morning")
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:
' 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")
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
Imports System.Text.RegularExpressions
Module Module1
Sub Main()
' Email address to validate
Dim emailAddress As String = "[email protected]"
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`.
Module Module1
Sub Main()
Dim myDog As New Dog()
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
Module Module1
Sub Main()
Dim calc As New Calculator()
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:
Module Module1
Sub Main()
Dim myShape As Shape = New Shape()
Dim myCircle As Circle = New Circle()
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
Module Module1
Sub Main()
Dim myCar As IVehicle = New Car()
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.
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
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"
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.
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"
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.
Imports System.IO
Module Module1
Sub Main()
Dim filePath As String = "C:\example\testfile.txt"
' 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
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.