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

Dot Net Set2 Model

The document provides an overview of key concepts in C# and .NET, including definitions of objects, namespaces, modifiers, MSIL, and assemblies. It covers programming examples for garbage collection, exception handling, file I/O operations, and inheritance types, along with their benefits and drawbacks. Additionally, it discusses the .NET framework architecture, Windows Forms control creation, and the role of constructors.

Uploaded by

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

Dot Net Set2 Model

The document provides an overview of key concepts in C# and .NET, including definitions of objects, namespaces, modifiers, MSIL, and assemblies. It covers programming examples for garbage collection, exception handling, file I/O operations, and inheritance types, along with their benefits and drawbacks. Additionally, it discusses the .NET framework architecture, Windows Forms control creation, and the role of constructors.

Uploaded by

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

SET – 2

2MARKS:
1. What is an object?
An object is an instance of a class that contains data (fields) and
methods (functions) to perform actions. It represents a real-
world entity in programming.

2. What is the benefit of using statements in C#?


Statements in C# help execute tasks like decision-making,
looping, and controlling program flow, making the code
organized and efficient.

3. Define namespaces in .NET.


A namespace is a container that organizes classes, interfaces,
and other types in .NET, preventing name conflicts in a
program.

4. What is the role of modifiers in C#?


Modifiers define the accessibility (e.g., public, private) and
behavior (e.g., static, abstract) of classes, methods, and fields.

5. Program to demonstrate the use of constructor and destructor


in C#
csharp
Copy code
using System;

class Demo
{
public Demo() // Constructor
{
Console.WriteLine("Constructor called.");
}

~Demo() // Destructor
{
Console.WriteLine("Destructor called.");
}
}

class Program
{
static void Main()
{
Demo obj = new Demo();
}
}

6. Define MSIL.
MSIL (Microsoft Intermediate Language) is the code generated
by .NET compilers, which is executed by the CLR (Common
Language Runtime).

7. Difference between abstract class and interface


Abstract Class Interface
Can have methods with All methods are abstract by
bodies. default.
Supports fields and Cannot have fields, only
properties. properties.

8. What is an assembly in the .NET framework?


An assembly is a compiled code library in .NET (DLL or EXE) that
contains reusable code, metadata, and resources.
9. What are the main data types in C#?
The main data types in C# include:
 int (integer values)
 float (decimal values)
 string (text)
 bool (true/false)

10. What are 2 benefits of ADO.NET?


 Fast data access from databases.
 Supports both connected (online) and disconnected
(offline) data models.

5MARKS:
1. Garbage collections in. Net with program
Garbage collection (GC) automatically manages memory
in .NET by reclaiming unused objects. It prevents memory leaks
and ensures efficient memory usage, improving application
performance.

Example Program:
using System;
class GarbageCollectionExample
{
static void Main()
{
// Create an object
MyClass obj = new MyClass();
// Nullify reference to make it eligible for garbage
collection
obj = null;
// Force garbage collection
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine("Garbage Collection completed.");
}
}
class MyClass
{
~MyClass() // Destructor
{
Console.WriteLine("Destructor called, object destroyed.");
}
}

2. Multiple exceptions
In C#, you can handle multiple exceptions by using multiple
catch blocks within a try-catch statement. Each catch block is
designed to handle a specific exception type. This helps in
managing errors effectively by providing specific responses to
different types of exceptions.

Example:
using System;
class Program
{
static void Main()
{
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); //
IndexOutOfRangeException

int result = 10 / 0; // DivideByZeroException


}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Error: Index is out of range.");
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: Cannot divide by zero.");
}
catch (Exception ex)
{
Console.WriteLine("An unexpected error occurred: " +
ex.Message);
}
}
}

Benefits:
 Allows handling specific errors with tailored responses.
 Improves program robustness by preventing crashes.
 Ensures fallback mechanisms for unexpected exceptions.

3. File io operations with example


 File I/O (Input/Output) operations in C# allow reading from
and writing to files, which is essential for tasks like saving
user data, processing files, or handling external resources.
 The .NET framework provides a rich set of classes for
working with files, located primarily in the System.IO
namespace.
 Common classes used for file I/O operations include File,
FileInfo, StreamReader, StreamWriter, FileStream,
and BinaryReader.
 Reading Files:

The StreamReader class is commonly used to read text files. It


reads characters from a byte stream in a specific encoding.

Example of reading a text file:

using System;

using System.IO;

class Program {

static void Main() {

string filePath = @"C:\example.txt";

using (StreamReader reader = new StreamReader(filePath)) {

string content = reader.ReadToEnd();

Console.WriteLine(content);

} } }

 Writing to Files:

The StreamWriter class is used for writing text to files. It provides


methods like Write() and WriteLine() to write data.

Example of writing to a text file:

using System;

using System.IO;

class Program {

static void Main() {

string filePath = @"C:\example.txt";


using (StreamWriter writer = new StreamWriter(filePath)) {

writer.WriteLine("Hello, this is a test!");

writer.WriteLine("Writing text to a file.");

} } }

 Checking if a File Exists:

Before performing file operations like reading or writing, it's often a


good practice to check if the file exists.

Example of checking file existence:

using System;

using System.IO;

class Program {

static void Main() {

string filePath = @"C:\example.txt";

if (File.Exists(filePath)) {

Console.WriteLine("File exists."); }

else {

Console.WriteLine("File does not exist.");

} } }

 Appending Data to a File:

To add data to an existing file without overwriting it, you can use the
StreamWriter with the append parameter set to true.

Example of appending data to a file:


using System;

using System.IO;

class Program {

static void Main() {

string filePath = @"C:\example.txt";

using (StreamWriter writer = new StreamWriter(filePath,


append: true)) {

writer.WriteLine("This is new text appended to the file.");

} } }

 Binary File I/O:

For reading and writing binary data (e.g., images or custom binary
files), the FileStream class is used in conjunction with
BinaryReader and BinaryWriter.

Example of reading a binary file:

using System;

using System.IO;

class Program {

static void Main() {

string filePath = @"C:\example.bin";

using (FileStream fs = new FileStream(filePath, FileMode.Open))

using (BinaryReader reader = new BinaryReader(fs))

{
int data = reader.ReadInt32();

Console.WriteLine("Read integer: " + data);

} }}

4. To print the number between m to n while skipping k


using System;
class Program
{
static void Main()
{
Console.WriteLine("Enter the starting number (m): ");
int m = int.Parse(Console.ReadLine());

Console.WriteLine("Enter the ending number (n): ");


int n = int.Parse(Console.ReadLine());

Console.WriteLine("Enter the number to skip (k): ");


int k = int.Parse(Console.ReadLine());

Console.WriteLine($"Numbers between {m} and {n}, skipping


{k}:");

for (int i = m; i <= n; i++)


{
if (i == k)
continue;

Console.Write(i + " ");


}
}
}

OUTPUT:
Enter the starting number (m):
2
Enter the ending number (n):
5
Enter the number to skip (k):
3
Numbers between 2 and 5, skipping 3:
245

12MARKS:

1. Framework architecture

A Framework is a Software. It is a collection of many small


technologies integrated together to develop applications that
can be executed anywhere.

What is .NET Framework?


According to Microsoft, .NET Framework is a software
development framework for building and running applications
on Windows. The .NET Framework is part of the .NET platform, a
collection of technologies for building apps for Linux, macOS,
Windows, iOS, Android, and more.
The .NET Framework is composed of four main components:
 Common Language Runtime (CLR)
 Framework Class Library (FCL),
 Core Languages (WinForms, ASP.NET, and ADO.NET),
and
 Other Modules (WCF, WPF, WF, Card Space, LINQ,
Entity Framework, Parallel LINQ, Task Parallel Library,
etc.)
What does the .NET Framework Provide?
The two major components of the .NET Framework are the
Common Language Runtime and the .NET Framework Class
Library.
 CL (Class Libraries)
 CLR (Common Language Runtime)

 .NET Framework Class Libraries:


The .NET Framework Class Libraries are designed by Microsoft.
Without Class Libraries, we can’t write any code in .NET. So,
Class Libraries are also known as the Building block of .NET
Programs. These are installed into the machine when we
installed the .NET framework. Class Libraries contains pre-
defined classes and interfaces and these classes and interfaces
are used for the purpose of application development. The Class
Library also provides a set of APIs and types for common
functionality. It provides types for strings, dates, numbers, etc.

 Common Language Runtime (CLR):


CLR stands for Common Language Runtime and it is the core
component under the .NET framework which is responsible for
converting the MSIL (Microsoft Intermediate Language) code
into native code and then provides the runtime environment to
execute the code. That means Common Language Runtime (CLR)
is the execution engine that handles running applications. It
provides services like thread management, garbage collection,
type safety, exception handling, and more

In the .NET framework, the Code is Compiled Twice.


 In the 1st compilation, the source code is compiled by
the respective language compiler and generates the
intermediate code which is known as MSIL (Microsoft
Intermediate Language) or IL (Intermediate language
code) Or Managed Code.
 In the 2nd compilation, MSIL code is converted into
Native code (native code means code specific to the
Operating system so that the code is executed by the
Operating System ) and this is done by CLR.

2. Give brief explanation the window form control creation with


example
Windows Forms is a framework for building desktop
applications with a graphical user interface (GUI). It provides a
variety of controls like buttons, labels, textboxes, etc., to create
interactive applications.

Key Steps to Create Controls:


 Create a Windows Forms Project:
o Open Visual Studio and create a new project using the

"Windows Forms App" template.


 Add Controls:
o Use the Toolbox to drag and drop controls like Button,

Label, or TextBox onto the form.


o Alternatively, you can create controls

programmatically in the code.


 Set Properties:
o Customize controls by setting their properties such as

Text, Size, Location, and Font.


 Event Handling:
o Add event handlers (e.g., Click, TextChanged) to define

what happens when the user interacts with the


controls.

Example:

using System;

using System.Windows.Forms;

class Program: Form

static void Main ()

Application.Run(new Program ());

public Program()

this.Text = "Simple Windows Form Example";


this.Size = new System.Drawing.Size(400, 300);

Label label = new Label();

label.Text = "Enter your name:";

label.Location = new System.Drawing.Point(20, 20);

this.Controls.Add(label);

TextBox textBox = new TextBox();

textBox.Location = new System.Drawing.Point(150, 20);

this.Controls.Add(textBox); // Add textbox to the form

Button button = new Button();

button.Text = "Submit";

button.Location = new System.Drawing.Point(150, 60);

this.Controls.Add(button);

button.Click += (sender, e) =>

MessageBox.Show($"Hello, {textBox.Text}!");

};

}
Advantages:
 Provides a drag-and-drop interface for easy GUI design.

 Supports programmatic control creation for flexibility.

 Simplifies event handling with built-in methods.

Disadvantages:

 Windows Forms lacks modern design features and


advanced UI capabilities.
 It has less flexible layout management and scaling for
different screen sizes.
 Windows Forms is restricted to Windows and does not
support cross-platform

3. Inheritance with various types and program


Inheritance is a fundamental concept in object-oriented
programming that allows us to define a new class based on an
existing class. The new class inherits the properties and
methods of the existing class and can also add new properties
and methods of its own. Inheritance promotes code reuse,
simplifies code maintenance, and improves code organization.
In C#, there are 4 types of inheritance:
 Single inheritance: A derived class that inherits from
only one base class.
 Multi-level inheritance: A derived class that inherits
from a base class and the derived class itself becomes
the base class for another derived class.
 Hierarchical inheritance: A base class that serves as a
parent class for two or more derived classes.
 Multiple inheritance: A derived class that inherits from
two or more base classes.

EXAMPLE:
using System;

// single inheritance
class Animal {
public void Eat() {
Console.WriteLine("Animal is eating.");
}
}

class Dog : Animal {


public void Bark() {
Console.WriteLine("Dog is barking.");
}
}

// multi-level inheritance
class Mammal : Animal {
public void Run() {
Console.WriteLine("Mammal is running.");
}
}

class Horse : Mammal {


public void Gallop() {
Console.WriteLine("Horse is galloping.");
}
}

// hierarchical inheritance
class Bird : Animal {
public void Fly() {
Console.WriteLine("Bird is flying.");
}
}

class Eagle : Bird {


public void Hunt() {
Console.WriteLine("Eagle is hunting.");
}
}

class Penguin : Bird {


public void Swim() {
Console.WriteLine("Penguin is swimming.");
}
}

// multiple inheritance
interface I1 {
void Method1();
}

interface I2 {
void Method2();
}

class MyClass : I1, I2 {


public void Method1() {
Console.WriteLine("Method1 is called.");
}

public void Method2() {


Console.WriteLine("Method2 is called.");
}
}
// main program
class Program {
static void Main(string[] args) {
// single inheritance
Dog dog = new Dog();
dog.Eat();
dog.Bark();

// multi-level inheritance
Horse horse = new Horse();
horse.Eat();
horse.Run();
horse.Gallop();

// hierarchical inheritance
Eagle eagle = new Eagle();
Penguin penguin = new Penguin();
eagle.Fly();
eagle.Hunt();
penguin.Fly();
penguin.Swim();

// multiple inheritance
MyClass myClass = new MyClass();
myClass.Method1();
myClass.Method2();

Console.ReadLine();
}
}
Advantages of Inheritance:
 Code Reusability: Inheritance allows us to reuse
existing code by inheriting properties and methods
from an existing class.
 Code Maintenance: Inheritance makes code
maintenance easier by allowing us to modify the base
class and have the changes automatically reflected in
the derived classes.
 Code Organization: Inheritance improves code
organization by grouping related classes together in a
hierarchical structure.

Disadvantages of Inheritance:
 Tight Coupling: Inheritance creates a tight coupling
between the base class and the derived class, which
can make the code more difficult to maintain.
 Complexity: Inheritance can increase the complexity of
the code by introducing additional levels of abstraction.
 Fragility: Inheritance can make the code more fragile by
creating dependencies between the base class and the
derived class.

4. What is constructor and types with example.

A constructor is a member function of a class that initializes the


object and allocates the memory. A constructor has the same
name as that of its class, thus it can be easily identified. It is
always declared and defined in the public section of a class. A
constructor does not have any return type. Therefore, it does
not return anything, but it is not even void.
Class name (arguments if any)
{
...
...
};

A single class may have multiple constructors that are


differentiated based on the number and type of arguments
passed.

There are three main types of constructors, namely:


 default constructor
 parameterized constructor
 copy constructor.

 Default Constructor in C#
A constructor without any parameters is called a default
constructor; in other words, this type of constructor does not
take parameters. The drawback of a default constructor is that
every instance of the class will be initialized to the same values
and it is not possible to initialize each instance of the class with
different values. The default constructor initializes:
 All numeric fields in the class to zero.
 All string and object fields to null.

 Parameterized Constructor in C#
A constructor with at least one parameter is called a
parameterized constructor. The advantage of a parameterized
constructor is that you can initialize each instance of the class
with a different value.

Example:
using System;
namespace Constructor
{
class paraconstrctor
{
public int a, b;
public paraconstrctor(int x, int y) {
a = x;
b = y;
}
}
class MainClass
{
static void Main ()
{
paraconstrctor v = new paraconstrctor(100, 175);
Console.WriteLine("Parameterized constructor example by
vithal wadje");
Console.WriteLine("\t");
Console.WriteLine("value of a=" + v.a );
Console.WriteLine("value of b=" + v.b);
Console.Read();
}
}

 Copy Constructor in C#
The constructor which creates an object by copying variables
from another object is called a copy constructor. The purpose of
a copy constructor is to initialize a new instance to the values of
an existing instance.
The copy constructor is invoked by instantiating an object of
type employee and bypassing it the object to be copied.

Example:
using System;
namespace copyConstractor
{
class employee
{
private string name;
private int age;
public employee (employee emp)
{
name = emp.name;
age = emp.age;
}
public employee (string name, int age)
{
this.name = name;
this.age = age;
}
public string Details // Get deatils of employee
{
get
{
return " The age of " + name +" is "+ age.ToString();
}
}
}
class empdetail
{
static void Main ()
{
employee emp1 = new employee ("Vithal", 23
employee emp2 = new employee(emp1);
Console.WriteLine(emp2.Details);
Console.ReadLine();
}
}
}

5. Repeated one (SET 1 [12MARK] 5th one)

You might also like