Dotnet Set 1
Dotnet Set 1
[2 MARKS]
1. What is C#?
2. Define Constructor.
● Arrays: Fixed-size data structures that store elements of the same type.
● Collections: Dynamic data structures (like List, Dictionary, etc.) that can grow or
shrink in size and store objects of different types.
● Debugging is the process of identifying, analyzing, and fixing errors or bugs in the
code.
● It helps ensure the program behaves as expected by allowing developers to inspect
variables, control program flow, and resolve issues.
[5 MARKS]
1.Method Overloading in C#
Definition:
Method overloading in C# is a feature that allows multiple methods in the same
class to have the same name but differ in the type, number, or order of their
parameters. This is a compile-time polymorphism concept.
Key Points:
1. Overloaded methods must have the same name but different parameter
lists.
2. It is achieved by:
○ Changing the number of parameters.
○ Changing the data type of parameters.
○ Changing the order of parameters.
Example Code:
using System;
class Calculator
{
// Method to add two integers
public int Add(int a, int b)
{
return a + b;
}
// Overloaded method to add three integers
public int Add(int a, int b, int c)
{
return a + b + c;
}
// Overloaded method to add two double numbers
public double Add(double a, double b)
{
return a + b;
}
}
class Program
{
static void Main()
{
Calculator calc = new Calculator();
Console.WriteLine("Addition of two integers: " + calc.Add(5, 10)); // Calls
Add(int, int)
Console.WriteLine("Addition of three integers: " + calc.Add(5, 10, 15)); // Calls
Add(int, int, int)
Console.WriteLine("Addition of two doubles: " + calc.Add(5.5, 10.5)); // Calls
Add(double, double)
}
}
Output:
Addition of two integers: 15
Addition of three integers: 30
Addition of two doubles: 16
Explanation:
1. The Add method is overloaded with three variations:
○ Two integers (Add(int, int)).
○ Three integers (Add(int, int, int)).
○ Two double values (Add(double, double)).
2. At compile time, the compiler determines which method to call based on the
arguments passed.
C# provides several classes in the System.IO namespace for file handling. The following
are commonly used functions for reading, writing, and manipulating files.
Console.WriteLine("File exists!");
}
// Delete the file
File.Delete(filePath);
Console.WriteLine("File deleted successfully.");
}
}
Output:
File Content: Hello, this is a file handling example in C#.
File exists!
Output Example:
If valid input (e.g., 5):
Enter a number:
5
You entered: 5
End of error handling example.
If invalid input (e.g., abc):
Enter a number:
abc
Error: Please enter a valid number. Input string was not in
the correct format.
End of error handling example.
4. Find Leap Year and Next Leap Year
Definition:
A leap year is divisible by 4 but not divisible by 100 unless it is divisible by 400. For
example, 2000 and 2024 are leap years.
Example Code: Check Leap Year and Find Next Leap Year
using System;
class Program
{
static void Main()
{
Console.Write("Enter a year: ");
int year = int.Parse(Console.ReadLine());
Example Output:
Input: 2023
Enter a year: 2023
2023 is not a leap year.
Next leap year: 2024
Input: 2024
Enter a year: 2024
2024 is a leap year.
Next leap year: 2028
[12 MARKS]
1. Basic Steps Involved in Creating a Simple .NET Project
● Download and install the .NET Software Development Kit (SDK) from the
official Microsoft .NET website.
● The SDK includes tools for building, running, and debugging .NET
applications.
Using Command Line: Run the following command to create a new console
application:
● This will create a new folder named MyProject with the necessary files.
4. Write Code
● Navigate to the project folder (MyProject) and open the Program.cs file.
Using Command Line: Run the following command to compile the project:
dotnet build
● Using Visual Studio: Click Build -> Build Solution from the menu.
Using Command Line: Run the following command to execute the application:
dotnet run
7. Debugging
● Add breakpoints in the code to analyze the program flow and check for errors.
● Use debugging tools in Visual Studio or dotnet CLI for troubleshooting.
● The output will be in the publish folder, which can be shared or deployed.
By following these steps, you can successfully create, build, and run a .NET project.
2. Operator Overloading in C#
Operator overloading in C# allows you to define or redefine the behavior of operators
(like +, -, *, etc.) for user-defined data types (such as classes or structs). It is used to
make the code more intuitive and easier to understand by allowing you to perform
operations on objects in a way similar to primitive data types.
Console.WriteLine(str.Length); // 19
Console.WriteLine(str.Substring(7, 5)); // World
Console.WriteLine(str.Replace("World", "Universe")); // Hello, Universe!
Console.WriteLine(string.Concat(str, " Let's learn!")); // Hello, World! Let's learn!
Console.WriteLine(str.ToUpper()); // HELLO, WORLD!
Console.WriteLine(str.ToLower()); // hello, world!
Console.WriteLine(str.Trim()); // Hello, World!
Console.WriteLine(str.IndexOf("World")); // 7
string[] fruits = "apple,banana,orange".Split(',');
Console.WriteLine(fruits[1]); // banana
Console.WriteLine(str.Contains("World")); // True
}
}
OUTPUT:
19
World
Hello, Universe!
Hello, World! Let's learn!
HELLO, WORLD!
hello, world!
Hello, World!
7
banana
True
4.I/O Collections in C#
I/O Collections in C# are part of the System.IO namespace and deal with input and output
operations, such as reading and writing to files, handling streams of data, and working with
directories. They provide a set of classes and methods that allow efficient handling of file
and data stream operations.
File and FileInfo are the main classes for file-related operations. File provides static
methods, while FileInfo offers instance methods that provide more detailed information
about files.
● File:
○ Provides methods like File.ReadAllText(), File.WriteAllText(),
File.Create(), File.Delete(), and more.
○ Allows reading from and writing to text files directly.
● FileInfo:
○ Provides properties like Exists, Length, Name, and methods like
CopyTo(), MoveTo(), Delete(), etc.
○ Used for more granular control over files.
● Directory:
○ Provides static methods for creating, deleting, and moving directories.
○ Methods like Directory.CreateDirectory(),
Directory.GetFiles(), and Directory.GetDirectories() help list
and manage directory contents.
● DirectoryInfo:
○ Provides instance methods to manipulate directories, such as GetFiles(),
GetDirectories(), CreateSubdirectory(), and more.
○ Allows access to directory properties like Name, FullName, and Parent.
Streams represent a sequence of bytes and can be used for input or output operations.
There are several important stream handling classes:
● FileStream:
○ Used for reading and writing raw bytes to and from files.
○ Ideal for binary data.
● StreamReader and StreamWriter:
○ Used for reading from and writing to files in a text format, with automatic
encoding handling.
○ StreamReader.ReadLine() reads a line of text, while
StreamWriter.WriteLine() writes a line of text.
● MemoryStream:
○ Works with data stored in memory (not in files).
○ Ideal for situations where you want to work with byte arrays in memory rather
than actual files.
● BufferedStream:
○ Wraps another stream and adds a buffer to improve I/O performance.
The Path class provides static methods for manipulating file and directory paths, such as:
Example:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = "example.txt";
File.WriteAllText(filePath, "Hello, File Handling!");
Console.WriteLine(File.ReadAllText(filePath));
Output:
Hello, File Handling!
Directory created: True
File name: example.txt
Explanation:
● File.WriteAllText() writes text to a file.
● File.ReadAllText() reads and displays the text from the file.
● Directory.CreateDirectory() creates a new directory.
In Windows Forms (WinForms), controls are visual elements like buttons, textboxes, labels,
etc. that you can place on a form. Controls have properties that define their appearance
and behavior, and they can trigger events based on user interaction.
Properties are attributes or characteristics of controls that you can set or retrieve at runtime.
They affect the control's behavior, appearance, and functionality.
1. Text:
○ Sets or gets the text displayed by a control (e.g., Label, Button).
Example:
button1.Text = "Click Me";
2. BackColor:
○ Sets or gets the background color of a control.
Example:
button1.BackColor = Color.Green;
3. ForeColor:
○ Sets or gets the text color of a control.
Example:
label1.ForeColor = Color.Blue;
4. Enabled:
○ Gets or sets a value indicating whether the control can respond to user
interactions.
Example:
button1.Enabled = false; // Disables the button
5. Visible:
○ Determines whether the control is visible.
Example:
textBox1.Visible = true;
6. Size:
○ Gets or sets the size of the control.
Example:
textBox1.Size = new Size(200, 30);
7. Location:
○ Gets or sets the position of the control on the form.
Example:
button1.Location = new Point(50, 100);
Events are actions or occurrences that the control can respond to, such as clicking a button,
changing text in a textbox, or moving the mouse over a control. You can subscribe to these
events to define specific behavior when they occur.
1. Click:
○ Occurs when a control is clicked by the user (e.g., Button, PictureBox).
Example:
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Button clicked!");
}
2. TextChanged:
○ Occurs when the text in a TextBox or RichTextBox changes.
Example:
private void textBox1_TextChanged(object sender, EventArgs e)
{
label1.Text = "Text changed!";
}
3. MouseEnter:
○ Occurs when the mouse pointer enters a control's client area.
private void button1_MouseEnter(object sender, EventArgs
e)
{
button1.BackColor = Color.Cyan;
}
4. MouseLeave:
○ Occurs when the mouse pointer leaves a control's client area.
Example:
private void button1_MouseLeave(object sender, EventArgs e)
{
button1.BackColor = Color.Green;
}
5. KeyDown:
○ Occurs when a key is pressed while the control has focus (e.g., TextBox).
Example:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
MessageBox.Show("Enter key pressed");
}
6. Load:
○ Occurs when the form is loaded into memory.
Example:
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = "Form Loaded!";
}
7. CheckedChanged:
○ Occurs when the state of a CheckBox or RadioButton changes.
Example:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
MessageBox.Show("Checked!");
else
MessageBox.Show("Unchecked!");
}
Example Program:
using System;
using System.Windows.Forms;
public class ExampleForm : Form
{
private Button button1 = new Button() { Text = "Click Me", Location = new
System.Drawing.Point(50, 50) };
private TextBox textBox1 = new TextBox() { Location = new System.Drawing.Point(50,
100) };
private Label label1 = new Label() { Location = new System.Drawing.Point(50, 150) };
public ExampleForm()
{
button1.Click += (s, e) => label1.Text = "Button clicked!";
textBox1.TextChanged += (s, e) => label1.Text = "Text changed!";
Controls.Add(button1);
Controls.Add(textBox1);
Controls.Add(label1);
}
[STAThread]
static void Main() => Application.Run(new ExampleForm());
}
Output:
● When the Button is clicked, the label shows: "Button clicked!".
● When the TextBox text changes, the label shows: "Text changed!"