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

Visual Baba

The document explains key concepts in Visual Basic (VB) and C#, including polymorphism, inheritance, variable declaration errors, and user-defined data types. It provides code examples for each concept, illustrating how to implement them in programming. Additionally, it covers error types, loop statements, file handling, and array manipulation in C#.

Uploaded by

h240253t
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)
3 views

Visual Baba

The document explains key concepts in Visual Basic (VB) and C#, including polymorphism, inheritance, variable declaration errors, and user-defined data types. It provides code examples for each concept, illustrating how to implement them in programming. Additionally, it covers error types, loop statements, file handling, and array manipulation in C#.

Uploaded by

h240253t
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/ 17

a) Explanation of Concepts in VB with Code Examples

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).

Example (Method Overriding):

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

Here, Car inherits the StartEngine method from Vehicle.

(b) Why the Variable Declaration is Wrong


The given declaration has two errors:

1. Name&surname is invalid: Variable names cannot contain & (special character).


Use Name_surname or NameAndSurname instead.
2. Dim misuse: While the syntax is correct for declaring multiple variables, the names must follow
VB rules (no special characters except underscores).

Corrected Version:

vb
Copy
Download
Dim password As String, Name_surname As String, first_num As Integer

 Avoid symbols like & in variable names.


 Use underscores or camelCase (e.g., nameSurname) for readability.

// Assume this code runs when a button (e.g., btnCalculate) is clicked


private void btnCalculate_Click(object sender, EventArgs e)
{
// Get the mark from a textbox (e.g., txtMark)
int mark;
if (int.TryParse(txtMark.Text, out mark))
{
string grade;

// 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")
}

// Display the grade (e.g., in a label named lblGrade)


lblGrade.Text = $"Grade: {grade}";
}
else
{
MessageBox.Show("Please enter a valid number!");
}
}
(a) Difference Between Instance of a Class and Static Class

Instance Class Static Class

You must create an object (new No object needed—accessed directly


MyClass()) to use it. (MyStaticClass.Method()).

Can have instance fields (unique per


Only static fields (shared across the app).
object).

Supports inheritance and interfaces. Cannot be inherited or implement interfaces.

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).

(b) Interpretation of the VB Snippet (Converted to C#)

The original VB loop:

vb
Copy
Download
Do While counter <= 1000
num.Text = counter
counter = counter + 1
Loop

C# Equivalent and Explanation:

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:

1. Loop Condition: Keep running while counter is ≤ 1000.


2. UI Update: Set num.Text (e.g., a label) to the current counter value.
3. Increment: Increase counter by 1 each iteration.
4. Repeat: Goes back to check the condition until counter hits 1001.

Purpose: Counts from counter’s initial value to 1000, updating a UI element in real-time (e.g.,
for a progress display).

(c) C# Code to Connect to Microsoft Access Database

csharp
Copy
Download
using System.Data.OleDb;

string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\


YourDatabase.accdb;";
OleDbConnection connection = new OleDbConnection(connectionString);

try
{
connection.Open();
MessageBox.Show("Connected to Access DB!"); // Success message

// Example: Execute a query


string query = "SELECT * FROM Students";
OleDbCommand command = new OleDbCommand(query, connection);
OleDbDataReader reader = command.ExecuteReader();

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 in C# (With Examples)

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

1. Class (Reference Type)

A class bundles data (fields/properties) and methods into a reusable template.


Example:

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!"

2. Struct (Value Type)

A lightweight alternative to classes for small data structures.

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)"

3. Enum (Named Constants)

An enum defines a set of named integer constants.

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

 Classes are used for complex logic and inheritance.


 Structs are for small, immutable data (e.g., coordinates).
 Enums improve code readability by replacing "magic numbers."

Why Use Them?

 Organize data logically (e.g., Person instead of loose variables like name, age).
 Reuse code efficiently.
 Make programs easier to maintain.

Let me know if you'd like a deeper dive into any of these!

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();
}

private void NumberButton_Click(object sender, EventArgs e)


{
Button button = (Button)sender;

if (isNewNumber || txtDisplay.Text == "0")


{
txtDisplay.Text = button.Text;
isNewNumber = false;
}
else
{
txtDisplay.Text += button.Text;
}
}

private void OperatorButton_Click(object sender, EventArgs e)


{
Button button = (Button)sender;
firstNumber = double.Parse(txtDisplay.Text);
operation = button.Text;
isNewNumber = true;
lblHistory.Text = $"{firstNumber} {operation}";
}

private void btnEquals_Click(object sender, EventArgs e)


{
if (!isNewNumber)
{
double secondNumber = double.Parse(txtDisplay.Text);
double result = 0;

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;
}
}

private void btnClear_Click(object sender, EventArgs e)


{
txtDisplay.Text = "0";
lblHistory.Text = "";
firstNumber = 0;
operation = "";
isNewNumber = true;
}

private void btnDecimal_Click(object sender, EventArgs e)


{
if (!txtDisplay.Text.Contains("."))
{
txtDisplay.Text += ".";
}
}
}
}

Here are the three main types of errors you'll encounter:

1. Syntax Errors (Compile-time errors)

csharp

Copy
Download
// Missing semicolon
int x = 5 // Error
Console.WriteLine(x)

// Incorrect:
if (x == 5 // Missing closing parenthesis
{
// code
}

2. Runtime Errors (Exceptions)

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

3. Logical Errors (Code works but gives wrong results)

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(b) Loop Statements in C#

1. For Loop

csharp

Copy
Download
// Count from 1 to 10
for (int i = 1; i <= 10; i++)
{
Console.WriteLine(i);
}

// Iterate through array


string[] colors = { "Red", "Green", "Blue" };
for (int i = 0; i < colors.Length; i++)
{
Console.WriteLine(colors[i]);
}
2. While Loop

csharp

Copy
Download
// Countdown from 5
int count = 5;
while (count > 0)
{
Console.WriteLine(count);
count--;
}

// User input validation


string input;
while (true)
{
Console.Write("Enter 'yes' to continue: ");
input = Console.ReadLine();
if (input == "yes") break;
}

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');

1(c) File and Array in C#

(i) File Class

csharp

Copy
Download
using System.IO;

// Write to file
File.WriteAllText("test.txt", "Hello World!");

// Read from file


string content = File.ReadAllText("test.txt");

// Check if file exists


if (File.Exists("test.txt"))
{
Console.WriteLine("File exists!");
}

(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]);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy