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

Dotnet Set 1

The document provides an overview of C#, including its definition, constructors, code compilation, and the role of CLI in .NET. It explains various programming concepts such as method overloading, file handling, error handling, and operator overloading, along with example codes. Additionally, it outlines the basic steps to create a simple .NET project and discusses debugging and data binding.

Uploaded by

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

Dotnet Set 1

The document provides an overview of C#, including its definition, constructors, code compilation, and the role of CLI in .NET. It explains various programming concepts such as method overloading, file handling, error handling, and operator overloading, along with example codes. Additionally, it outlines the basic steps to create a simple .NET project and discusses debugging and data binding.

Uploaded by

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

SET-1

[2 MARKS]
1. What is C#?

● C# is an object-oriented programming language developed by Microsoft as part of


the .NET framework.
● It is used to build various types of applications, such as web, desktop, and mobile
apps, and it provides features like type safety, garbage collection, and support for
modern programming paradigms.

2. Define Constructor.

● A constructor is a special method in a class that is automatically called when an


object of the class is created.
● It is used to initialize the object’s properties. In C#, a constructor has the same name
as the class and does not have a return type.

3. Explain the Four Steps Involved in C# Code Compilation.

1. Source Code Compilation: The C# code is compiled into Intermediate Language


(IL) by the C# compiler (csc.exe).
2. Assembly Creation: The IL code, along with metadata, is stored in an assembly
(DLL or EXE).
3. JIT Compilation: During execution, the Common Language Runtime (CLR)
compiles the IL code into native machine code using Just-In-Time (JIT) compilation.
4. Execution: The native code is executed by the CPU.

4. What is the Purpose of CLI in .NET?

● The Common Language Infrastructure (CLI) is a standardized environment in .NET


that allows multiple programming languages to work together.
● It provides a runtime environment, metadata, and a virtual execution system for code
execution across different platforms.

5. How are Console Applications Executed in C#?

● Console applications in C# are executed by running the compiled executable file


(EXE) generated by the compiler.
● The execution happens in a command-line environment, where input and output are
handled through the console window.

6. What is the Difference Between Compile-Time and Run-Time Behavior


in .NET?
● Compile-Time Behavior: Refers to the phase where the source code is checked for
syntax errors and converted into IL code by the compiler.
● Run-Time Behavior: Refers to the execution phase, where the IL code is converted
into native code and executed, handling dynamic behavior like method calls, memory
allocation, and exception handling.

7. What is the Role of Garbage Collection in .NET?

● Garbage collection (GC) in .NET is an automatic memory management process that


reclaims unused memory by identifying and removing objects that are no longer
referenced.
● This helps prevent memory leaks and optimizes the application’s performance.

8. What is the Difference Between Collections and Arrays in C#?

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

9. What is the Purpose of Debugging in a C# Project?

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

10. What is Data Binding?

● Data binding in C# is the process of linking a UI element (like a textbox) to a data


source (like a variable or database).
● It ensures that changes in the data source automatically update the UI and vice
versa.

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

This demonstrates the concept of method overloading.

2.File Handling Functions in C#

C# provides several classes in the System.IO namespace for file handling. The following
are commonly used functions for reading, writing, and manipulating files.

Function Description Example

File.Create() Creates a new file. File.Create("example.txt");

File.WriteAllText( Writes text to a file, overwriting File.WriteAllText("example.txt"


) existing content. , "Hello, World!");

File.AppendAllText Appends text to an existing File.AppendAllText("example.txt


() file. ", "Additional text.");

File.ReadAllText() Reads all text from a file. string content =


File.ReadAllText("example.txt")
;

File.Exists() Checks if a file exists. bool exists =


File.Exists("example.txt");

File.Delete() Deletes a file. File.Delete("example.txt");

File.Copy() Copies a file to a new location. File.Copy("source.txt",


"destination.txt");

File.Move() Moves or renames a file. File.Move("oldname.txt",


"newname.txt");
Example Code: File Handling in C#
using System;
using System.IO;
class FileHandling
{
static void Main()
{
string filePath = "example.txt";
// Create and write to the file
File.WriteAllText(filePath, "Hello, this is a file handling example in C#.");
// Read and display the content of the file
string content = File.ReadAllText(filePath);
Console.WriteLine("File Content: " + content);
// Check if the file exists
if (File.Exists(filePath))

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!

File deleted successfully.

3. Error Handling Functions in C#


Definition:
Error handling in C# is achieved using try, catch, finally, and throw blocks.
These constructs allow developers to handle runtime errors (exceptions) gracefully
without crashing the program.

Key Functions and Usage:


Function/Keywo Description Example
rd

try Defines a block of code to try { /* Code */ }


monitor for exceptions.

catch Defines a block of code to catch (Exception ex) {


handle the exception. /* Handle exception */ }

finally Defines a block of code that finally { /* Cleanup


will execute regardless of code */ }
whether an exception
occurred or not.

throw Used to explicitly throw an throw new


exception. Exception("Custom error
message");

Exception.Mes Retrieves the error Console.WriteLine(ex.Mes


sage message associated with sage);
the exception.

Example Code: Error Handling in C#


using System;
class ErrorHandlingExample
{
static void Main()
{
try
{
Console.WriteLine("Enter a number: ");
int number = int.Parse(Console.ReadLine()); // May
throw a FormatException
Console.WriteLine("You entered: " + number);
}
catch (FormatException ex)
{
Console.WriteLine("Error: Please enter a valid
number. " + ex.Message);
}
finally
{
Console.WriteLine("End of error handling
example.");
}
}
}

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

Console.WriteLine((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))


? $"{year} is a leap year."
: $"{year} is not a leap year.");

int nextLeap = year + 1;


while (!(nextLeap % 4 == 0 && (nextLeap % 100 != 0 || nextLeap % 400 == 0)))
nextLeap++;
Console.WriteLine($"Next leap year: {nextLeap}");
}
}

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

Creating a simple .NET project involves the following essential steps:

1. Install the .NET SDK

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

2. Open a Command-Line Interface or IDE

● You can use a command-line interface like Command Prompt, PowerShell, or


Terminal.
● Alternatively, use an Integrated Development Environment (IDE) like Visual
Studio or Visual Studio Code.

3. Create a New Project

Using Command Line: Run the following command to create a new console
application:

dotnet new console -n MyProject

● This will create a new folder named MyProject with the necessary files.

● Using Visual Studio:


○ Open Visual Studio.
○ Select "Create a new project".
○ Choose Console App (.NET) or another project type.
○ Set the project name and location, then click "Create".

4. Write Code

● Navigate to the project folder (MyProject) and open the Program.cs file.

Add or modify the code for your application. For example:


using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello, .NET World!");
}
}

5. Build the Project

Using Command Line: Run the following command to compile the project:

dotnet build

● This generates the executable files in the bin folder.

● Using Visual Studio: Click Build -> Build Solution from the menu.

6. Run the Project

Using Command Line: Run the following command to execute the application:

dotnet run

● Output: Hello, .NET World!


● Using Visual Studio: Press F5 or click Run to execute the project.

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.

8. Add Dependencies (Optional)


Use the dotnet add package command to add external libraries.
dotnet add package Newtonsoft.Json

9. Test the Project (Optional)

● Create unit tests using the xUnit or NUnit framework.

Run the tests using:


dotnet test

10. Publish the Project

Publish the project for deployment using:


dotnet publish -c Release

● The output will be in the publish folder, which can be shared or deployed.

Summary Steps for 12 Marks:

1. Install the .NET SDK.


2. Open Command-Line/IDE.
3. Create a new project.
4. Write the code (Program.cs).
5. Build the project.
6. Run the project.
7. Debug the application.
8. Add dependencies and publish (if required).

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.

Types of Operator Overloading

1. Unary Operator Overloading:


○ Unary operators operate on a single operand.
○ Examples: ++, --, !, -, ~.
○ Use case: To define how unary operators behave for user-defined
types.
○ Example: Overloading ++ to increment an object's value.
2. Binary Operator Overloading:
○ Binary operators operate on two operands.
○ Examples: +, -, *, /, %, <<, >>, &, |, ^.
○ Use case: To define operations between two objects of the same class
or type.
○ Example: Overloading + for adding two complex numbers.
3. Relational Operator Overloading:
○ Relational operators compare two objects and return a boolean value.
○ Examples: ==, !=, <, >, <=, >=.
○ Use case: To compare objects of user-defined types.
○ Example: Overloading == to compare two complex numbers for
equality.
4. Logical Operator Overloading:
○ Logical operators perform logical operations.
○ Examples: &&, ||.
○ Use case: To overload logical operations between user-defined types.
○ Example: Overloading && to perform logical "AND" between objects.
5. Type Cast Operator Overloading:
○ Type cast operators define how objects of one type can be converted
to another type.
○ Examples: (Type), as, is.
○ Use case: To define custom type conversions between classes or
structs.
○ Example: Overloading explicit and implicit operators to convert
between types.
6. Indexing Operator Overloading:
○ This operator is used for objects that act like arrays or collections.
○ Example: [] for indexing.
○ Use case: To enable array-like behavior for user-defined classes.
○ Example: Overloading [] to allow array-style indexing for custom
collections.
7. Comma Operator Overloading:
○ The comma operator can be overloaded for use in custom types.
○ Use case: To define how objects of a class are separated in an
expression.
○ Example: Overloading the comma operator to return multiple values
during an operation.
8. Array Subscript Operator Overloading:
○ This allows a class to behave like an array by using the subscript
operator [].
○ Use case: To access elements of an object using indexing.
○ Example: Overloading [] to allow custom indexing in a user-defined
class.

Example: Operator Overloading in C#


using System;
class Complex
{
public int real, imag;
public Complex(int r, int i) { real = r; imag = i; }
public static Complex operator +(Complex c1, Complex c2) =>
new Complex(c1.real + c2.real, c1.imag + c2.imag);

public static bool operator ==(Complex c1, Complex c2) =>


c1.real == c2.real && c1.imag == c2.imag;
public static bool operator !=(Complex c1, Complex c2) => !(c1 == c2);
public override string ToString() => $"{real} + {imag}i";
public override bool Equals(object obj) => obj is Complex c && real == c.real &&
imag == c.imag;
public override int GetHashCode() => (real, imag).GetHashCode();
}
class Program
{
static void Main()
{
Complex c1 = new Complex(2, 3), c2 = new Complex(4, 5);
Console.WriteLine(c1 + c2); // 6 + 8i
Console.WriteLine(c1 == c2); // False
}
}
Explanation:

● The + operator adds two Complex numbers.


● The == and != operators compare Complex numbers.
● The ToString() method prints the complex number in a readable form.

3. String Handling Functions in C#


String handling functions in C# are used to manipulate and process string
data. These functions are part of the System.String class and provide
various utilities for working with strings. Here, we will explore three commonly
used string handling functions, along with examples
1. Length - Get the Length of a String
The Length property returns the number of characters in a string.
string str = "Hello";
Console.WriteLine(str.Length); // Output: 5

2. Substring - Extract a Substring from a String


Substring(startIndex, length) extracts a substring starting from a specified
index for a given length.
string str = "Hello, World!";
Console.WriteLine(str.Substring(7, 5)); // Output: World

3. Replace - Replace Substring in a String


The Replace method replaces all occurrences of a substring with another substring.
string str = "Hello, World!";
Console.WriteLine(str.Replace("World", "Universe")); // Output: Hello, Universe!

4. Concat - Concatenate Two or More Strings


The Concat method joins multiple strings together into one.
string str1 = "Hello, ";
string str2 = "World!";
Console.WriteLine(string.Concat(str1, str2)); // Output: Hello, World!

5. ToUpper() - Convert All Characters to Uppercase


The ToUpper() method converts all characters in a string to uppercase.
string str = "hello";
Console.WriteLine(str.ToUpper()); // Output: HELLO

6. ToLower() - Convert All Characters to Lowercase


The ToLower() method converts all characters in a string to lowercase.
string str = "HELLO";
Console.WriteLine(str.ToLower()); // Output: hello

7. Trim() - Remove Leading and Trailing Whitespaces


The Trim() method removes whitespace characters from the start and end of the
string.
string str = " Hello, World! ";
Console.WriteLine(str.Trim()); // Output: Hello, World!

8. IndexOf() - Find the Index of a Substring or Character


The IndexOf method returns the index of the first occurrence of a specified
substring.
string str = "Hello, World!";
Console.WriteLine(str.IndexOf("World")); // Output: 7

9. Split() - Split a String into an Array of Substrings


The Split() method divides a string into an array of substrings based on a
delimiter.
string str = "apple,banana,orange";
string[] fruits = str.Split(',');
Console.WriteLine(fruits[1]); // Output: banana

10. Contains() - Check if a String Contains a Substring


The Contains() method checks if a substring exists within a string.
string str = "Hello, World!";
Console.WriteLine(str.Contains("World")); // Output: True
Example:
using System;
class Program
{
static void Main()
{
string str = " Hello, World! ";

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.

C# I/O classes can be broadly categorized into the following groups:

● File Handling: For working with files.


● Stream Handling: For reading from and writing to byte streams.
● Directory Handling: For working with directories and their contents.
● Path Handling: For manipulating file paths.

Types of I/O Collections in C#

1. File Handling Classes

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.

2. Directory Handling Classes

Directory and DirectoryInfo are used for working with directories.

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

3. Stream Handling Classes

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.

4. Path Handling Classes

The Path class provides static methods for manipulating file and directory paths, such as:

● Path.Combine() to combine multiple strings into a valid path.


● Path.GetFileName() to get the name of a file from a path.
● Path.GetExtension() to get the file extension.
● Path.GetDirectoryName() to get the directory name from a path.

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

string dirPath = "exampleDir";


Directory.CreateDirectory(dirPath);
Console.WriteLine($"Directory created: {Directory.Exists(dirPath)}");
Console.WriteLine($"File name: {Path.GetFileName(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.

5.Properties and Events in Windows Forms Controls

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 of Windows Forms Controls

Properties are attributes or characteristics of controls that you can set or retrieve at runtime.
They affect the control's behavior, appearance, and functionality.

Some commonly used properties in Windows Forms controls are:

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 in Windows Forms Controls

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

You might also like