C# 2 Marks Important

2 Marks (IMP)

1. Expand CLR and CTS. (regular – 2019)
  • Common Language Runtime (CLR)
  • Common Type System
2. How to use null able types in .NET?

A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example,  Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.

Example:

int? myInt = null;

// Check if myInt is null
if (myInt == null)
{
Console.WriteLine("myInt is null");
}

// Check if myInt is not null, and output its value
else
{
Console.WriteLine("myInt is " + myInt);
}

// Combline """if"""" and """else"""" statement
myInt ?? Console.WriteLine("myInt is null");
myInt ??= myInt; // This will be executed only if myInt is calculated as null
3. What do you mean by sealed class.

We use sealed classes to prevent inheritance. As we cannot inherit from a sealed class, the methods in the sealed class cannot be manipulated from other classes. It helps to prevent security issues.

4. What is tracing in ASP.NET?

ASP.NET tracing enables you to follow a page’s execution path, display diagnostic information at run time, and debug your application.

5. What do you mean by NET assembly?

NET-based applications. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. Assemblies take the form of executable (.exe) or dynamic link library (. dll) files, and are the building blocks of . NET applications.

6. Define delegate.

A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++.

7. Define debugging in windows service.

To debug a service, you must start the service and then attach a debugger to the process in which it is running. You can then debug your application by using all of the standard debugging functionality of Visual Studio.

8.What is abstract class?

An abstract class is a special type of class that cannot be instantiated. An abstract class is designed to be inherited by subclasses that either implement or override its methods.

9.What do you mean by garbage collection?
  • Garbage collector checks for objects that are no longer being used by the application,
  • The garbage collector (GC) manages the allocation and release of memory. The garbage collector serves as an automatic memory manager.
10.Define exception. Give example.

An exception is defined as an event that occurs during the execution of a program that is unexpected by the program code. An exception is an unexpected event that occurs during program execution. For example, int divideByZero = 7 / 0;

11.What is the use of throw keyword? Give example.
  • throw can also be used in a catch block to re-throw an exception handled in a catch block.
  • Any type of exceptions which is derived from Exception class can be raised using the throw keyword. Output: Student object is null. In the above example, PrintStudentName() method raises NullReferenceException if Student object is null.
12.What is interface? Give example.

Interface in C# is a blueprint of a class. It is like abstract class because all the methods which are declared inside the interface are abstract methods. It cannot have method body and cannot be instantiated. It is used to achieve multiple inheritance which can’t be achieved by class.

13. What is .NET assembly?

NET-based applications. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. Assemblies take the form of executable (.exe) or dynamic link library (. dll) files, and are the building blocks of . NET applications

14.Write the syntax of for each loop.
foreach (datatype variable name in iterable-item)
{
// body of the loop
}
15. What are the .NET aware Languages?

NET programming languages | C#, F#, and Visual Basic.

16. What are the advantages of using .NET ?
  • Reliability & Scalability. When it comes to developing commercial apps, the 
  • Flexible Deployment. 
  • Security and Safety. …
  • Simple Caching System . …
  • Open-Source Framework. …
  • Code Reusing. …
  • Automatic Monitoring in ASP.NET.
17.Define Bugs and errors.
  • Bug is informal name to Defect which is flaws or mistakes in the Code or Design. Error is any mistake done by the user while using the Application or Software.
  • an error occurs when there is an incorrect input and is temporary in nature, whereas a bug is an unexpected flaw or imperfection that could be permanent.
18. What is the use of finally block ?

By using a finally block, you can clean up any resources that are allocated in a try block, and you can run code even if an exception occurs in the try block.

19. Define multicast delegate.

MultiCast Delegate: Delegate refers to the delegation of multiple functions or methods.

20. Mention any two members of Fileinfo class.
  • Create
  • CreateText
  • Delete 
  • CopyTo
  • MoveTo
  • AppendText
  • OpenText
21. Mention any four data types in C#.
  • C# mainly categorized data types in two types: Value types and Reference types. Value types include simple types (such as int, float, bool, and char), enum types, struct types, and Nullable value types.
  • Reference types include class types, interface types, delegate types, and array types.
22. Mention the use of read only members.(Repeater – 2018)

Read-only is a file attribute which only allows a user to view a file, restricting any writing to the file.

2. Explain JIT.

Just-In-Time compiler(JIT) is a part of Common Language Runtime (CLR) in .NET which is responsible for managing the execution of . NET programs regardless of any .NET programming language.

23. What is a partial class ?

Partial Class is a unique feature of C#. It can break the functionality of a single class into many files. When the application is compiled, these files are then reassembled into a single class file. The partial keyword is used to build a partial class.

24. What is .NET Assembly ? Mention the types.

NET-based applications. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. Assemblies take the form of executable (.exe) or dynamic link library (. dll) files, and are the building blocks of . NET applications

  • Private Assembly.
  • Shared or Public Assembly.
25. Compare sealed class with an abstract class.
  • The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.
  • The sealed keyword enables you to prevent the inheritance of a class or certain class members that were previously marked virtual.
26. List any two members of System.Environment Class.
  • CommandLine
  • ExitCode
  • MachineName
  • NewLine
  • Working
  • Version
27. What are Nullable types ?

In C#, nullable types allow you to assign a null value to value types such as int, float, double, and bool, which would otherwise not allow null values. A nullable type is a value type that can also represent a null reference.

28. What is an event in C# ? Give the syntax.

Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.

public delegate void Notify();  // delegate
public class ProcessBusinessLogic
 {   
   public event NotifyProcessCompleted; // event
 }
29. Mention any 4 applications of C#.

mobile apps, desktop apps, cloud-based services, websites, enterprise software and games. 

30. What is an Event?

Events in C# are actions that allow classes or objects to inform other classes or objects when an interesting phenomenon occurs.

31.Mention any two methods of System.Console Class.
  • Beep()
  • Clear()
  • Read()
  • ReadLine()
  • Write()
  • writeLine()
32.What is a file?

A file is a collection of data stored in a disk with a specific name and a directory path.

33.What are mutable and immutable strings?

mutable types are those whose data members can be changed after the instance is created but Immutable types are those whose data members can not be changed after the instance is created.

34.What is the purpose of static keyword? (regular – 2017)

The static keyword is also part of the using static directive. Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. The static modifier can be used to declare static classes.

35.Define the term constructor.

Constructors are special methods in C# that are automatically called when an object of a class is created to initialize all the class data members.

36.List any two methods of System.GC class.
  • Using System.gc()
  • Using Runtime.getRuntime().gc()
37.What is the significance of System. Application Exception class?
  • The System. ApplicationException class supports exceptions generated by application programs
  • SystemExceptions are thrown by the CLR and are of more generic nature. ApplicationExceptions are thrown by Applications. It is used when we want to define user-defined exception. It is thrown when a nonrecoverable error has occurred, such as database crash.
38.What is a shared assembly?

A shared assembly is an assembly that resides in a centralized location known as the GAC (Global Assembly Cache) and that provides resources to multiple applications.

39.What is the purpose of Directory Info Class?

DirectoryInfo class is a part of System.IO namespace. It is used to create, delete and move directory. It provides methods to perform operations related to directory and subdirectory.

40.What is the difference between constant and read only?

While const is initialized at compile time, readonly keyword allow the variable to be initialized either at compile time or runtime. Both initializations are fine, from the compiler side. The compileTime variable tells you this is initialized beforehand.

41.What do you mean by boxing and unboxing in C#.
  • The process of converting a Value Type variable (char, int etc.) to a Reference Type variable (object) is called boxing.
  • The process of converting a Reference Type variable into a Value Type variable is known as unboxing.
42. Write any two key members of system. IO name space.

The System.IO namespace consists of IO related classes, structures, delegates and enumerations.

43. Differentiate between class and interface?

 

Class

Interface

The keyword used to create a class is “class”

The keyword used to create an interface is “interface”

A class can be instantiated i.e, objects of a class can be created.

An Interface cannot be instantiated i.e, objects cannot be created.

Classes does not support multiple inheritance.

Interface supports multiple inheritance.

It can be inherit another class.

It cannot inherit a class.

It can be inherited by another class using the keyword ‘extends’.

It can be inherited by a class by using the keyword ‘implements’ and it can be inherited by an interface using the keyword ‘extends’.

It can contain constructors.

It cannot contain constructors.

It cannot contain abstract methods.

It contains abstract methods only.

Variables and methods in a class can be declared using any access specifier(public, private, default, protected)

All variables and methods in a interface are declared as public.

Variables in a class can be static, final or neither.

All variables are static and final.

44. What do you mean by garbage collection?
  • Garbage collector checks for objects that are no longer being used by the application,
  • The garbage collector (GC) manages the allocation and release of memory. The garbage collector serves as an automatic memory manager.
45. Compare an abstract class with an interface?

An abstract class contains an abstract keyword on the declaration whereas an Interface is a sketch that is used to implement a class.

46. What is significance of BinaryWriter and BinaryReader class?

The BinaryWriter and BinaryReader classes in C# are used to read and write primitive data types and strings. These classes are used for reading from and writing to a binary file.

Significance of BinaryWriter:

  • Efficient and compact data storage: Saves storage space compared to text formats, especially for large datasets.
  • Simplified data handling: Provides dedicated methods for writing primitive data types, making code concise and easier to maintain.

Significance of BinaryReader:

  • Efficient and accurate data retrieval: Reads various data types like integers, floats, booleans, and strings from binary streams.
  • Platform-independent data access: Reads data written with BinaryWriter across different platforms and applications.
47. List various relational operations in C#.

In C#, various relational operations can be performed using operators such as:

  1. Equal to (==): Compares if two operands are equal.
  2. Not equal to (!=): Checks if two operands are not equal.
  3. Greater than (>): Checks if the left operand is greater than the right operand.
  4. Less than (<): Examines if the left operand is less than the right operand.
  5. Greater than or equal to (>=): Determines if the left operand is greater than or equal to the right operand.
  6. Less than or equal to (<=): Checks if the left operand is less than or equal to the right operand.
48. What is an interface class?

Interface in C# is a blueprint of a class. It is like abstract class because all the methods which are declared inside the interface are abstract methods. It cannot have method body and cannot be instantiated. It is used to achieve multiple inheritance which can’t be achieved by class.

49. What is an Event handler?

An event handler, in C#, is a method that contains the code that gets executed in response to a specific event that occurs in an application. Event handlers are used in graphical user interface (GUI) applications to handle events such as button clicks and menu selections, raised by controls in the user interface.

50. Define inter-operability?

C# provides support for using COM objects no matter what language was used to author them.

51. What is line terminator in C#?

Terminated line: The line segment is defined as the line which can be drawn between two points, and have fixed ends, and cannot be extended further from both the sides.

52. What is MSIL?

The Microsoft Intermediate Language (MSIL) also goes by the name Common Intermediate Language (CIL). It is typically a set of platform-independent instructions created from source code by a language-specific compiler.

53. What is the use of ‘new’ in inheritance?

When used as a declaration modifier, the new keyword explicitly hides a member that is inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base class version.

54. Write a C# program that receives command-line arguments and display them.
using System;
class OCI
{
 public static void Main(String []args)
 {
      Console.WriteLine("Argument length: "+args.Length);
    Console.WriteLine("Supplied Arguments are:");
     foreach (Object obj in args)
   {
       Console.WriteLine(obj);     
      }
  }            
}
55. What is Boxing and Unboxing?
  • The process of converting a Value Typevariable (char, int etc.) to a Reference Type variable (object) is called 
  • The process of converting a Reference Typevariable into a Value Type variable is known as 
56. How is an interface member invoke at Object level?

In Object-Oriented Programming, an interface is a contract that defines a set of methods that must be implemented by any class that claims to implement the interface. An interface member, or method, is a method defined in an interface that must be implemented by any class that implements the interface.

To invoke an interface member at the object level, you would first create an instance of a class that implements the interface, then use the dot notation to access the method as if it were a member of that class.

For example:

MyInterface if = new MyClass();
if.doSomething();
57. What are verbatim string? Given an example.
A verbatim string is a string literal that preserves the literal meaning of the characters within it. This means that any escape sequences within the string will be ignored, and the string will be interpreted as-is.
For example:
normal_string = "This is a normal string."
print(normal_string) # Output: This is a normal string.

verbatim_string = """This is
a verbatim string
with newlines
and tab characters."""
print(verbatim_string) # Output:

This is
a verbatim string
with newlines
and tab characters.
58. Define containment and delegation.

Containment refers to the practice of limiting the access that an individual or process has to sensitive resources or data on a computer system. This is typically achieved through the use of encryption, firewalls, and other security controls that are designed to block unauthorized access.

Delegation, on the other hand, refers to the practice of assigning certain security responsibilities to specific individuals or processes within an organization. This is often done to ensure that sensitive data is properly managed and secured, and that potential threats are identified and addressed in a timely manner.

59. How do you write a generic catch block?

A generic catch block is used to handle any exceptions that may occur in your program. The syntax for a catch block in Python is “try:”, followed by the code that might raise an exception, and then “except ExceptionType:” followed by the code to handle the exception. You can include multiple catch blocks, separated by “except ExceptionType1:”, “except ExceptionType2:”, etc. The catch block code should be able to handle any exception and prevent the program from crashing.

or

A generic catch block can be written in most programming languages as follows:

  1. First, you need to identify the type of exception(s) that your code might throw.
  2. Write a try-catch block around the code that might throw an exception, with the catch block containing a statement that is executed when an exception is thrown.
  3. In the catch block, you can write a catch block for multiple types of exceptions if needed, each with its own statement.

For example, in Python, a generic catch block can be written as follows:

try:
# code that might throw an exception
except Exception as e:
# statement to handle the exception

In this catch block, the except Exception as e statement means that the catch block will be executed if any exception occurs, including syntax errors, name errors, zero division errors, and other types of exceptions. The as e part of the statement is used to assign the name e to the exception object, which can be used to access the exception details in the statement that follows.

60. What are anonymous methods?

In C#, an anonymous method is a method that does not have a name. Instead, it is defined inline within another statement, such as a delegate assignment, foreach loop, or a conditional expression. Anonymous methods are commonly used to write concise and expressive code, particularly when dealing with LINQ queries.

1. Definition

2. Benefits

3. Usage

61. Write any two key members of system.IO name space.

Two key members of the System.IO namespace are File and Stream.

62. Differentiate between directory and Directory Info classes.
DirectoryDirectoryInfo
Static classInstance class
Methods for manipulating directoriesProperties and methods to access information about a specific directory
Direct access to methodsCreate an instance for a specific directory
More conciseMore object-oriented and readable
63. Differentiate SDI and MDI.
SDIMDI
Single active document window at a time
Multiple document windows open simultaneously
Switch between documents using tabs, menus, or task manager
Direct access and control over multiple documents through their windows
Application window as main focus with document windows contained within
Application window as a container for multiple document windows
Focus on single document editing, simpler interface
Multi-document comparison, contrast, or simultaneous work
Notepad, Microsoft Paint, Visual Studio Code (single file editing)
Google Chrome, Windows Explorer, Adobe Photoshop (with multiple documents)
Focus on single task, simpler UI, less resource intensive
Efficient multi-document interaction, flexibility, side-by-side comparison
Limited multi-document interaction, context switching can be cumbersome
Complex UI management, potential resource usage overhead
64. Explain DLL Hell Problem.123

The term “DLL Hell” refers to the complications that can arise from the incorrect or conflicting versions of dynamic link libraries (DLLs) in a Windows operating system environment. This issue occurs when applications or system components depend on different versions of the same DLL.

It is problematic:

  1. Version Conflict: If an application requires a specific version of a DLL and a different version is installed, it can lead to incompatibility issues or errors when the application tries to call functions from the DLL.

  2. Installation of Older Versions: When an application installs an older version of a DLL that may be required by other applications, it can overwrite the newer version, causing problems for those applications that need the later version.

  3. Shared DLLs: Shared DLLs enhance efficient resource utilization. However, if multiple applications rely on a shared DLL, and one of those applications installs an incompatible version, it can disrupt the operation of the other applications.

  4. Uninstallation Issues: When an application is uninstalled, it might remove a shared DLL that is still needed by other programs, leading to errors in those programs.

To mitigate DLL Hell, several techniques are employed such as strong naming of assemblies, versioning, side-by-side deployment, and the use of DLL redirection. 

65. Expand MSIL and JIT. (Repeater – 2019)
  • MSIL stands for Microsoft Intermediate Language
  • JIT stands for Just-in-Time compilation.
66. What is the significance of Stream Reader and Stream Writer class.
  • Stream Reader is useful when working with large files, where the data may be too large to load into memory at once. In such scenarios, Stream Reader can help in reading the data chunk-by-chunk, making it easier to work with.
  • Stream Writer can be used to write data to a file, such as in the case of saving user-generated content on a website. It can also be used to save data to a file before sending it over the network or to save it in a database.
67. What is an inner exception? Give an example.

An inner exception occurs when an exception is thrown inside another exception’s handler. In other words, it happens when one exception happens while another exception is already being processed.

Here’s an example:

try 
{
// some code
} catch (Exception e1)
{
// handle e1
} catch (Exception e2)
{
// handle e2
} catch (Exception e3)
{
// handle e3
}
68. What are properties in C# ? Give an example.

In C#, properties are a powerful tool that provide a clean and concise way to access and modify the state of an object’s fields. They act like accessor methods for fields, offering a more object-oriented and controlled approach compared to directly manipulating the fields themselves.

Their key features:

  • Encapsulation
  • Getters and Setters
  • Custom logic
  • Simplified access

Example:

public class Person
{
// Private field to store age
private int _age;

// Public property to access and modify the age
public int Age
{
get { return _age; }
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException("Age cannot be negative.");
}
_age = value;
}
}
}
69. Write any two key members of System. String Data type?
  1. System.Conosle class
  2. System.Object class

String Data Types represent text or a sequence of characters in programming languages such as Python, Java, and JavaScript. They can store alphanumeric characters as well as special symbols and spaces.

70. Write down the c# Syntax to catch exception?
try
{
// code that may throw an exception
}
catch (Exception ex)
{
// code to handle the exception
}

Leave a Reply

Your email address will not be published. Required fields are marked *

error: Content is protected !!