Unit 1 (1)
Unit 1 (1)
NET
framework.
9. Explain the architecture of the .NET framework?
2.NET Framework Class Library (FCL): The .NET Framework Class Library provides a large set of pre-built functions
and classes that can be used to create a wide range of applications.
The .NET Framework provides various tools and frameworks to help developers create different types of applications.
Here's a simplified breakdown:
1. CLR (Common Language Runtime): It's like the engine that runs .NET code, regardless of the language it's written
in. It ensures code is managed, provides memory management, and other services.
2. FCL (Framework Class Library): This is a collection of reusable classes, interfaces, and value types that are available
to developers using .NET languages.
3. Types of Applications:
○ WinForms: These are desktop applications with a graphical user interface (GUI).
○ ASP .NET: These are web-based applications that run on web servers.
○ ADO .NET: These are applications that interact with databases.
4. WPF (Windows Presentation Foundation): It's a framework for creating desktop applications with rich user
interfaces.
5. WCF (Windows Communication Foundation): This framework is used to build and deploy services that
communicate with each other.
6. WF (Windows Workflow Foundation): It's a
framework for defining, executing, and managing
workflows in .NET applications.
7. Card Space: This is a tool for managing digital
identities securely.
8. LINQ (Language Integrated Query): It's a way to
query data from different sources using .NET
languages like C# and VB.
9. Entity Framework: This is an ORM (Object-Relational
Mapping) framework that simplifies database
interactions in .NET applications.
10. Parallel LINQ (PLINQ): It's an extension of LINQ that
enables parallel processing of queries.
11. TPL (Task Parallel Library): It's a set of APIs for adding
concurrency and parallelism to .NET applications,
making it easier to work with multiple tasks
simultaneously.
12. .NET API for Store/UWP Apps: These are APIs provided by Microsoft for creating Universal Windows Platform
(UWP) apps using .NET languages.
13. Task-Based Asynchronous Model: It's a way of handling asynchronous operations and tasks in .NET applications,
making them more responsive and efficient.
6. Explain three types of arrays with suitable example and param array Ans:
Single-Dimensional Array: - A single-dimensional array is the most common type of array. It consists of a single line of
elements, and you can access elements using a single index.
Example
—---------------------------------------------------------------
int[] numbers = { 1, 2, 3, 4, 5 };
Console.WriteLine(numbers[0]);
Console.WriteLine(numbers[2]);
—---------------------------------------------------------------
Multidimensional Array: A multidimensional array stores elements in multiple dimensions, forming a matrix or a cube.
The most common type is the two-dimensional array.
Example:
—---------------------------------------------------------------
int[,] matrix = new int[3, 3]
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Console.WriteLine(matrix[0, 1]); // Output: 2
Console.WriteLine(matrix[2, 2]); // Output: 9
—---------------------------------------------------------------
Jagged Array: - A jagged array is an array of arrays. It is an array whose elements are arrays themselves. Each sub-array can
have a different length.
Example:
—---------------------------------------------------------------
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5 };
jaggedArray[2] = new int[] { 6, 7, 8, 9 };
Console.WriteLine(jaggedArray[0][1]); // Output: 2
Console.WriteLine(jaggedArray[2][2]); // Output: 8
—---------------------------------------------------------------
Param Array: A parameter array (param array) allows a method to accept a variable number of arguments. It is defined
using the params keyword.
Example:
—---------------------------------------------------------------
public static void DisplayNumbers(params int[] numbers)
{
foreach (int num in numbers)
{
Console.WriteLine(num);
}}
DisplayNumbers(1, 2, 3);
DisplayNumbers(4, 5);
DisplayNumbers(6, 7, 8, 9, 10);
—---------------------------------------------------------------
29. Explain in detail inheritance , name hiding and polymorphism with example Ans:
INHERITANCE : - 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.
1. Single Inheritance: - In single inheritance, a class inherits from only one base class. This is the simplest form of
inheritance.
—---------------------------------------------------------------
using System;
class Animal {
public void Eat() {
Console.WriteLine("Animal is eating.");
}}
class Dog : Animal {
public void Bark() {
Console.WriteLine("Dog is barking.");
}}
class MainClass {
static void Main(string[] args) {
Animal animal = new Animal();
animal.Eat(); // Output: Animal is eating.
NAME HIDING : In method hiding, you can hide the POLYMORPHISM: Polymorphism means "many forms",
implementation of the methods of a base class from and it occurs when we have many classes that are related
the derived class using the new keyword. to each other by inheritance
Example: Example:
public class My_Family { class Animal // Base class (parent) {
public void member() { public void animalSound() {
Console.WriteLine("Total number of family members: Console.WriteLine("The animal makes a sound");
3"); }
}
}
}
class Pig : Animal // Derived class (child) {
public class My_Member : My_Family {
public new void member() { public void animalSound() {
Console.WriteLine("Name: Rakesh, Age: 40 \nName: Console.WriteLine("The pig says: wee wee");
Somya, "+ "Age: 39 \nName: Rohan, Age: 20 "); }
} }
} class Dog : Animal // Derived class (child) {
class GFG { public void animalSound() {
static public void Main() { Console.WriteLine("The dog says: bow wow");
My_Member obj = new My_Member() }
obj.member(); }
}
}
26. Explain Sealed class and sealed method with suitable examples.
Sealed classes : Sealed classes are used to restrict the users from inheriting the class. A class can be sealed by using the
sealed keyword. The keyword tells the compiler that the class is sealed, and therefore, cannot be extended. No class can
be derived from a sealed class.
Sealed method : A method can also be sealed, and in that case, the method cannot be overridden. However, a method
can be sealed in the classes in which they have been inherited. If you want to declare a method as sealed, then it has to be
declared as virtual in its base class.
Sealed classes: Sealed method:
Syntax: using System;
sealed class class_name { class BaseClass{
// data members public virtual void Method1() {
// methods Console.WriteLine("Base class method.");
} }
// Sealed method
Example: public sealed void Method2() {
using System; Console.WriteLine("Sealed method.");
sealed class SealedClass { }
public int Add(int a, int b) { }
return a + b; class DerivedClass : BaseClass{
} // Attempting to override a sealed method will result in a
} compile-time error
class Program { // public override void Method2() { }
static void Main(string[] args) { // Error: 'DerivedClass.Method2()': cannot override inherited
SealedClass slc = new SealedClass(); member 'BaseClass.Method2()' because it is sealed
int total = slc.Add(6, 4); }
Console.WriteLine("Total = " + total.ToString());
} class Program {
} static void Main(string[] args) {
BaseClass obj = new BaseClass();
obj.Method1(); // Output: Base class method.
obj.Method2(); // Output: Sealed method.
26. What is a constructor? Illustrate how the superclass constructors are called in their base classes?
26. What is a constructor? Illustrate how the superclass constructors are called in their derived classes 23, 21
In C#, a constructor is a special method that is automatically called when an object is created. It is used to initialize the
object's. Constructors have the same name as the class and do not have a return type
class Program {
static void Main(string[] args) {
// Attempting to instantiate an abstract class will result in a compile-time error
// Shape shape = new Shape(); // Error: Cannot create an instance of the abstract class or interface 'Shape'
Circle circle = new Circle();
circle.Draw(); // Output: Drawing a circle.
}
}
—---------------------------------------------------------------
Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the derived
class (inherited from).
An abstract class can have both abstract and regular methods:
—---------------------------------------------------------------
abstract class Animal {
public abstract void animalSound();
public void sleep()
{
Console.WriteLine("Zzz");
}
}
—---------------------------------------------------------------
Unboxing: - Unboxing is the process of converting an object type back to a value type. It involves extracting the value from
the boxed object and copying it back to a value type variable. Unboxing can only be performed if the object is actually a
boxed value of the same value type.
Boxing: Unboxing:
using System; using System;
class GFG { class GFG {
// Main Method // Main Method
static public void Main() { static public void Main() {
// Assigning int value 2020 to num // Assigning int value 23 to num
int num = 2020; int num = 23;
// Boxing: Assigning the value of num to obj // Boxing: Assigning the value of num to obj
object obj = num; object obj = num;
// Changing the value of num // Unboxing: Explicitly converting obj back to int and
num = 100; assigning to i
int i = (int)obj;
// Printing the value of num and obj
Console.WriteLine("Value-type value of num is: {0}", // Displaying the results
num); Console.WriteLine("Value of obj object is: " + obj);
Console.WriteLine("Object-type value of obj is: {0}", Console.WriteLine("Value of i is: " + i);
obj); }}
}}
3. Substring: Substring extracts a portion of a string based on starting index and length.
string str = "Hello World";
string substr = str.Substring(6, 5); // Starting index: 6, Length: 5
Console.WriteLine(substr); // Output: World
4. Replace: Replace replaces all occurrences of a specified string with another string.
string str = "Hello World";
string replaced = str.Replace("World", "Universe");
Console.WriteLine(replaced); // Output: Hello Universe
36. Write a C# Console application to remove all characters in the second string which are present in the first string.
using System;
class Program {
static void Main() {
Console.WriteLine("Enter the first string:");
string firstString = Console.ReadLine();
Console.WriteLine("Result after removing characters from second string which are present in the first string:");
Console.WriteLine(result);
}
static string RemoveCharacters(string firstString, string secondString) {
// Convert the first string to a HashSet for faster lookup
var set = new HashSet<char>(firstString);
// Remove characters from the second string which are present in the first string
string result = "";
foreach (char c in secondString) {
if (!set.Contains(c)) {
result += c;
} }
return result;
}}
static string RemoveText(string input, int startIndex, int static string ReplaceText(string input, string oldValue,
length) {
string newValue) {
return input.Remove(startIndex, length);
} return input.Replace(oldValue, newValue);
} }
}
8. With syntax and examples explain the usage of different statements used in c#.
Here's an overview of some commonly used statements in C# with syntax examples:
Declaration Statements:
1. Variable Declaration: 2. Constant Declaration:
int age; // Declares a variable 'age' of type int const double PI = 3.14; // Declares a constant 'PI' with
value 3.14
Assignment Statements:
Simple Assignment: Compound Assignment:
age = 30; // Assigns the value 30 to the variable 'age' age += 5; // Increments 'age' by 5
Control Flow Statements:
Conditional Statements (if-else): Switch Statement:
if (age >= 18) switch (day)
{ {
Console.WriteLine("You are an adult."); case 1:
} Console.WriteLine("Monday");break;
else case 2:
{ Console.WriteLine("Tuesday");break;
Console.WriteLine("You are a minor."); default:
}- Console.WriteLine("Other day");break;
}
Loop Statements (for, while, do-while): Break Statement:
for (int i = 0; i < 5; i++) for (int i = 0; i < 10; i++)
{ {
Console.WriteLine(i); if (i == 5)
} break;
Console.WriteLine(i);
int j = 0; }
while (j < 5) Continue Statement:
{ for (int i = 0; i < 5; i++)
Console.WriteLine(j); {
j++; if (i == 3)
} continue;
Console.WriteLine(i);
int k = 0; }
do Return Statement:
{ public int Add(int a, int b)
Console.WriteLine(k); {
k++; return a + b;
} while (k < 5); }
Exception Handling Statements:
Try-Catch Statement: Finally Statement:
try try
{ {
int result = Divide(10, 0); // Some code that may throw an exception
Console.WriteLine("Result: " + result); }
} finally
catch (DivideByZeroException ex) {
{ // This block always executes, regardless of whether an
Console.WriteLine("Error: " + ex.Message); exception is thrown
} }
These are some of the fundamental statements in C# used for variable declaration, assignment, control flow, looping,
jumping, and exception handling, among others. Understanding and mastering these statements is essential for effective
C# programming.
14. What are the value types and reference types in c#? ref , out in c#? Explain with Examples.
Value Type: - A data type is a value type if it holds a data value within its own memory space. It means the variables
of these data types directly contain values.
—----------------------------------------------------------------
For example, consider integer variable
int i = 100;
int intValue = 42; // Value type example
char charValue = 'A';
Console.WriteLine($"Initial values: {intValue}, {charValue}");
—----------------------------------------------------------------
Reference Type: - Unlike value types, a reference type doesn't store its value directly. Instead, it stores the address where
the value is being stored. In other words, a reference type contains a pointer to another memory location that holds the
data.
—---------------------------------------------------------------
For example, consider the following string variable:
string s = "Hello World!!";
// Reference type example
class Person
{
public string Name { get; set; }
}
// Creating an instance of the reference type
Person person = new Person();
person.Name = "John";
Console.WriteLine($"Initial Name: {person.Name}");
}
—---------------------------------------------------------------
ref : - indicates that the parameter may be modified by the called method, and the variable must be initialized before
being passed.
—---------------------------------------------------------------
For example:
int value = 10;
Console.WriteLine($"Initial value: {value}");
ModifyValueRef(ref value);
Console.WriteLine($"Modified value (ref): {value}");
—---------------------------------------------------------------
out : - is similar to ref, but the variable does not need to be initialized before being passed. using System;
—---------------------------------------------------------------
class GFG {
static public void Main()
{
int i;
Addition(out i);
Console.WriteLine("The addition of the value is: {0}", i);
}
—---------------------------------------------------------------
32. Explain the exception handling in c#. describe the syntax of exception handling constructs with an example?
An exception is a problem that arises during the execution of a program.Exceptions provide a way to transfer control from
one part of a program to another.
C# exception handling is built upon four
keywords:
• try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one
or more catch blocks.
• catch: A program catches an exception with an exception handler at the place in a program where you want to
handle the problem. The catch keyword indicates the catching of an exception.
• finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not
thrown.
• throw: A program throws an exception when a problem shows up. This is done using a throw keyword.
Example:
using System;
class Program{
static void Main(string[] args) {
Try {
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]);
// Trying to access an index that doesn't exist
}
catch (IndexOutOfRangeException ex) {
Console.WriteLine("An error occurred: " + ex.Message);
}
catch (Exception ex) {
Console.WriteLine("An unexpected error occurred: " +
ex.Message);
}
finally {
Console.WriteLine("This block always executes,
regardless of exceptions.");
} }}
—----------------------------------------------------------------------------------------------------------------------------------------------------------------
—----------------------------------------------------------------------------------------------------------------------------------------------------------------
5. With examples, explain how memory management is done for reference and value types by CLR.
Memory management in the Common Language Runtime (CLR) differs for reference types and value types.
1. Reference Types: Reference types are objects that are allocated on the managed heap. Memory for reference types is
allocated dynamically, and the CLR automatically handles memory management, including garbage collection.
Example:-----------------------------------------------------------
// Reference type example string
str1 = "Hello"; // str1 is a reference type string
str2 = str1; // str2 now refers to the same object as str1
// Here, both str1 and str2 are pointing to the same memory location on the heap where the string "Hello" is
stored.
-----------------------------------------------------------
In this example, both str1 and str2 are reference types pointing to the same string object on the heap. When no longer
needed, the CLR's garbage collector automatically deallocates the memory occupied by these objects when they become
unreachable, freeing up memory for other objects.
2. Value Types: Value types are variables that directly contain their data. They are typically stored on the stack or inline
within other objects. Memory for value types is allocated statically or on the stack, and their lifetime is determined by their
scope.
Example:-----------------------------------------------------------
// Value type example
int num1 = 10; // num1 is a value type int
num2 = num1; // num2 gets a copy of the value of num1
// Here, num1 and num2 are independent variables each containing their own copy of the value 10.
-----------------------------------------------------------
In this example, num1 and num2 are both value types containing their own copies of the integer value 10. These variables
are stored either on the stack or inline within other objects. Their memory is deallocated automatically when they go out
of scope.
Overall , CLR manages memory for reference types by allocating memory on the managed heap and automatically handling
garbage collection, while for value types, memory is typically allocated statically or on the stack, and its deallocation is
determined by the variable's scope.
33. Explain the user defined exception in c#. Describe the syntax with an example
C# allows us to create user-defined or custom exceptions. It is used to make meaningful exceptions. To do this, we
need to inherit the Exception class. An exception is a problem that arises during the execution of a program.Exceptions
provide a way to transfer control from one part of a program to another.
Example:
—---------------------------------------------------------------
using System;
public class InvalidAgeException : Exception
{
public InvalidAgeException(String message)
: base(message)
{
} }
public class TestUserDefinedException
{
static void validate(int age)
{
if (age < 18)
{
throw new InvalidAgeException("Sorry, Age must be greater than 18"); }
}
public static void Main(string[] args)
{
try
{
validate(12);
}
catch (InvalidAgeException e) { Console.WriteLine(e); }
Console.WriteLine("Rest of the code");
} }
—---------------------------------------------------------------