C# Fundamental Part 2

Spread the love

26. How are extension methods used in C#?

Sample answer:

Extension methods allow developers to add a method to existing types without changing the original source code. This allows them to extend the functionality of the method. An extension method is a static method and uses the <this> keyword.

27. How are user controls created in C#?

Sample answer:

In C#, user controls allow developers to write code that can be used in various areas of the program. 

For example, if a website requires the same search control in multiple places, it can be created once as a user control and then dropped into different areas of the code. This serves the dual purposes of reusability and bug prevention.

28. When should nullable types be used in C#?

Sample answer:

In C#, nullable types are used to represent an undefined value of an underlying type. It essentially means ‘no value’ and is generally used when no data is available for the field.

29. How is serialization implemented in C#?

Sample answer:

In C#, serialization is the process of converting an object into a stream of bytes for storage on a memory, database, or file. This allows the developer to save the state of an object for future reference. 

Serialization can be performed by applying <SerializableAttribute> to a type to indicate that instances of this type can be serialized. All public and private fields marked as such are then serialized by default.

30. What is the difference between String and StringBuilder in C#?

Sample answer:

A string object is immutable, meaning that it cannot be changed after it’s created. Any operation that tries to modify the string object will simply create a new string object. On the other hand, a string builder object is mutable and can be modified as the developer sees fit.

31. How is reflection used in C#?

Sample answer:

In C#, reflection is used to obtain metadata on types at runtime. In other words, it allows developers to retrieve data on the loaded assemblies and the types within them.

It’s implemented using a two-step process. First, you get the type object. Second, you use the type to browse members, such as methods and properties. 

32. What are the advantages of generics in C#?

Sample answer:

In C#, generics allow the developer to define classes and methods which can be used with any data type. This brings several benefits:

  • Saves time by reusing code
  • Provides type safety without unnecessary overhead
  • Removes the need for boxing and unboxing
  • Generic collection types generally perform better with value types because there is no need to box the values

33. What are the disadvantages of generics in C#?

Sample answer:

There are a few limitations with generics. These include:

  • They cannot be used with enumerations
  • They cannot be used with lightweight dynamic methods
  • The .NET framework doesn’t support context-bound generic types

34. What are the key differences between Array and ArrayList in C#?

Sample answer:

An ArrayList has wider usage than an Array. The key differences include:

  • An Array is strongly-typed, meaning it only stores the same type of data. An ArrayList is a non-generic collection type, meaning it can store multiple types of data
  • An Array stores a fixed number of elements. An ArrayList features a variable number of elements and can continually be added to
  • An Array cannot accept null values, whereas an ArrayList can
  • The relative simplicity of an Array means it typically provides better performance than an ArrayList

35. How are the different types of control statements used in C#?

Sample answer:

Each type of control statement has its own set of syntax used to invoke the statement:

  1. Selection statements include <if>, <else>, <switch>, and <case>
  2. Iteration statements include <do>, <for>, <foreach>, and <while>
  3. Jump statements include <break>, <continue>, <return>, and <goto>

36. When should multithreading be used and when should it be avoided in C#?

Sample answer:

Multithreading, or threading, can be a good way to improve the performance of a program where several operations run simultaneously. 

It allows distinct threads to run at their own time, rather than having to wait for the previous step to be complete. This has the potential to speed up a program.

However, multithreading is not advisable when much of the program’s processes are interdependent. For example, if Step B was reliant on the prior completion of Step A, multithreading would lead to performance issues and create bugs in the program. 

As a program grows more complex, threading becomes a more delicate operation. 

37. What is a Delegates/multicast delegate in C#?

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++. It provides a way which tells which method is to be called when an event is triggered. 
For example, if you click on a Button on a form (Windows Form application), the program would call a specific method. In simple words, it is a type that represents references to methods with a particular parameter list and return type and then calls the method in a program for execution when it is needed.
Important Points About Delegates: 

  • Provides a good way to encapsulate the methods.
  • Delegates are the library class in System namespace.
  • These are the type-safe pointer of any method.
  • Delegates are mainly used in implementing the call-back methods and events.
  • Delegates can be chained together as two or more methods can be called on a single event.
  • It doesn’t care about the class of the object that it references.
  • Delegates can also be used in “anonymous methods” invocation.
  • Anonymous Methods(C# 2.0) and Lambda expressions(C# 3.0) are compiled to delegate types in certain contexts. Sometimes, these features together are known as anonymous functions.

Declaration of Delegates

Delegate type can be declared using the delegate keyword. Once a delegate is declared, delegate instance will refer and call those methods whose return type and parameter-list matches with the delegate declaration.


// “public” is the modifier

// “int” is return type

// “GeeksForGeeks” is delegate name

// “(int G, int F, int G)” are the parameters

public delegate int GeeksForGeeks(int G, int F, int G);

Instantiation & Invocation of Delegates

After declaring a delegate, a delegate object is created with the help of new keyword. Once a delegate is instantiated, a method call made to the delegate is pass by the delegate to that method. The parameters passed to the delegate by the caller are passed to the method, and the return value, if any, from the method, is returned to the caller by the delegate.

GeeksForGeeks GFG = new GeeksForGeeks (Geeks);
       // here,
       // "GeeksForGeeks" is delegate name. 
       // "GFG" is instance_name
       // "Geeks" is the calling method.

// C# program to illustrate the use of Delegates

using System;

namespace GeeksForGeeks {

// declare class “Geeks”

class Geeks {

// Declaring the delegates

// Here return type and parameter type should

// be same as the return type and parameter type

// of the two methods

// “addnum” and “subnum” are two delegate names

public delegate void addnum(int a, int b);

public delegate void subnum(int a, int b);

    // method “sum”

    public void sum(int a, int b)


        Console.WriteLine(“(100 + 40) = {0}”, a + b);


    // method “subtract”

    public void subtract(int a, int b)


        Console.WriteLine(“(100 – 60) = {0}”, a – b);


// Main Method

public static void Main(String []args)


    // creating object “obj” of class “Geeks”

    Geeks obj = new Geeks();

    // creating object of delegate, name as “del_obj1”

    // for method “sum” and “del_obj2” for method “subtract” &

    // pass the parameter as the two methods by class object “obj”

    // instantiating the delegates

    addnum del_obj1 = new addnum(obj.sum);

    subnum del_obj2 = new subnum(obj.subtract);

    // pass the values to the methods by delegate object

    del_obj1(100, 40);

    del_obj2(100, 60);

    // These can be written as using

    // “Invoke” method

    // del_obj1.Invoke(100, 40);

    // del_obj2.Invoke(100, 60);





(100 + 40) = 140
(100 - 60) = 40

Multicast Delegates:

Multicasting of delegate is an extension of the normal delegate(sometimes termed as Single Cast Delegate). It helps the user to point more than one method in a single call.

  • Delegates are combined and when you call a delegate then a complete list of methods is called.
  • All methods are called in First in First Out(FIFO) order.
  • ‘+’ or ‘+=’ Operator is used to add the methods to delegates.
  • ‘–’ or ‘-=’ Operator is used to remove the methods from the delegates list.

Note: Remember, multicasting of delegate should have a return type of Void otherwise it will throw a runtime exception. Also, the multicasting of delegate will return the value only from the last method added in the multicast. Although, the other methods will be executed successfully.
Below program demonstrates the use of Multicasting of a delegate:

Unlike a simple delegate, a multicast delegate in C# references multiple target methods. When a multicast delegate is used, all the functions the delegate is pointing to are invoked. They’re implemented using the Multicast Delegate class, which is derived from the system.

using System;

class rectangle {

// declaring delegate

public delegate void rectDelegate(double height,

                                  double width);

    // “area” method

    public void area(double height, double width)


        Console.WriteLine(“Area is: {0}”, (width * height));


    // “perimeter” method

    public void perimeter(double height, double width)


        Console.WriteLine(“Perimeter is: {0} “, 2 * (width + height));


// Main Method

public static void Main(String []args)


    // creating object of class

    // “rectangle”, named as “rect”

    rectangle rect = new rectangle();

    // these two lines are normal calling

    // of that two methods

    // rect.area(6.3, 4.2);

    // rect.perimeter(6.3, 4.2);

    // creating delegate object, name as “rectdele”

    // and pass the method as parameter by

    // class object “rect”

    rectDelegate rectdele = new rectDelegate(rect.area);

    // also can be written as

    // rectDelegate rectdele = rect.area;

    // call 2nd method “perimeter”

    // Multicasting

    rectdele += rect.perimeter;

    // pass the values in two method

    // by using “Invoke” method

    rectdele.Invoke(6.3, 4.2);


    // call the methods with

    // different values

    rectdele.Invoke(16.3, 10.3);




Area is: 26.46
Perimeter is: 21 
Area is: 167.89
Perimeter is: 53.2 

38. How would you explain the four fundamental concepts of object-oriented programming? 

Sample answer:

The four fundamental concepts of object-oriented programming can be explained as follows:

  • Encapsulation is the bundling of data, including the methods that operate on that data, into a single, private unit
  • Polymorphism is the ability of a type to take on many forms using a single interface
  • Abstraction is the concealment of unnecessary program details so that the user only sees the essential attributes
  • Inheritance is the process where one class derives (or inherits) its attributes and methods from another

39. How is the singleton design pattern implemented in C#?

Sample answer:

The singleton design pattern ensures that only one object of its kind exists, and provides global access to it for any other code. This design pattern can be implemented in a number of ways, using:

  • Thread-safety singleton
  • Thread-safety singleton using double-check locking
  • No thread-safe singleton
  • Thread-safe without a lock
  • .NET 4’s Lazy<T> type

40. What is the difference between late binding and early binding in C#?

Sample answer:

The key differences between early binding and late binding are:

  • Early binding occurs at compile-time, whereas late binding occurs at runtime
  • Early binding uses class information to resolve method calling, whereas late binding uses the object to resolve method calling
  • Typically, the performance of late binding is slower than early binding because it occurs at runtime

41. How is HashSet used in C#?

Sample answer:

In C#, HashSet is an unordered collection of distinct values. Generally, it is used to prevent duplicate elements from being placed in a collection, and it performs better than a list in achieving this goal. 

It is implemented using the HashSet class, which is derived from the System. 

42. When is method overriding used in C#?

Sample answer:

In C#, method overriding is used to invoke functions that belong to different classes. This process creates a method in the derived class with the same signature as a method in the base class without modifying the code of the base class. This helps achieve runtime polymorphism.

43. What is the difference between Const and ReadOnly keywords in C#?

Sample answer:

There are several differences between Const and ReadOnly keywords in C#. These include:

  • ReadOnly is a constant used at runtime, whereas Const is a constant used at compile-time
  • ReadOnly values can be changed, whereas Const values cannot be changed
  • ReadOnly cannot be declared inside the method, whereas Const can

44. How are custom controls added to an application in C#?

Sample answer:

A custom control is designed for single use in a specific application. There are three main ways to create a new custom control:

  1. Derive it from an existing user control
  2. Group existing controls together into new compiled control
  3. Create a new control by deriving from the System.Windows.Controls.Control class

45. What is meant by dependency injection in C#?

Sample answer:

In C#, dependency injection (DI) is a design pattern used to develop loosely coupled code. This process moves the creation and binding of dependent objects outside of the class that depends on them. The main purpose of this is to make future changes to code more manageable. 

46. How can circular references be fixed in C#?

Sample answer:

In C#, circular references are most commonly resolved using garbage collection. The garbage collector systematically detects and collects circular references. Other solutions for circular references issues include callback methods, event handlers, and dependency injection.

47. How can a class be set to be inherited without overriding the method in C#?

Sample answer:

Provided that the method isn’t virtual, it won’t be overridden. However, if the class is inheriting from a base class that contains a virtual member function, you can use the <sealed> modifier to avoid further overriding that member function.

48. What are the different techniques for overloading a method in C#?

Sample answer:

Method overloading can be achieved in the three following ways:

  • By using different types of data for parameters in a method
  • By changing the number of parameters in a method
  • By changing the order of parameters in a method

49. How is exception handling performed in C#?

Sample answer:

In C#, exception handling helps detect errors in code at runtime. The process is implemented using four different keywords:

  1. <Try> identifies blocks of code where exceptions are activated
  2. <Catch> catches the exceptions that have been identified by <Try>
  3. <Finally> executes a given set of statements depending on whether an exception is thrown out or not
  4. <Throw> removes the exception

50. What is the difference between a throw exception and a throw clause in C#?

Sample answer:

The fundamental difference is that throw exceptions overwrite the stack trace, whereas throw clauses retain the stack information. As such, it is much harder to retrieve the original code responsible for throwing the exception with throw exceptions.

51.Explain what are classes and objects in C#?

Answer: C# is an object-oriented language and classes are its foundation. A class generally depicts the structure of data, how data is stored and managed within a program. A class has its own properties, methods, and other objects that define the class.

Objects are the real-world entity having some characteristics and is created using the class instance. These classes define the type of the defined object.

For example, if we consider a program that covers the object related to the book. We call the class a Book which has two properties: name and the author. In real programming, Vedas is an object and an instance of the class Book.

52.Describe the different C# classes in detail.

Answer:  There are 4 types of classes that we can use in C#:

  • Static Class: It is the type of class that cannot be instantiated, in other words, we cannot create an object of that class using the new keyword and the class members can be called directly using their class name.
  • Abstract Class: Abstract classes are declared using the abstract keyword. Objects cannot be created for abstract classes. If you want to use it then it must be inherited in a subclass. You can easily define abstract or non-abstract methods within an Abstract class. The methods inside the abstract class can either have an implementation or no implementation.
  • Partial Class: It is a type of class that allows dividing their properties, methods, and events into multiple source files, and at compile time these files are combined into a single class.
  • Sealed Class:  One cannot inherit a sealed class from another class and restricts the class properties. Any access modifiers cannot be applied to the sealed class. 
  • 53 . Explain different access modifiers in C#?

Answer: These are the keywords that help to define the accessibility of class, member, and data type in the program. These keywords are used to restrict the use of some data manipulation done by other classes. There are 4 types of access modifiers- public, private, protected, and internal. These modifiers define 6 other accessibility levels when working together- public, protected, internal, protected internal, private, and private protected.

Below is the access chart of the modifiers.

Complete programYesNoNoNoNoNo
Derived types within the current assemblyYesYesNoYesNoYes
Using  classYesYesYesYesYesYes
Current assemblyYesNoYesYesNoNo
Derived data typesYesYesNoYesNoNo
  • 54.How can you describe object-oriented concepts in detail?

Answer:  C# is an object-oriented programming language that supports 4 OOP concepts.

  • Encapsulation: defines the binding together code and the data and keeps it safe from any manipulation done by other programs and classes. It is a container that prevents code and data from being accessed by another program that is defined outside the container.
  • Abstraction: this concept of object-oriented protects everything other than the relevant data about any created object in order to increase efficiency and security within the program.
  • Inheritance: Inheritance is applied in such a way where one object uses the properties of another object. 
  • Polymorphism: is a feature that allows one interface to act as a base class for other classes. This concept is often expressed as a “single interface but multiple actions”. 
  • 55 .Explain how code gets compiled in C#?

Answer: It takes 4 steps to get a code to get compiled in C#. Below are the steps:

  • First, compile the source code in the managed code compatible with the C# compiler.
  • Second, combine the above newly created code into assemblies.
  • Third, load the CLR.
  • Last, execute the assembly by CLR to generate the output.
  • 56.What is break and continue statements in C#, explain?

Answer:  Below is the differences:

You can use break statements in both switch and loop (for, while, and do-while ) statements.You can use continue statements only in the loop (for, while, do) statements.
The switch or loop statements terminate at the moment the break statement is executed and it ends abruptly from there.You cannot make a continue statement terminate the loop, it carries on the loop to go to the next iteration level without executing the immediate next step.
The loop or switch exits immediately from the inner loop when the compiler encounters a break statement and comes out of the inner loop.A continue that is placed inside a nested loop within a switch causes the next loop iteration.


  • 57.How you can explain the use of ‘using’ statements in C# in detail.

Answer:  The using statement is used to control the usage of one or more resources that are being used within the program. The resources are continuously consumed and released. The main function of this statement is to manage unused resources and release them automatically. Once the object is created which is using the resource and when you are done you make sure that the object’s dispose method is called to release the resources used by that object, this is where using statements works well.

For example:

using (MyResource abc = new MyResource())
Gets translated to,
MyResource abc= new MyResource();
 // Check for a null resource.
 if (abc!= null)
     // Call the object's Dispose method.
  • 58.Describe the C# dispose of the method in detail.

Answer: Dispose of the method: The disposeof() method releases the unused resources by an object of the class. The unused resources like files, data connections, etc. This method is declared in the interface called IDisposable which is implemented by the class by defining the interface IDisposable body. Dispose method is not called automatically, the programmer has to implement it manually for the efficient usage of the resources.

  • 59. Explain in detail the finalize method in C#?

Answer: Finalize method The finalize () method is defined in the object class which is used for cleanup activities. This method is generally called by the garbage collector whenever the reference of any object is not used for a long time. Garbage collector frees that managed resources automatically but if you want to free the unused resources like filehandle, data connection, etc., then you have to implement the finalize method manually.

  • How you can define the exception handling in C#?

Answer: An exception is a raised problem that may occur during the execution of the program. Handling exceptions offers a simple way to pass the control within the program whenever an exception is raised. C# exceptions are handled by using 4 keywords and those are try, catch, finally, throw.

  • try: a raised exception finds a particular block of code to get handled. There is no limit on the number of catch blocks that you will use in your program to handle different types of exception raised.
  • catch: you can handle the raised exception within this catch block. You can mention the steps that you want to do to solve the error or you can ignore the error by suppressing it by the code.
  • Finally: irrespective of the error, if you still want some set of instructions to get displayed then you can use those statements within the finally block and it will display it on the screen.
  • throw: you can throw an exception using the throw statement. It will display the type of error you are getting.

60.How can you check if a number is an Armstrong number or not with C#?


using System;  
  public class ArmstrongDemo  
     public static void Main(string[] args)  
       int  n,b,sum=0,num;      
       Console.Write("Enter the Number= ");      
       n= int.Parse(Console.ReadLine());     
        Console.Write("Armstrong Number.");      
        Console.Write("Not Armstrong Number.");      


Enter the Number= 371
Armstrong Number.

  • 61.What is a different approach to the passing parameter in C#?

Answer:  Parameters can be passed in three different ways to any defined methods and they are defined below:

Value Parameters:  it will pass the actual value of the parameter to the formal parameter. In this case, any changes that are made into the formal parameter of the function will be having no effect on the actual value of the argument.

Reference Parameters: with this method, you can copy the argument that refers to the memory location into the formal parameter that means any changes made to the parameter affect the argument.

Output Parameters: This method returns more than one value to the method.

62.How you can implement nullable<> types in C#? explain with the syntax of Nullable type.

AnswerIn C#, you cannot put a null value directly into any variable and the compiler does not support it. So, the revised version C# 2.0 provides you with a special feature that will assign a null value to a variable that is called as the Nullable type. You cannot make the nullable types to work with value types. Nullable value can only work with the reference types as it already has a null value. System.Nullable<T> structure creates the instance nullable type, where T defines the data type. This T contains a non-nullable value type that can be any data type you want.


Nullable<data_type> variable_name=null;


Datatype? variable_name=null;

There is no possibility that you can access the value of the nullable value type directly with assigning the value. For getting its original assigned value you have to use the method GetValueOrDefault(). If the value is null then it will provide zero as it is its default value.

  • 63.What are various types of comments in C#, explain with example?

Answer:  C# supports three types of comments-

1. Single line comment

Syntax:  //single line

2. Multiple line comment

Syntax: /* multiple lines


3. XML comment

Syntax: /// set error

  • 64.What are the constructors?

Answer: In C#, there is a special method that is invoked automatically at the time of object creation. It initializes the data members of a new object and has the same name as the class or the structure. There are two types of constructors:

  • Default constructor: it has no parameter to pass.
  • Parameterized constructor: it is invoked with parameters that are passed to the class during object creation.
  • What are the different collection classes in C#?

Answer: Collection classes are classes that are mainly used for data storage and retrieval. These collection classes will serve many purposes like allocating dynamic memory during run time and you can even access the items of the collection using the index value that makes the search easier and faster. These collection classes belong to the object class.

There are many collection classes which are as follows:

Some of the common collection classes are described in this section:

  Generic Collections C# includes the following generic collection classes in the System.Collections.Generic namespace. Generic Collections Description List<T> Generic List<T> contains elements of specified type. It grows automatically as you add elements in it. Dictionary<TKey,TValue> Dictionary<TKey,TValue> contains key-value pairs. SortedList<TKey,TValue> SortedList stores key and value pairs. It automatically adds the elements in ascending order of key by default. Queue<T> Queue<T> stores the values in FIFO style (First In First Out). It keeps the order in which the values were added. It provides an Enqueue() method to add values and a Dequeue() method to retrieve values from the collection. Stack<T> Stack<T> stores the values as LIFO (Last In First Out). It provides a Push() method to add a value and Pop() & Peek() methods to retrieve values. Hashset<T> Hashset<T> contains non-duplicate elements. It eliminates duplicate elements. 

Non Generic Collection :

Array list: it refers to the ordered collection of the objects that are indexed individually. You can use it as an alternative to the array. Using index you can easily add or remove the items off the list and it will resize itself automatically. It works well for dynamic memory allocation, adding or searching items in the list.

Hash tableif you want to access the item of the hash table then you can use the key-value to refer to the original assigned value to the variable. Each item in the hash table is stored as a key/value pair and the item is referenced with its key value.

Stack: it works on the concept of last-in and first-out collection of the objects. Whenever you add an item to the list it is called pushing and when you remove the item off the list it is called popping.

Sorted list: this collection class uses the combination of key and the index to access the item in a list.

Queuethis collection works on the concept of first-in and first-out collection of the object. Adding an item to the list is call enqueue and removing the item off the list is call deque.

BitArray: this collection class is used to represent the array in binary form (0 and 1). You can use this collection class when you do not know the number and the items can be accessed by using integer indexes that start from zero.

65.       Explain file handling in C#.

AnswerWhenever you open a file for reading or writing it becomes a stream which is a sequence of bytes travelling from source to destination. The two commonly used streams are input and output. The included namespace is system.IO that includes many classes for file handling. The stream is an abstract class that is the parent class for the file handling process. The file is a static class with many static methods to handle file operation.

Below are the used classes:

The following table describes some commonly used classes in the System.IO namespace.

Class NameDescription
FileStreamThis stream read from and write to any location within a file
BinaryReaderread primitive data types from a binary stream
DirectoryInfoperform operations on directories
FileInfoperform operations on files
BinaryWriterwrite primitive data types in binary format
StreamReaderto read characters from a byte Stream
StreamWriterwrite characters to a stream.
StringReaderread from a string buffer
StringWriterwrite into a string buffer

66.     Define interface class in C#? Explain with an example.

AnswerAn interface class is completely an abstract class that contains abstract methods and properties. By default, the members of the interface class are abstract and public with no fields defined. If you want to access the interface methods then the interface must be implemented by another class using ‘:’ symbol. If you want to define the body of the methods that can only be implemented in the implementing class.

C# abstract class explained

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. In other words, abstract classes are either partially implemented or not implemented at all. You can have functionality in your abstract class—the methods in an abstract class can be both abstract and concrete. An abstract class can have constructors—this is one major difference between an abstract class and an interface. You can take advantage of abstract classes to design components and specify some level of common functionality that must be implemented by derived classes.

C# interface explained

An interface is basically a contract—it doesn’t have any implementation. An interface can contain only method declarations; it cannot contain method definitions. Nor can you have any member data in an interface. Whereas an abstract class may contain method definitions, fields, and constructors, an interface may only have declarations of events, methods, and properties. Methods declared in an interface must be implemented by the classes that implement the interface. Note that a class can implement more than one interface but extend only one class. The class that implements the interface should implement all its members. Like an abstract class, an interface cannot be instantiated.

For example:

// Interface
Interface IAnimal {
  void Sound(); // interface method (without body)
class Pig : IAnimal   // Pig class "implements" the IAnimal interface
  public void Sound()
Console.WriteLine("The pig says: wee wee"); // The body of Sound() is provided her
class Program
  static void Main(string[] args)
 Pig myPig = new Pig();  // Create a Pig object

67.     How will you differentiate between a Class and a Struct?

Answer: Although both class and structure are user-defined data types, they are different in several fundamental ways. A class is a reference type and stores on the heap. Struct, on the other hand, is a value type and is, therefore, stored on the stack. While the structure doesn’t support inheritance and polymorphism, the class provides support for both. A class can be of an abstract type, but a structure can’t. All members of a class are private by default, while members of a struct are public by default. Another distinction between class and struct is based on memory management. The former supports garbage collection while the latter doesn’t.

  • Compare Virtual methods and Abstract methods.

Answer: Any Virtual method must have a default implementation, and it can be overridden in the derived class using the override keyword. On the contrary, an Abstract method doesn’t have an implementation, and it resides in the abstract class. The derived class must implement the abstract method. Though not necessary, we can use an override keyword here.

69.     What are Namespaces in C#?

Answer: Use of namespaces is for organizing large code projects. The most widely used namespace in C# is System. Namespaces are created using the namespace keyword. It is possible to use one namespace in another, known as Nested Namespaces.

70.     What are I/O classes in C#? Define some of the most commonly used ones.

Answer: The System.IO namespace in C# consists of several classes used for performing various file operations, such as creation, deletion, closing, and opening. Some of the most frequently used I/O classes in C# are:

  • File – Manipulates a file
  • Path – Performs operations related to some path information
  • StreamReader – Reads characters from a stream
  • StreamWriter – Writes characters to a stream
  • StringReader – Reads a string buffer
  • StringWriter – Writes a string buffer

What do you understand by regular expressions in C#? Write a program that searches a string using regular expressions.

Answer: Regular expression is a template for matching a set of input. It can consist of constructs, character literals, and operators. Regex is used for string parsing, as well as replacing the character string. Following code searches a string “C#” against the set of inputs from the languages array using Regex:

static void Main(strong[] args)
string[] languages = {“C#”, “Python”, “Java”};
foreach(string s in languages)
Console.WriteLine(“Match found”);

71.     Explain Reflection in C#.

Answer: The ability of code to access the metadata of the assembly during runtime is called Reflection. A program reflects upon itself and uses the metadata to:

  • Inform the user, or
  • Modify the behaviour

The system contains all classes and methods that manage the information of all the loaded types and methods. Reflection namespace. Implementation of reflection is in 2 steps:

  • Get the type of the object, then
  • Use the type to identify members, such as properties and methods

72.       Name some of the most common places to look for a Deadlock in C#.

Answer: For recognizing deadlocks, one should look for threads that get stuck on one of the following:

  • .Result, .GetAwaiter().GetResult(), WaitAll(), and WaitAny() (When working with Tasks)
  • Dispatcher.Invoke() (When working in WPF)
  • Join() (When working with Threads)
  • lock statements (In all cases)
  • WaitOne() methods (When working with AutoResetEvent/EventWaitHandle/Mutex/Semaphore)

73.     Define Serialization and its various types in C#.

Answer: The process of converting some code into its binary format is known as Serialization in C#. Doing so allows the code to be stored easily and written to a disk or some other storage device. We use Serialization when there is a strict need for not losing the original form of the code. A class marked with the attribute [Serializable] gets converted to its binary form. A stream that contains the serialized object and the System.Runtime.Serialization namespace can have classes for serialization. Serialization in C# is of three types:

  • Binary Serialization – Faster and demands less space; it converts any code into its binary form. Serialize and restore public and non-public properties.
  • SOAP – It produces a complete SOAP compliant envelope that is usable by any system capable of understanding SOAP. The classes about this type of serialization reside in System.Runtime.Serialization.
  • XML Serialization – Serializes all the public properties to the XML document. In addition to being easy to read, the XML document manipulated in several formats. The classes in this type of serialization reside in System.sml.Serialization.

Note: Retrieving the C# code back from the binary form is known as Deserialization.

74.     Give a brief explanation of Thread Pooling in C#.

Answer: A collection of threads, termed as a Thread Pool in C#. Such threads are for performing tasks without disturbing the execution of the primary thread. After a thread belonging to a thread pool completes execution, it returns to the thread pool. Classes that manage the thread in the thread pool, and its operations, are contained in the System.Threading.ThreadPool namespace.

75.       Is it possible to use this keyword within a static method in C#?

Answer: A special type of reference variable, this keyword is implicitly defined with each non-static method and constructor as the first parameter of the type class, which defines it. Static methods don’t belong to a particular instance. Instead, they exist without creating an instance of the class and calls with the name of the class. Because this keyword returns a reference to the current instance of the class containing it, it can’t be used in a static method. Although we can’t use this keyword within a static method, we can use it in the function parameters of Extension Methods.

2 thoughts on “C# Fundamental Part 2”

Leave a Comment

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

https://www.cooljerseyedge.com, https://www.collegeshopfan.com, https://www.kcchiefsgearusa.com, https://www.dlionsgearusa.com, https://www.bravensgearusa.com, https://www.cbengalsgearusa.com, https://www.gbpackersgearusa.com, https://www.htexansgearusa.com, https://www.laramsgearusa.com, Josh Allen Wyoming Jersey, https://www.dcowboysgearusa.com, https://www.mdolphinsgearusa.com, https://www.aliexfanshop.com, https://www.bestplayershop.com, https://www.collegeedgeshop.com, https://www.giantsonlinefans.com