Visual Baba
Visual Baba
i. Polymorphism
Polymorphism means "many forms." It allows objects of different classes to be treated as objects
of a common superclass. In VB, this is often done using method overriding (with Overrides) or
method overloading (multiple methods with the same name but different parameters).
vb
Copy
Download
Class Animal
Public Overridable Sub MakeSound()
Console.WriteLine("Some animal sound")
End Sub
End Class
Class Dog
Inherits Animal
Public Overrides Sub MakeSound()
Console.WriteLine("Bark!")
End Sub
End Class
' Usage:
Dim myAnimal As Animal = New Dog()
myAnimal.MakeSound() ' Output: "Bark!"
Here, Dog overrides the MakeSound method of Animal, showing polymorphism.
ii. Inheritance
Inheritance allows a class (child) to inherit properties and methods from another class (parent).
This promotes code reuse.
Example:
vb
Copy
Download
Class Vehicle
Public Sub StartEngine()
Console.WriteLine("Engine started.")
End Sub
End Class
Class Car
Inherits Vehicle
Public Sub Drive()
Console.WriteLine("Car is driving.")
End Sub
End Class
' Usage:
Dim myCar As New Car()
myCar.StartEngine() ' Inherited from Vehicle
myCar.Drive() ' Defined in Car
Corrected Version:
vb
Copy
Download
Dim password As String, Name_surname As String, first_num As Integer
// Decision-making logic
if (mark >= 80)
{
grade = "D";
}
else if (mark >= 70)
{
grade = "2:1";
}
else if (mark >= 60)
{
grade = "2:2";
}
else if (mark >= 40)
{
grade = "P";
}
else
{
grade = "F"; // Assuming "F" for "Fail" (since the description says "less than 40")
}
Example: Car myCar = new Car(); Example: Math.Max(3, 5); (no new Math() needed).
Key Point: Use instance classes for objects with state (e.g., Person, Car), and static classes for
utilities (e.g., Math, Logger).
vb
Copy
Download
Do While counter <= 1000
num.Text = counter
counter = counter + 1
Loop
csharp
Copy
Download
while (counter <= 1000)
{
num.Text = counter.ToString(); // Update UI with current counter value
counter++; // Increment counter by 1
}
Line-by-Line Meaning:
Purpose: Counts from counter’s initial value to 1000, updating a UI element in real-time (e.g.,
for a progress display).
csharp
Copy
Download
using System.Data.OleDb;
try
{
connection.Open();
MessageBox.Show("Connected to Access DB!"); // Success message
while (reader.Read())
{
Console.WriteLine(reader["Name"].ToString()); // Print each student's name
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message); // Show errors
}
finally
{
connection.Close(); // Always close the connection
}
User-defined data types are custom types created by the programmer to group related data or
behaviors. They include:
1. Classes
2. Structs
3. Enums
csharp
Copy
Download
// Define a class
public class Person
{
// Fields (data)
public string Name;
public int Age;
// Method (behavior)
public void Greet()
{
Console.WriteLine($"Hello, I'm {Name}!");
}
}
// Usage
Person person1 = new Person();
person1.Name = "Alice";
person1.Age = 25;
person1.Greet(); // Output: "Hello, I'm Alice!"
Example:
csharp
Copy
Download
// Define a struct
public struct Point
{
public int X;
public int Y;
}
// Usage
Point p1 = new Point();
p1.X = 10;
p1.Y = 20;
Console.WriteLine($"Point: ({p1.X}, {p1.Y})"); // Output: "Point: (10, 20)"
Example:
csharp
Copy
Download
// Define an enum
public enum DayOfWeek
{
Monday, // 0
Tuesday, // 1
Wednesday, // 2
// ...
}
// Usage
DayOfWeek today = DayOfWeek.Wednesday;
Console.WriteLine(today); // Output: "Wednesday"
Key Points
Organize data logically (e.g., Person instead of loose variables like name, age).
Reuse code efficiently.
Make programs easier to maintain.
using System;
using System.Windows.Forms;
namespace SimpleCalculator
{
public partial class CalculatorForm : Form
{
private double firstNumber = 0;
private string operation = "";
private bool isNewNumber = true;
public CalculatorForm()
{
InitializeComponent();
}
switch (operation)
{
case "+":
result = firstNumber + secondNumber;
break;
case "-":
result = firstNumber - secondNumber;
break;
case "*":
result = firstNumber * secondNumber;
break;
case "/":
if (secondNumber != 0)
{
result = firstNumber / secondNumber;
}
else
{
MessageBox.Show("Cannot divide by zero!");
return;
}
break;
}
txtDisplay.Text = result.ToString();
lblHistory.Text = $"{firstNumber} {operation} {secondNumber} =";
isNewNumber = true;
}
}
csharp
Copy
Download
// Missing semicolon
int x = 5 // Error
Console.WriteLine(x)
// Incorrect:
if (x == 5 // Missing closing parenthesis
{
// code
}
csharp
Copy
Download
// Division by zero
int a = 10, b = 0;
int result = a / b; // Throws DivideByZeroException
// Null reference
string text = null;
int length = text.Length; // Throws NullReferenceException
csharp
Copy
Download
// Calculating average incorrectly
int[] numbers = { 10, 20, 30 };
int average = numbers[0] + numbers[1] + numbers[2]; // Forgot to divide by 3
// Incorrect condition
if (age > 18 && age < 16) // Impossible condition
{
// code
}
1. For Loop
csharp
Copy
Download
// Count from 1 to 10
for (int i = 1; i <= 10; i++)
{
Console.WriteLine(i);
}
csharp
Copy
Download
// Countdown from 5
int count = 5;
while (count > 0)
{
Console.WriteLine(count);
count--;
}
3. Do-While Loop
csharp
Copy
Download
// Runs at least once
int number;
do
{
Console.Write("Enter a positive number: ");
number = int.Parse(Console.ReadLine());
} while (number <= 0);
// Menu system
char choice;
do
{
Console.WriteLine("1. Option 1");
Console.WriteLine("2. Option 2");
Console.WriteLine("Q. Quit");
choice = Console.ReadKey().KeyChar;
} while (choice != 'Q');
csharp
Copy
Download
using System.IO;
// Write to file
File.WriteAllText("test.txt", "Hello World!");
(ii) Array
csharp
Copy
Download
// Create and initialize array
int[] numbers = { 1, 2, 3, 4, 5 };
// Access elements
Console.WriteLine(numbers[0]); // First element (1)
// Modify element
numbers[1] = 10;
// Loop through array
foreach (int num in numbers)
{
Console.WriteLine(num);
}
// Multi-dimensional array
int[,] matrix = new int[2, 3] { { 1, 2, 3 }, { 4, 5, 6 } };
Console.WriteLine(matrix[0, 1]);