1. What is the difference between string and StringBuilder in c#?
StringBuilder and string both use to store string value but both have many differences on the bases of instance creation and also
for performance:
String:
String is an immutable object. Immutable like when we create string object in code so we cannot modify or change that object in any operations like insert new value, replace or append any value with existing value in string object, when we have to do some operations to change string simply it will dispose the old value of string object and it will create new instance in memory for hold the new value in string object like:
StringBuilder:
System.Text.Stringbuilder is mutable object which also hold the string value, mutable means once we create a System.Text.Stringbuilder object we can use this object for any operation like insert value in existing string with insert functions also replace or append without creating new instance of System.Text.Stringbuilder for every time so it’s use the previous object so it’s work fast as compare than System.String. Let’s have an example to understand System.Text.Stringbuilder like:
2. What are partial classes?
A partial class is only use to splits the definition of a class in two or more classes in a same source code file or more than one source files. You can create a class definition in multiple files but it will be compiled as one class at run time and also when you’ll create an instance of this class so you can access all the methods from all source file with a same object.
Partial Classes can be create in the same namespace it’s doesn’t allowed to create a partial class in different namespace. So use “partial” keyword with all the class name which you want to bind together with the same name of class in same namespace, let’s have an example:
3. What is IEnumerable<> in c#?
IEnumerable is the parent interface for all non-generic collections in System.Collections namespace like ArrayList, HastTable etc. that can be enumerated. For the generic version of this interface as IEnumerable<T> which a parent interface of all generic collections class in System.Collections.Generic namespace like List<> and more.
In System.Collections.Generic.IEnumerable<T> have only a single method which is GetEnumerator() that returns an IEnumerator. IEnumerator provides the power to iterate through the collection by exposing a Current property and Move Next and Reset methods, if we doesn’t have this interface as a parent so we can’t use iteration by foreach loop or can’t use that class object in our LINQ query.
============================================
sql
difference between stored procedure and function
The difference between SP and UDF is listed below:
4. C# difference between Readonly and constant
Const
Const is nothing but "constant", a variable of which the value is constant but at compile time. And it's mandatory to assign a value to it. By default a const is static and we cannot change the value of a const variable throughout the entire program.
Readonly
Readonly is the keyword whose value we can change during runtime or we can assign it at run time but only through the non-static constructor. Not even a method
5. What is the difference between ref and out keywords?
In C Sharp (C#) we can have three types of parameters in a function. The parameters can be in parameter (which is not returned back to the caller of the function), out parameter and ref parameter. We have lots of differences in both of them.

6. Can “this” be used within a static method?
We can't use this in static method because keyword 'this' returns a reference to the current instance of the class containing it. Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class and call with the name of a class not by instance so we can’t use this keyword in the body of static Methods, but in case of Extension Methods we can use it the functions parameters. Let’s have a look on “this” keyword.
The "this" keyword is a special type of reference variable that is implicitly defined within each constructor and non-static method as a first parameter of the type class in which it is defined. For example, consider the following class written in C#.
7. Define Property in C#.net?
Properties are members that provide a flexible mechanism to read, write or compute the values of private fields, in other words by the property we can access private fields. In other words we can say that a property is a return type function/method with one parameter or without a parameter. These are always public data members. It uses methods to access and assign values to private fields called accessors.
Now question is what are accessors?
The get and set portions or blocks of a property are called accessors. These are useful to restrict the accessibility of a property, the set accessor specifies that we can assign a value to a private field in a property and without the set accessor property it is like a read-only field. By the get accessor we can access the value of the private field, in other words it returns a single value. A Get accessor specifies that we can access the value of a field publically.
We have the three types of properties
Now question is what are accessors?
The get and set portions or blocks of a property are called accessors. These are useful to restrict the accessibility of a property, the set accessor specifies that we can assign a value to a private field in a property and without the set accessor property it is like a read-only field. By the get accessor we can access the value of the private field, in other words it returns a single value. A Get accessor specifies that we can access the value of a field publically.
We have the three types of properties
- Read/Write.
- ReadOnly.
- WriteOnly
8. What is extension method in c# and how to use them?
Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type.
How to use extension methods?
An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.
Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.
Like: suppose we have a class like bellow:
How to use extension methods?
An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.
Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.
Like: suppose we have a class like bellow:
- public class Class1 {
- public string Display() {
- return ("I m in Display");
- }
- public string Print() {
- return ("I m in Print");
- }
- }
Now we need to extend the definition of this class so m going to create a static class to create an extinction method like:
Here I just create a method that name is NewMethod with a parameter using this to define which type of data I need to be extend, now let’s see how to use this function.
- public static class XX {
- public static void NewMethod(this Class1 ob) {
- Console.WriteLine("Hello I m extended method");
- }
- }

- class Program {
- static void Main(string[] args) {
- Class1 ob = new Class1();
- ob.Display();
- ob.Print();
- ob.NewMethod();
- Console.ReadKey();
- }
- }

9. What is the difference between dispose and finalize methods in c#?
finalizer and dispose both are used for same task like to free unmanaged resources but have some differences see.
Finalize:
Finalize:
- Finalize used to free unmanaged resources those are not in use like files, database connections in application domain and more, held by an object before that object is destroyed.
- In the Internal process it is called by Garbage Collector and can’t called manual by user code or any service.
- Finalize belongs to System.Object class.
- Implement it when you have unmanaged resources in your code, and make sure that these resources are freed when the Garbage collection happens.
Dispose:
- Dispose is also used to free unmanaged resources those are not in use like files, database connections in Application domain at any time.
- Dispose explicitly it is called by manual user code.
- If we need to dispose method so must implement that class by IDisposable interface.
- It belongs to IDisposable interface.
- Implement this when you are writing a custom class that will be used by other users.
10. What is the difference between string and StringBuilder in c#?
StringBuilder and string both use to store string value but both have many differences on the bases of instance creation and also for performance:
String:
String is an immutable object. Immutable like when we create string object in code so we cannot modify or change that object in any operations like insert new value, replace or append any value with existing value in string object, when we have to do some operations to change string simply it will dispose the old value of string object and it will create new instance in memory for hold the new value in string object like:
String:
String is an immutable object. Immutable like when we create string object in code so we cannot modify or change that object in any operations like insert new value, replace or append any value with existing value in string object, when we have to do some operations to change string simply it will dispose the old value of string object and it will create new instance in memory for hold the new value in string object like:

StringBuilder:System.Text.Stringbuilder is mutable object which also hold the string value, mutable means once we create a System.Text.Stringbuilder object we can use this object for any operation like insert value in existing string with insert functions also replace or append without creating new instance of System.Text.Stringbuilder for every time so it’s use the previous object so it’s work fast as compare than System.String. Let’s have an example to understand System.Text.Stringbuilder like:

Note:
- StringBuilder is a mutable object.
- Performance wise StringBuilder is very fast because it will use same instance of StringBuilder object to perform any operation like insert value in existing string.
- StringBuilder belongs to System.Text.Stringbuilder namespace.
11. What is delegates in C# and uses of delegates?
C# delegates are same as pointers to functions, in C or C++. A delegate Object is a reference type variable that use to holds the reference to a method. The reference can be changed at runtime which is hold by an object of delegate, a delegate object can hold many functions reference which is also known as Invocation List that refers functions in a sequence FIFO, we can new functions ref in this list at run time by += operator and can remove by -= operator.
Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.
Let’s see how to use Delegate with Example:
Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from the System.Delegate class.
Let’s see how to use Delegate with Example:

12. What is sealed class in c#?
Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as a sealed class, the class cannot be inherited.
In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET the Not Inheritable keyword serves the purpose of sealed. If a class is derived from a sealed class then the compiler throws an error.
If you have ever noticed, structs are sealed. You cannot derive a class from a struct.
The following class definition defines a sealed class in C#:
In C#, the sealed modifier is used to define a class as sealed. In Visual Basic .NET the Not Inheritable keyword serves the purpose of sealed. If a class is derived from a sealed class then the compiler throws an error.
If you have ever noticed, structs are sealed. You cannot derive a class from a struct.
The following class definition defines a sealed class in C#:
- // Sealed class
- sealed class SealedClass
- {
- }
13. What are partial classes?
A partial class is only use to splits the definition of a class in two or more classes in a same source code file or more than one source files. You can create a class definition in multiple files but it will be compiled as one class at run time and also when you’ll create an instance of this class so you can access all the methods from all source file with a same object.
Partial Classes can be create in the same namespace it’s doesn’t allowed to create a partial class in different namespace. So use “partial” keyword with all the class name which you want to bind together with the same name of class in same namespace, let’s have an example:
Partial Classes can be create in the same namespace it’s doesn’t allowed to create a partial class in different namespace. So use “partial” keyword with all the class name which you want to bind together with the same name of class in same namespace, let’s have an example:

14. What is boxing and unboxing?
Boxing and Unboxing both using for type converting but have some difference:
Boxing:
Boxing is the process of converting a value type data type to the object or to any interface data type which is implemented by this value type. When the CLR boxes a value means when CLR converting a value type to Object Type, it wraps the value inside a System.Object and stores it on the heap area in application domain.
Example:
Boxing:
Boxing is the process of converting a value type data type to the object or to any interface data type which is implemented by this value type. When the CLR boxes a value means when CLR converting a value type to Object Type, it wraps the value inside a System.Object and stores it on the heap area in application domain.
Example:

Unboxing:
Unboxing is also a process which is use to extracts the value type from the object or any implemented interface type. Boxing may be done implicit but unboxing have to be explicit by code.
Example:
Unboxing is also a process which is use to extracts the value type from the object or any implemented interface type. Boxing may be done implicit but unboxing have to be explicit by code.
Example:

The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object.
15. What is IEnumerable<> in c#?
IEnumerable is the parent interface for all non-generic collections in System.Collections namespace like ArrayList, HastTable etc. that can be enumerated. For the generic version of this interface as IEnumerable<T> which a parent interface of all generic collections class in System.Collections.Generic namespace like List<> and more.
In System.Collections.Generic.IEnumerable<T> have only a single method which is GetEnumerator() that returns an IEnumerator. IEnumerator provides the power to iterate through the collection by exposing a Current property and Move Next and Reset methods, if we doesn’t have this interface as a parent so we can’t use iteration by foreach loop or can’t use that class object in our LINQ query.
In System.Collections.Generic.IEnumerable<T> have only a single method which is GetEnumerator() that returns an IEnumerator. IEnumerator provides the power to iterate through the collection by exposing a Current property and Move Next and Reset methods, if we doesn’t have this interface as a parent so we can’t use iteration by foreach loop or can’t use that class object in our LINQ query.

16. What is difference between late binding and early binding in c#?
Early Binding and Late Binding concepts belongs to polymorphism so let’s see first about polymorphism:
Polymorphism is an ability to take more than one form of a function means with a same name we can write multiple functions code in a same class or any derived class.
Polymorphism we have 2 different types to achieve that:
Run time polymorphism also known as late binding, in Run Time polymorphism or Late Binding we can do use same method names with same signatures means same type or same number of parameters but not in same class because compiler doesn’t allowed that at compile time so we can use in derived class that bind at run time when a child class or derived class object will instantiated that’s way we says that Late Binding. For that we have to create my parent class functions as partial and in driver or child class as override functions with override keyword.
Like as following example:
Indexer allows classes to be used in more intuitive manner. C# introduces a new concept known as Indexers which are used for treating an object as an array. The indexers are usually known as smart arrays in C#. They are not essential part of object-oriented programming.
An indexer, also called an indexed property, is a class property that allows you to access a member variable of a class using the features of an array.
Defining an indexer allows you to create classes that act like virtual arrays. Instances of that class can be accessed using the [] array access operator.
Creating an Indexer
In the above code:
<modifier>
can be private, public, protected or internal.
<return type>
can be any valid C# types.
Answer
Delegate can invoke only one method reference has been encapsulated into the delegate.it is possible for certain delegate to hold and invoke multiple methods such delegate called multicast delegates.multicast delegates also know as combinable delegates, must satisfy the following conditions:
"is" operator
In the C# language, we use the "is" operator to check the object type. If the two objects are of the same type, it returns true and false if not.
Let's understand the preceding from a small program.
We defined the following two classes:
Now, let's try to check the preceding types as:
We declared an object of Speaker as in the following:
In the preceding, we are just checking the matching type. Yes, our speaker is an object of Speaker type.
So, the results as true.
But, here we get false:
Because our our speaker is not an object of Author type.
"as" operator:
Let's understand the preceding with a small snippet as in the following:
We have a method that accepts dynamic objects and returns the object name property if the object is of the Author type.
Here, we declared two objects:
The following returns the "Name" property:
It returns an empty string:
A nullable Type is a data type is that contain the defined data type or the value of null.
You should note here that here variable datatype has been given and then only it can be used.
This nullable type concept is not comaptible with "var".
I will explain this with syntax in next section.
Declaration:
As discussed in previous section "var" is not compatible with this Nullable Type.
So we will have Compile Time error if we are declaring something like: -
though following syntax is completely fine :-
Method overloading is a way to achieve compile time Polymorphism where we can use a method with the same name but different signature, Method overloading is done at compile time and we have multiple way to do that but in all way method name should be same.
Note:
If we have a method that have two parameter object type and have a same name method with two integer parameter so when we call that method with int value so it’ll call that method have integer parameter instead of object type parameters method.
Object Pooling is something that tries to keep a pool of objects in memory to be re-used later and hence it will reduce the load of object creation to a great extent. This article will try to explain this in detail. The example is for an Employee object, but you can make it general by using Object base class.
What does it mean?
Object Pool is nothing but a container of objects that are ready for use. Whenever there is a request for a new object, the pool manager will take the request and it will be served by allocating an object from the pool.
How it works?
We are going to use Factory pattern for this purpose. We will have a factory method, which will take care about the creation of objects. Whenever there is a request for a new object, the factory method will look into the object pool (we use Queue object). If there is any object available within the allowed limit, it will return the object (value object), otherwise a new object will be created and give you back.
Generics allow you to delay the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.
You write the specifications for the class or the method, with substitute parameters for data types. When the compiler encounters a constructor for the class or a function call for the method, it generates code to handle the specific data type.
Polymorphism is an ability to take more than one form of a function means with a same name we can write multiple functions code in a same class or any derived class.
Polymorphism we have 2 different types to achieve that:
- Compile Time also known as Early Binding or Overloading.
- Run Time also known as Late Binding or Overriding.
Compile Time Polymorphism or Early Binding:In Compile time polymorphism or Early Binding we will use multiple methods with same name but different type of parameter or may be the number or parameter because of this we can perform different-different tasks with same method name in the same class which is also known as Method overloading.
See how we can do that by the following example:
See how we can do that by the following example:

Run Time Polymorphism or Late Binding:
Run time polymorphism also known as late binding, in Run Time polymorphism or Late Binding we can do use same method names with same signatures means same type or same number of parameters but not in same class because compiler doesn’t allowed that at compile time so we can use in derived class that bind at run time when a child class or derived class object will instantiated that’s way we says that Late Binding. For that we have to create my parent class functions as partial and in driver or child class as override functions with override keyword.
Like as following example:

17. What are the differences between IEnumerable and IQueryable?
Before the differences learn what is IEnumerable and IQueryable.
IEnumerable:
Is the parent interface for all non-generic collections in System.Collections namespace like ArrayList, HastTable etc. that can be enumerated. For the generic version of this interface as IEnumerable<T> which a parent interface of all generic collections class in System.Collections.Generic namespace like List<> and more.
IQueryable:
As per MSDN IQueryable interface is intended for implementation by query providers. It is only supposed to be implemented by providers that also implement IQueryable<T>. If the provider does not also implement IQueryable<T>, the standard query operators cannot be used on the provider's data source.
The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed. The definition of "executing an expression tree" is specific to a query provider. For example, it may involve translating the expression tree to an appropriate query language for the underlying data source. Queries that do not return enumerable results are executed when the Execute method is called.
IEnumerable:
Is the parent interface for all non-generic collections in System.Collections namespace like ArrayList, HastTable etc. that can be enumerated. For the generic version of this interface as IEnumerable<T> which a parent interface of all generic collections class in System.Collections.Generic namespace like List<> and more.
IQueryable:
As per MSDN IQueryable interface is intended for implementation by query providers. It is only supposed to be implemented by providers that also implement IQueryable<T>. If the provider does not also implement IQueryable<T>, the standard query operators cannot be used on the provider's data source.
The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed. The definition of "executing an expression tree" is specific to a query provider. For example, it may involve translating the expression tree to an appropriate query language for the underlying data source. Queries that do not return enumerable results are executed when the Execute method is called.

18. What happens if the inherited interfaces have conflicting method names?
If we implement multipole interface in the same class with conflict method name so we don’t need to define all or in other words we can say if we have conflict methods in same class so we can’t implement their body independently in the same class coz of same name and same signature so we have to use interface name before method name to remove this method confiscation let’s see an example:
Now see how to use those in a class:
Output:
- interface testInterface1 {
- void Show();
- }
- interface testInterface2 {
- void Show();
- }
- class Abc: testInterface1,
- testInterface2 {
- void testInterface1.Show() {
- Console.WriteLine("For testInterface1 !!");
- }
- void testInterface2.Show() {
- Console.WriteLine("For testInterface2 !!");
- }
- }
- class Program {
- static void Main(string[] args) {
- testInterface1 obj1 = new Abc();
- testInterface1 obj2 = new Abc();
- obj1.Show();
- obj2.Show();
- Console.ReadLine();
- }
- }

19. What are the Arrays in C#.Net?
Arrays are powerful data structures for solving many programming problems. You saw during the creation of variables of many types that they have one thing in common, they hold information about a single item, for instance an integer, float and string type and so on. So what is the solution if you need to manipulate sets of items? One solution would be to create a variable for each item in the set but again this leads to a different problem. How many variables do you need?
So in this situation Arrays provide mechanisms that solves problem posed by these questions. An array is a collection of related items, either value or reference type. In C# arrays are immutable such that the number of dimensions and size of the array are fixed.
Arrays Overview
An array contains zero or more items called elements. An array is an unordered sequence of elements. All the elements in an array are of the same type (unlike fields in a class that can be of different types). The elements of an array accessed using an integer index that always starts from zero. C# supports single-dimensional (vectors), multidimensional and jagged arrays.
Elements are identified by indexes relative to the beginning of the arrays. An index is also commonly called indices or subscripts and are placed inside the indexing operator ([]). Access to array elements is by their index value that ranges from 0 to (length-1).
Array Properties
Method creates a shallow copy of an array. A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to.
CopyTo:The Copy static method of the Array class copies a section of an array to another array. The CopyTo method copies all the elements of an array to another one-dimension array. The code listed in Listing 9 copies contents of an integer array to an array of object types.
So in this situation Arrays provide mechanisms that solves problem posed by these questions. An array is a collection of related items, either value or reference type. In C# arrays are immutable such that the number of dimensions and size of the array are fixed.
Arrays Overview
An array contains zero or more items called elements. An array is an unordered sequence of elements. All the elements in an array are of the same type (unlike fields in a class that can be of different types). The elements of an array accessed using an integer index that always starts from zero. C# supports single-dimensional (vectors), multidimensional and jagged arrays.
Elements are identified by indexes relative to the beginning of the arrays. An index is also commonly called indices or subscripts and are placed inside the indexing operator ([]). Access to array elements is by their index value that ranges from 0 to (length-1).
Array Properties
- The length cannot be changed once created.
- Elements are initialized to default values.
- Arrays are reference types and are instances of System.Array.
- Their number of dimensions or ranks can be determined by the Rank property.
- An array length can be determined by the GetLength() method or Length property.
20. What is the Constructor Chaining in C#?
Constructor chaining is a way to connect two or more classes in a relationship as Inheritance, in Constructor Chaining every child class constructor is mapped to parent class Constructor implicitly by base keyword so when you create an instance of child class to it’ll call parent’s class Constructor without it inheritance is not possible.
21. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
Clone:
Method creates a shallow copy of an array. A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to.
CopyTo:The Copy static method of the Array class copies a section of an array to another array. The CopyTo method copies all the elements of an array to another one-dimension array. The code listed in Listing 9 copies contents of an integer array to an array of object types.
22. Can Multiple Catch Blocks executed in c#?
we can use multiple Catches block with every try but when any Exceptions is throw by debugger so every catches match this exception type with their signature and catch the exception by any single catch block so that means we can use multiple catches blocks but only one can executed at once like:
- using System;
- class MyClient {
- public static void Main() {
- int x = 0;
- int div = 0;
- try {
- div = 100 / x;
- Console.WriteLine("Not executed line");
- } catch (DivideByZeroException de) {
- Console.WriteLine("DivideByZeroException");
- } catch (Exception ee) {
- Console.WriteLine("Exception");
- } finally {
- Console.WriteLine("Finally Block");
- }
- Console.WriteLine("Result is {0}", div);
- }
- }
23. What is Singleton Design Patterns and How to implement in C#?
What is Singleton Design Pattern?
- Ensures a class has only one instance and provides a global point of access to it.
- A singleton is a class that only allows a single instance of itself to be created, and usually gives simple access to that instance.
- Most commonly, singletons don't allow any parameters to be specified when creating the instance, since a second request of an instance with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter then the factory pattern is more appropriate.)
- There are various ways to implement the Singleton Pattern in C#. The following are the common characteristics of a Singleton Pattern.
• A single constructor, that is private and parameterless.
• The class is sealed.
• A static variable that holds a reference to the single created instance, if any.
• A public static means of getting the reference to the single created instance, creating one if necessary.
This is the example how to write the code with Singleton:
- namespace Singleton {
- class Program {
- static void Main(string[] args) {
- Calculate.Instance.ValueOne = 10.5;
- Calculate.Instance.ValueTwo = 5.5;
- Console.WriteLine("Addition : " + Calculate.Instance.Addition());
- Console.WriteLine("Subtraction : " + Calculate.Instance.Subtraction());
- Console.WriteLine("Multiplication : " + Calculate.Instance.Multiplication());
- Console.WriteLine("Division : " + Calculate.Instance.Division());
- Console.WriteLine("\n----------------------\n");
- Calculate.Instance.ValueTwo = 10.5;
- Console.WriteLine("Addition : " + Calculate.Instance.Addition());
- Console.WriteLine("Subtraction : " + Calculate.Instance.Subtraction());
- Console.WriteLine("Multiplication : " + Calculate.Instance.Multiplication());
- Console.WriteLine("Division : " + Calculate.Instance.Division());
- Console.ReadLine();
- }
- }
- public sealed class Calculate {
- private Calculate() {}
- private static Calculate instance = null;
- public static Calculate Instance {
- get {
- if (instance == null) {
- instance = new Calculate();
- }
- return instance;
- }
- }
- public double ValueOne {
- get;
- set;
- }
- public double ValueTwo {
- get;
- set;
- }
- public double Addition() {
- return ValueOne + ValueTwo;
- }
- public double Subtraction() {
- return ValueOne - ValueTwo;
- }
- public double Multiplication() {
- return ValueOne * ValueTwo;
- }
- public double Division() {
- return ValueOne / ValueTwo;
- }
- }
- }
24. Difference between Throw Exception and Throw Clause
The basic difference is that the Throw exception overwrites the stack trace and this makes it hard to find the original code line number that has thrown the exception.
Throw basically retains the stack information and adds to the stack information in the exception that it is thrown.
Let us see what it means rather speaking so many words to better understand the differences. I am using a console application to easily test and see how the usage of the two differ in their functionality.
Now run the code by pressing the F5 key of the keyboard and see what happens. It returns an exception and look at the stack trace:
Throw basically retains the stack information and adds to the stack information in the exception that it is thrown.
Let us see what it means rather speaking so many words to better understand the differences. I am using a console application to easily test and see how the usage of the two differ in their functionality.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace TestingThrowExceptions {
- class Program {
- public void ExceptionMethod() {
- throw new Exception("Original Exception occurred in ExceptionMethod");
- }
- static void Main(string[] args) {
- Program p = new Program();
- try {
- p.ExceptionMethod();
- } catch (Exception ex) {
- throw ex;
- }
- }
- }
- }
25. What are Indexer in C# .Net?
Indexer allows classes to be used in more intuitive manner. C# introduces a new concept known as Indexers which are used for treating an object as an array. The indexers are usually known as smart arrays in C#. They are not essential part of object-oriented programming.
An indexer, also called an indexed property, is a class property that allows you to access a member variable of a class using the features of an array.
Defining an indexer allows you to create classes that act like virtual arrays. Instances of that class can be accessed using the [] array access operator.
Creating an Indexer
- < modifier > <
- return type > this[argument list] {
- get {
- // your get block code
- }
- set {
- // your set block code
- }
- }
<modifier>
can be private, public, protected or internal.
<return type>
can be any valid C# types.
26. What is multicast delegate in c#?
Answer
Delegate can invoke only one method reference has been encapsulated into the delegate.it is possible for certain delegate to hold and invoke multiple methods such delegate called multicast delegates.multicast delegates also know as combinable delegates, must satisfy the following conditions:
- The return type of the delegate must be void. None of the parameters of the delegate type can be delegate type can be declared as output parameters using out keywords.
- Multicast delegate instance that created by combining two delegates, the invocation list is formed by concatenating the invocation list of two operand of the addition operation. Delegates are invoked in the order they are added.
Implement Multicast Delegates Example:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- delegate void MDelegate();
- class DM {
- static public void Display() {
- Console.WriteLine("Meerut");
- }
- static public void print() {
- Console.WriteLine("Roorkee");
- }
- }
- class MTest {
- public static void Main() {
- MDelegate m1 = new MDelegate(DM.Display);
- MDelegate m2 = new MDelegate(DM.print);
- MDelegate m3 = m1 + m2;
- MDelegate m4 = m2 + m1;
- MDelegate m5 = m3 - m2;
- m3();
- m4();
- m5();
- }
- }
27. Difference between Equality Operator (==) and Equals() Method in C#
Both the == Operator and the Equals() method are used to compare two value type data items or reference type data items. The Equality Operator (==) is the comparison operator and the Equals() method compares the contents of a string. The == Operator compares the reference identity while the Equals() method compares only contents. Let’s see with some examples.
In this example we assigned a string variable to another variable. A string is a reference type and in the following example, a string variable is assigned to another string variable so they are referring to the same identity in the heap and both have the same content so you get True output for both the == Operator and the Equals() method.
In this example we assigned a string variable to another variable. A string is a reference type and in the following example, a string variable is assigned to another string variable so they are referring to the same identity in the heap and both have the same content so you get True output for both the == Operator and the Equals() method.
- using System;
- namespace ComparisionExample {
- class Program {
- static void Main(string[] args) {
- string name = "sandeep";
- string myName = name;
- Console.WriteLine("== operator result is {0}", name == myName);
- Console.WriteLine("Equals method result is {0}", name.Equals(myName));
- Console.ReadKey();
- }
- }
- }
28. Difference between is and as operator in C#
"is" operator
In the C# language, we use the "is" operator to check the object type. If the two objects are of the same type, it returns true and false if not.
Let's understand the preceding from a small program.
We defined the following two classes:
- class Speaker {
- public string Name {
- get;
- set;
- }
- }
- class Author {
- public string Name {
- get;
- set;
- }
- }
- var speaker = new Speaker { Name="Gaurav Kumar Arora"};
- var isTrue = speaker is Speaker;
- Console.WriteLine("speaker is of Speaker type:{0}", isTrue);
But, here we get false:
- var author = new Author { Name = "Gaurav Kumar Arora" };
- var isTrue = speaker is Author;
- Console.WriteLine("speaker is of Author type:{0}", isTrue);
"as" operator:
The "as" operator behaves similar to the "is" operator. The only difference is it returns the object if both are compatible to that type else it returns null.
- public static string GetAuthorName(dynamic obj)
- {
- Author authorObj = obj as Author;
- return (authorObj != null) ? authorObj.Name : string.Empty;
- }
Here, we declared two objects:
- var speaker = new Speaker { Name="Gaurav Kumar Arora"};
- var author = new Author { Name = "Gaurav Kumar Arora" };
- var authorName = GetAuthorName(author);
- Console.WriteLine("Author name is:{0}", authorName);
- authorName = GetAuthorName(speaker);
- Console.WriteLine("Author name is:{0}", authorName);
29. How to use Nullable<> Types in .Net?
A nullable Type is a data type is that contain the defined data type or the value of null.
You should note here that here variable datatype has been given and then only it can be used.
This nullable type concept is not comaptible with "var".
I will explain this with syntax in next section.
Declaration:
Any DataType can be declared nullable type with the help of operator "?".
Example of the syntax is as Follows :-
- int? i = null;
So we will have Compile Time error if we are declaring something like: -
- var? i = null;
- var i = 4;
30. Different Ways of Method can be overloaded
Method overloading is a way to achieve compile time Polymorphism where we can use a method with the same name but different signature, Method overloading is done at compile time and we have multiple way to do that but in all way method name should be same.
- Number of parameter can be different.
- Types of parameter can be different.
- Order of parameters can be different.
Example:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Hello_Word {
- class overloding {
- public static void Main() {
- Console.WriteLine(volume(10));
- Console.WriteLine(volume(2.5F, 8));
- Console.WriteLine(volume(100L, 75, 15));
- Console.ReadLine();
- }
- static int volume(int x) {
- return (x * x * x);
- }
- static double volume(float r, int h) {
- return (3.14 * r * r * h);
- }
- static long volume(long l, int b, int h) {
- return (l * b * h);
- }
- }
- }
If we have a method that have two parameter object type and have a same name method with two integer parameter so when we call that method with int value so it’ll call that method have integer parameter instead of object type parameters method.
31. What is an Object Pool in .Net?
Object Pooling is something that tries to keep a pool of objects in memory to be re-used later and hence it will reduce the load of object creation to a great extent. This article will try to explain this in detail. The example is for an Employee object, but you can make it general by using Object base class.
What does it mean?
Object Pool is nothing but a container of objects that are ready for use. Whenever there is a request for a new object, the pool manager will take the request and it will be served by allocating an object from the pool.
How it works?
We are going to use Factory pattern for this purpose. We will have a factory method, which will take care about the creation of objects. Whenever there is a request for a new object, the factory method will look into the object pool (we use Queue object). If there is any object available within the allowed limit, it will return the object (value object), otherwise a new object will be created and give you back.
32. What are generics in c#.net?
Generics allow you to delay the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.
You write the specifications for the class or the method, with substitute parameters for data types. When the compiler encounters a constructor for the class or a function call for the method, it generates code to handle the specific data type.

Generic classes and methods combine reusability, type safety and efficiency in a way that their non-generic counterparts cannot. Generics are most frequently used with collections and the methods that operate on them. Version 2.0 of the .NET Framework class library provides a new namespace, System.Collections.Generic, that contains several new generic-based collection classes. It is recommended that all applications that target the .NET Framework 2.0 and later use the new generic collection classes instead of the older non-generic counterparts such as ArrayList.
Features of Generics
Generics is a technique that enriches your programs in the following ways:
Access modifiers are keywords used to specify the declared accessibility of a member or a type.
Why to use access modifiers?
Access modifiers are an integral part of object-oriented programming. They support the concept of encapsulation, which promotes the idea of hiding functionality. Access modifiers allow you to define who does or doesn't have access to certain features.
In C# there are 5 different types of Access Modifiers.
Serialization means saving the state of your object to secondary memory, such as a file.
Suppose you have a business layer where you have many classes to perform your business data.
Now suppose you want to test whether your business classes give the correct data out without verifying the result from the UI or from a database. Because it will take some time to process.
SO what you will you do my friend?
Here comes Serialization. You will serialize all your necessary business classes and save them into a text or XML file.
on your hard disk. So you can easily test your desired result by comparing your serialized saved data with.
your desired output data. You can say it is a little bit of autonomic unit testing performed by the developer.
There are three types of serialization:
The .Net Framework provides resource management for managed objects through the garbage collector - You do not have to explicitly allocate and release memory for managed objects. Clean-up operations for any unmanaged resources should performed in the destructor in C#. To allow the programmer to explicitly perform these clean-up activities, objects can provide a Dispose method that can be invoked when the object is no longer needed. The using statement in C# defines a boundary for the object outside of which, the object is automatically destroyed. The using statement is excited when the end of the "using" statement block or the execution exits the "using" statement block indirectly, for example - an exception is thrown. The "using" statement allows you to specify multiple resources in a single statement. The object could also be created outside the "using" statement. The objects specified within the using block must implement the IDisposable interface. The framework invokes the Dispose method of objects specified within the "using" statement when the block is exited.
A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays."
A special type of array is introduced in C#. A Jagged Array is an array of an array in which the length of each array index can differ.
Example:
In the above declaration the rows are fixed in size. But columns are not specified as they can vary.
Declaring and initializing jagged array.
The real usage of a thread is not about a single sequential thread, but rather using multiple threads in a single program. Multiple threads running at the same time and performing various tasks is referred as Multithreading. A thread is considered to be a lightweight process because it runs within the context of a program and takes advantage of resources allocated for that program.

A single-threaded process contains only one thread while a multithreaded process contains more than one thread for execution.
A Hashtable is a collection that stores (Keys, Values) pairs. Here, the Keys are used to find the storage location and is immutable and cannot have duplicate entries in the Hashtable. The .Net Framework has provided a Hash Table class that contains all the functionality required to implement a hash table without any additional development. The hash table is a general-purpose dictionary collection. Each item within the collection is a DictionaryEntry object with two properties: a key object and a value object. These are known as Key/Value. When items are added to a hash table, a hash code is generated automatically. This code is hidden from the developer. All access to the table's values is achieved using the key object for identification. As the items in the collection are sorted according to the hidden hash code, the items should be considered to be randomly ordered.
The Base Class libraries offers a Hashtable Class that is defined in the System.Collections namespace, so you don't have to code your own hash tables. It processes each key of the hash that you add every time and then uses the hash code to look up the element very quickly. The capacity of a hash table is the number of elements the hash table can hold. As elements are added to a hash table, the capacity is automatically increased as required through reallocation. It is an older .Net Framework type.
Declaring a Hashtable
The Hashtable class is generally found in the namespace called System.Collections. So to execute any of the examples, we have to add using System.Collections; to the source code. The declaration for the Hashtable is:
LINQ stands for Language Integrated Query. LINQ is a data querying methodology which provides querying capabilities to .NET languages with a syntax similar to a SQL query
LINQ has a great power of querying on any source of data. The data source could be collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface.
Advantages of LINQ
You can dynamically discover the set of interfaces supported by a given type using the System.Reflection namespace. This namespace contains numerous related types as follows:
Features of Generics
Generics is a technique that enriches your programs in the following ways:
- It helps you to maximize code reuse, type safety and performance.
- You can create generic collection classes. The .NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. You may use these generic collection classes instead of the collection classes in the System.Collections namespace.
- You can create your own generic interfaces, classes, methods, events and delegates.
- You may create generic classes constrained to enable access to methods on specific data types.
- You may get information on the types used in a generic data type at run-time using reflection.
33. Describe the accessibility modifiers in c#
Access modifiers are keywords used to specify the declared accessibility of a member or a type.
Why to use access modifiers?
Access modifiers are an integral part of object-oriented programming. They support the concept of encapsulation, which promotes the idea of hiding functionality. Access modifiers allow you to define who does or doesn't have access to certain features.
In C# there are 5 different types of Access Modifiers.

34. What is Virtual Method in C#?
A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as derived the class. It is used when a method's basic functionality is the same but sometimes more functionality is needed in the derived class. A virtual method is created in the base class that can be overridden in the derived class. We create a virtual method in the base class using the virtual keyword and that method is overridden in the derived class using the override keyword.
When a method is declared as a virtual method in a base class then that method can be defined in a base class and it is optional for the derived class to override that method. The overriding method also provides more than one form for a method. Hence it is also an example for polymorphism.
When a method is declared as a virtual method in a base class and that method has the same definition in a derived class then there is no need to override it in the derived class. But when a virtual method has a different definition in the base class and the derived class then there is a need to override it in the derived class.
When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.
Virtual Method
When a method is declared as a virtual method in a base class then that method can be defined in a base class and it is optional for the derived class to override that method. The overriding method also provides more than one form for a method. Hence it is also an example for polymorphism.
When a method is declared as a virtual method in a base class and that method has the same definition in a derived class then there is no need to override it in the derived class. But when a virtual method has a different definition in the base class and the derived class then there is a need to override it in the derived class.
When a virtual method is invoked, the run-time type of the object is checked for an overriding member. The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.
Virtual Method
- By default, methods are non-virtual. We can't override a non-virtual method.
- We can't use the virtual modifier with the static, abstract, private or override modifiers.
35. What are the Difference between Array and ArrayList in C#.Net?

36. What you understand by Value types and Reference types in C#.Net?
In C# data types can be of two types: Value Types and Reference Types. Value type variables contain their object (or data) directly. If we copy one value type variable to another then we are actually making a copy of the object for the second variable. Both of them will independently operate on their values, Value Type member will located into Stack and reference member will located in Heap always.
Let consider each case briefly.
Let consider each case briefly.
- Pure Value Type
Here I used a structure as a value type. It has an integer member. I created two instances of this structure. After wards I assigned second instance to the first one. Then I changed the state of second instance, but it hasn't effect the first one, as whole items are value type and assignments on those types will copy only values not references i.e. in a Value Type assignment, all instances have its own local copy of members. - Pure Reference Type
I created a class and added a "DataTable" as a Reference Type member for this class. Then I performed the assignments just like below. But the difference is that on changing the state of second instance, the state of first instance will automatically alter. So in a Reference Type assignment both Value and Reference will be assigned i.e. all instances will point to the single object. - Value Type With Reference TypeThis case and the last case to come are more interesting. I used a structure in this particular scenario also. But this time it includes a Reference Type(A Custom Class Object) Member besides a Value Type (An Integer) Member. When you performing the assignments, it seems like a swallow copy, as Value Type member of first instance won't effected, but the Reference Type member will alter according to the second instance. So in this particular scenario, assignment of Reference Type member produced a reference to a single object and assignment of Value Type member produced a local copy of that member.
- Reference Type With Value Type
Contrary to the above case, in this scenario, both Reference & Value Types will be effected. I.e. a Value Type member in a Reference Type will be shared among its instances.
37. What is Serialization?
Serialization means saving the state of your object to secondary memory, such as a file.
Suppose you have a business layer where you have many classes to perform your business data.
Now suppose you want to test whether your business classes give the correct data out without verifying the result from the UI or from a database. Because it will take some time to process.
SO what you will you do my friend?
Here comes Serialization. You will serialize all your necessary business classes and save them into a text or XML file.
on your hard disk. So you can easily test your desired result by comparing your serialized saved data with.
your desired output data. You can say it is a little bit of autonomic unit testing performed by the developer.
There are three types of serialization:
- Binary serialization (Save your object data into binary format).
- Soap Serialization (Save your object data into binary format; mainly used in network related communication).
- XmlSerialization (Save your object data into an XML file).
38. What is the use of Using statement in C#?
The .Net Framework provides resource management for managed objects through the garbage collector - You do not have to explicitly allocate and release memory for managed objects. Clean-up operations for any unmanaged resources should performed in the destructor in C#. To allow the programmer to explicitly perform these clean-up activities, objects can provide a Dispose method that can be invoked when the object is no longer needed. The using statement in C# defines a boundary for the object outside of which, the object is automatically destroyed. The using statement is excited when the end of the "using" statement block or the execution exits the "using" statement block indirectly, for example - an exception is thrown. The "using" statement allows you to specify multiple resources in a single statement. The object could also be created outside the "using" statement. The objects specified within the using block must implement the IDisposable interface. The framework invokes the Dispose method of objects specified within the "using" statement when the block is exited.
39. What is jagged array in C#.Net?
A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array of arrays."
A special type of array is introduced in C#. A Jagged Array is an array of an array in which the length of each array index can differ.
Example:
- int[][] jagArray = new int[5][];
Declaring and initializing jagged array.
- int[][] jaggedArray = new int[5][];
- jaggedArray[0] = new int[3];
- jaggedArray[1] = new int[5];
- jaggedArray[2] = new int[2];
- jaggedArray[3] = new int[8];
- jaggedArray[4] = new int[10];
- jaggedArray[0] = new int[] { 3, 5, 7, };
- jaggedArray[1] = new int[] { 1, 0, 2, 4, 6 };
- jaggedArray[2] = new int[] { 1, 6 };
- jaggedArray[3] = new int[] { 1, 0, 2, 4, 6, 45, 67, 78 };
- jaggedArray[4] = new int[] { 1, 0, 2, 4, 6, 34, 54, 67, 87, 78 };
40. What is Multithreading with .NET?
The real usage of a thread is not about a single sequential thread, but rather using multiple threads in a single program. Multiple threads running at the same time and performing various tasks is referred as Multithreading. A thread is considered to be a lightweight process because it runs within the context of a program and takes advantage of resources allocated for that program.

A single-threaded process contains only one thread while a multithreaded process contains more than one thread for execution.

System.Threading Namespace
Like many other features, in .NET, System.Threading is the namespace that provides various types to help in construction of multithreaded applications.
Like many other features, in .NET, System.Threading is the namespace that provides various types to help in construction of multithreaded applications.

41. Explain Anonymous type in C#?
Anonymous types allow us to create new type without defining them. This is way to defining read only properties into a single object without having to define type explicitly. Here Type is generating by the compiler and it is accessible only for the current block of code. The type of properties is also inferred by the compiler.
We can create anonymous types by using “new” keyword together with the object initializer.
Example
Anonymous Types with LINQ Example
Anonymous types are also used with the "Select" clause of LINQ query expression to return subset of properties.
Example
If Any object collection having properties called FirstName , LastName, DOB etc. and you want only FirstName and LastName after the Querying the data then.
We can create anonymous types by using “new” keyword together with the object initializer.
Example
- var anonymousData = new
- {
- ForeName = "Jignesh",
- SurName = "Trivedi"
- };
- Console.WriteLine("First Name : " + anonymousData.ForeName);
Anonymous types are also used with the "Select" clause of LINQ query expression to return subset of properties.
Example
If Any object collection having properties called FirstName , LastName, DOB etc. and you want only FirstName and LastName after the Querying the data then.
- class MyData {
- public string FirstName {
- get;
- set;
- }
- public string LastName {
- get;
- set;
- }
- public DateTime DOB {
- get;
- set;
- }
- public string MiddleName {
- get;
- set;
- }
- }
- static void Main(string[] args) {
- // Create Dummy Data to fill Collection.
- List < MyData > data = new List < MyData > ();
- data.Add(new MyData {
- FirstName = "Jignesh", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1990, 12, 30)
- });
- data.Add(new MyData {
- FirstName = "Tejas", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1995, 11, 6)
- });
- data.Add(new MyData {
- FirstName = "Rakesh", LastName = "Trivedi", MiddleName = "G", DOB = new DateTime(1993, 10, 8)
- });
- data.Add(new MyData {
- FirstName = "Amit", LastName = "Vyas", MiddleName = "P", DOB = newDateTime(1983, 6, 15)
- });
- data.Add(new MyData {
- FirstName = "Yash", LastName = "Pandiya", MiddleName = "K", DOB = newDateTime(1988, 7, 20)
- });
- }
- var anonymousData = from pl in data
- select new {
- pl.FirstName, pl.LastName
- };
- foreach(var m in anonymousData) {
- Console.WriteLine("Name : " + m.FirstName + " " + m.LastName);
- }
- }
42. Explain Hashtable in C#?
A Hashtable is a collection that stores (Keys, Values) pairs. Here, the Keys are used to find the storage location and is immutable and cannot have duplicate entries in the Hashtable. The .Net Framework has provided a Hash Table class that contains all the functionality required to implement a hash table without any additional development. The hash table is a general-purpose dictionary collection. Each item within the collection is a DictionaryEntry object with two properties: a key object and a value object. These are known as Key/Value. When items are added to a hash table, a hash code is generated automatically. This code is hidden from the developer. All access to the table's values is achieved using the key object for identification. As the items in the collection are sorted according to the hidden hash code, the items should be considered to be randomly ordered.
The Hashtable Collection
The Base Class libraries offers a Hashtable Class that is defined in the System.Collections namespace, so you don't have to code your own hash tables. It processes each key of the hash that you add every time and then uses the hash code to look up the element very quickly. The capacity of a hash table is the number of elements the hash table can hold. As elements are added to a hash table, the capacity is automatically increased as required through reallocation. It is an older .Net Framework type.
Declaring a Hashtable
The Hashtable class is generally found in the namespace called System.Collections. So to execute any of the examples, we have to add using System.Collections; to the source code. The declaration for the Hashtable is:
- Hashtable HT = new Hashtable ();
43. What is LINQ in C#?
LINQ stands for Language Integrated Query. LINQ is a data querying methodology which provides querying capabilities to .NET languages with a syntax similar to a SQL query
LINQ has a great power of querying on any source of data. The data source could be collections of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface.
Advantages of LINQ
- LINQ offers an object-based, language-integrated way to query over data no matter where that data came from. So through LINQ we can query database, XML as well as collections.
- Compile time syntax checking.
- It allows you to query collections like arrays, enumerable classes etc in the native language of your application, like VB or C# in much the same way as you would query a database using SQL.

44. What is File Handling in C#.Net?
The System.IO namespace provides four classes that allow you to manipulate individual files, as well as interact with a machine directory structure. The Directory and File directly extends System.Object and supports the creation, copying, moving and deletion of files using various static methods. They only contain static methods and are never instantiated. The FileInfo and DirecotryInfo types are derived from the abstract class FileSystemInfo type and they are typically, employed for obtaining the full details of a file or directory because their members tend to return strongly typed objects. They implement roughly the same public methods as a Directory and a File but they are stateful and the members of these classes are not static.

45. What is Reflection in C#.Net?
Reflection typically is the process of runtime type discovery to inspect metadata, CIL code, late binding and self-generating code. At run time by using reflection, we can access the same "type" information as displayed by the ildasm utility at design time. The reflection is analogous to reverse engineering in which we can break an existing *.exe or *.dll assembly to explore defined significant contents information, including methods, fields, events and properties.
You can dynamically discover the set of interfaces supported by a given type using the System.Reflection namespace. This namespace contains numerous related types as follows:

Reflection typically is used to dump out the loaded assemblies list, their reference to inspect methods, properties etcetera. Reflection is also used in the external disassembling tools such Reflector, Fxcop and NUnit because .NET tools don't need to parse the source code similar to C++.
Metadata Investigation
The following program depicts the process of reflection by creating a console based application. This program will display the details of the fields, methods, properties and interfaces for any type within the mscorlib.dll assembly. Before proceeeding, it is mandatory to import "System.Reflection".
Here, we are defining a number of static methods in the program class to enumerate fields, methods and interfaces in the specified type. The static method takes a single "System.Type" parameter and returns void.
The following program depicts the process of reflection by creating a console based application. This program will display the details of the fields, methods, properties and interfaces for any type within the mscorlib.dll assembly. Before proceeeding, it is mandatory to import "System.Reflection".
Here, we are defining a number of static methods in the program class to enumerate fields, methods and interfaces in the specified type. The static method takes a single "System.Type" parameter and returns void.
- static void FieldInvestigation(Type t) {
- Console.WriteLine("*********Fields*********");
- FieldInfo[] fld = t.GetFields();
- foreach(FieldInfo f in fld) {
- Console.WriteLine("-->{0}", f.Name);
- }
- }
- static void MethodInvestigation(Type t) {
- Console.WriteLine("*********Methods*********");
- MethodInfo[] mth = t.GetMethods();
- foreach(MethodInfo m in mth) {
- Console.WriteLine("-->{0}", m.Name);
- }
- }