MVC interview questions for 7 years experience – MVC Interview Questions in .NET

MVC interview questions for 7 years experience: We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

MVC Interview Questions

Question 1.
How will you specify what version of the framework your application is targeting?
Answer:
You can define “targetFramework” in Web.config file to specify the framework version. It is introduced in Asp.net 4.0

1 <?xml version-‘1.0M?>
2 <configuration>
3 <system.web>
4 compilation targetFramework=M4.0M />
5 </system.web>
6 </configuration>

Question 2.
What is the difference between Static class and Singleton instance?
Answer:
– In c# a static class cannot implement an interface. When a single instance class needs to implement an interface for some business reason or loC purposes, you can use the Singleton pattern without a static class.
– You can clone the object of Singleton but, you can not clone the static class object
– Singleton object stores in Heap but, static object stores in stack
– A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded

Question 3.
What is the difference between Unicode, UTF, ASCII, and ANSI code format of encoding?
Answer:
Character encoding interprets the zeros and ones into real characters.

Unicode:

Unicode is a standard that can handle characters for almost all modern languages and even some ancient languages at the same time, as long as the client has fonts for the particular language installed in his system

UTF:

Unicode assigns each character a unique number, or code point. It defines two mapping methods, the UTF (Unicode Transformation Format) encodings, and the UCS (Universal Character Set) encodings. Unicode-based encodings implement the Unicode standard and include UTF-8, UTF-16, and UTF-32/UCS-4. They go beyond 8-bits.

ASCII:

ASCII is abbreviated from American Standard Code for Information Interchange, is a character encoding standard.ASCII codes represent text in computers. lt is a code for representing characters as numbers, with each letter assigned a number from 0 to 127. In an ASCII file, each alphabetic, numeric, or special character is represented with a 7-bit binary number

ANSI:

ANSI is abbreviated from American National Standards Institute, is a character encoding standard.ANSI includes all the ASCII characters with an additional 128 character codes. ASCII just defines a 7-bit code page with 128 symbols. ANSI extends this to 8 bit and there are several different code pages for the symbols 128 to 255.

Question 4.
Can you serialize hashtable and Why?
Answer:
No, You can’t Serialize the Hash table. Because the .NET Framework does not allow serialization of any object that implements the IDictionary interface

Question 5.
What is .PDB file?
Answer:
PDB is an abbreviation for Program Data Base. It is a repository (persistent storage as databases) to maintain the information required to run your program in debug mode. It contains much important relevant information required while debugging your code; for e.g. at what points you have inserted breakpoints where you expect the debugger to break rn Visual Studicr etc.

Question 6.
Why singleton pattern is considered an Anti-pattern?
Answer:
– Singletons aren’t easy to handle with unit tests. You can’t control their instantiation and they may retain state across invocations.
– Memory allocated to a Singleton can’t be freed.
– In a multithreaded environment, access to the singleton object may have to be guarded (e.g. via synchronization).
– Singletons promote tight coupling between classes, so it is hard to test

Question 7.
What are extension methods and where can we use them?
Answer:
Extension methods enable you to add new capabilities to an existing type. You don’t need to make any modifications to the existing type, just bring the extension method into the scope and you can call it like a regular instance method.
Extension methods need to be declared in a nongeneric, non-nested, static class.

Notes:

  • The difference between a regular static method and an extension method is the special keyword for the first argument,
  • An extension method cannot be declared on a class or struct,
  • It can also be declared on an interface (such as IEnumerable). Normally, an interface wouldn’t have any implementation. With extension methods, however, you can add methods that will be available on every concrete implementation of the interface
  • Language-Integrated Query (LINQ) is one of the best examples of how you can use this technique to enhance existing code.
    You can read the implementation of Extension Methods in C# here.

Question 8.
How to update the web. config programmatically?
Answer:
This file is an XML file, and reading/writing XML is supported by. NET. You can choose one of the methods as per your requirement:

  • Use System.Xml.XmlDocument class. It implements a DOM interface; this way is the easiest and good enough if the size of the document is not too big.
  • Use the classes System.Xml.XmlTextWriter and System.Xml.XmlTextReader; this is the fastest way of reading
  • Use the class System.Xml.Linq.XDocument; this is to support LINQ to XML Programming.

Question 9.
What is the difference between Stack and Heap memory in C#? Stack Memory
Answer:
Stack Memory

C# Professional (Expert) Interview Questions in .NET chapter 4 img 1

It is an array of memory.
It is a LIFO (Last In First Out) data structure.
In it, data can be added to and deleted only from the top of it.
“Things” declared with the following list of type declarations are Value Types (because they are from System.ValueType):
bool, byte, char, decimal, double, enum, float, int, long, sbyte, short, struct, uint, ulong, ushort

Memory allocation is Static

C# Professional (Expert) Interview Questions in .NET chapter 4 img 2

Variables can’t be Resized Its access is fast
Its block allocation is reserved in LIFO.
The most recently reserved block is always the next block to be freed.
It can be visible/accessible only to the Owner Thread
In recursion calls, memory-filled up quickly
It can be used by one thread of execution
.NET Runtime throws exception “StackOverflowException” when stack space is exhausted
Local variables get wiped off once they lose the scope
It contains values for Integral Types, Primitive Types, and References to the Objects.

Heap Memory
C# Professional (Expert) Interview Questions in .NET chapter 4 img 3

It is an area of memory where chunks are allocated to store certain kinds of data objects.
In it data can be stored and removed in any order.
“Things” declared with the following list of type declarations are Reference Types
(and inherit from System. Object… except, of course, for an object which is the System. Object object):
class, interface, delegate, object, string
Memory allocation is Dynamic
It is stored indirectly

C# Professional (Expert) Interview Questions in .NET chapter 4 img 4

Variables can be Resized

Its access is Slow
Its block allocation is free and done at any time
It can be visible/accessible to all the threads
In recursion calls memory filled up slowly
It can be used by all the parts of the application
It is a special thread created by .NET runtime to monitor allocations of heap space.
It only collects heap memory since objects are only created in heap

Question 10.
What is the difference between covariance and contravariance?
Answer:
If you have an interface IFoo<T> it can be covariant in T (i.e. declare it as IFoocout T> if T is only used in an output position (e.g. a return type) within the interface. It can be contravariant in T (i.e. IFoo<in T>) if T is only used in an input position (e.g. a parameter type).

Covariance

Canonical examples: IEnumerable<out T>, Func<out T>

You can convert from IEnumerable<string> to IEnumerable<object>, or Func<string> to Func<object>. Values only come out from these objects.

It works because if you’re only taking values out of the API, and it’s going to return something specific (like string), you can treat that returned value as a more general type (like object).

Contravariance

Canonical examples: IComparer<in T>, Action<in T>

You can convert from IComparer<object> to IComparer<string>, or Action<object> to Action<string>; values only go into these objects.

This time it works because if the API is expecting something general (like object) you can give it something more specific (like string).

Question 11.
What are indexers in C# .NET? What is the difference between property & indexers?
Answer:
An indexer is a pair of get and set accessors, similar to those of properties.

  • Like a property, an indexer does not allocate memory for storage,
  • Both indexers and properties are used primarily for giving access to other data members with which they are associated and for which they provide get and set access.

– A property usually represents a single data member.
– An indexer usually represents multiple data members.

  • Like a property, an indexer can have either one or both of the accessors,
  • Indexers are always instance members; hence, an indexer cannot be declared static.
  • Like properties, the code implementing the get and set accessors does not have to be associated with any fields or properties. The code can do anything, or nothing, as long as the get accessor returns some value of the specified type.

Question 12.
What’s the difference between delegates and events?
Answer:
An event is just a wrapper for a multicast delegate.
Adding a public event to a class is almost the same as adding a public multicast delegate field.
In both cases, subscriber objects can register for notifications, and in both cases, the publisher object can send notifications to the subscribers. However, a public multicast delegate has the undesirable property that external objects can invoke the delegate, something we’d normally want to restrict to the publisher. Hence events – an event adds public methods to the containing class to add and remove receivers but does not make the invocation mechanism public.

Question 13.
Can we Overload the main( ) method rn C#?
Answer:
Yes, We can overload the main( ) method. A C# class can have any number of main() methods.
But to run the C# class, the class should have the main( ) method with signature as “public static void main(String[] args)”. If you do any modifications to this signature, the compilation will be successful. But, You will get a run time error as the main method is not found.

Question 14.
How to design a class (or data type) that sorts its data either ascending or descending by default
Answer:
You can do this by using Array.BinarySearch. Below is the implementation in C#.

class Program
{
static void Main(string[] args)
{
MySortedList list = new MySortedList( );
list.Add(13);
list.Add(Sl);
list.Add(25);
list.Add(9);
list.Add(33);
list.Add(46);
list.Add(1);
13 foreach (int v in list.ltems)
{
Console. WriteLine(v);
}
Console. ReadLine( );
}
}
class MySortedList
{
int[] items = new int[0];
public int[] Items
{
get {return items;}
set {items = value;}
} 

public void Add(int value)
{
int index = Array.BinarySearch(items, value);
if (index < 0)
index = ~index;


//Increase Items Array Size by 1
int lastlndex = items.Length;
int capacity = items.Length + 1;
int[ ] dupArray = new incapacity];
Array.Copy(items, dupArray, items.Length);
items = dupArray;


//Adjusting elements to insert element in its right index
if (index < lastlndex)
{
Array.Copy(items, index, items, index + 1, lastlndex - index);
}
items[index] = value;
} 
}

Question 15.
You have a component with 5 parameters and deployed to client-side now you changed your method which takes 6 parameters. How can you deploy this without affecting the client’s code?
Answer:
Instead of adding the 6th parameter to the existing method, write a new overloaded method with 6 parameters.

So when the old application calls this method, a method with 5 parameters will execute.
And method with 6 parameters will be used by the new application. That way we can provide backward compatibility to old applications.

Question 16.
What is Satellite Assembly?
Answer:
A satellite assembly is a compiled library (DLL) that contains “localizable” resources specific to a given culture such as strings, bitmaps, etc. You are likely to use satellite assemblies when creating a multilingual Ul application.

As per MSDN definition, A .NET Framework assembly containing resources specific to a given language. Using satellite assemblies, you can place the resources for different languages in different assemblies, and the correct assembly is loaded into memory only if the user elects to view the application in that language.

Question 17.
Explain the difference between Error and Exception in C#?
Answer:
Exception handling is a mechanism to detect and handle errors at a run time whereas Errors occurred at development/compile time. You can read more on exception handling in C# here.

Question 18.
What is the difference between == and .Equals method in c#?
Answer:
intx = 20;
int y = 20;
Console.WriteLine( x == y); Console. WriteLine(x.Equals(y));
Output:
True
True

For Reference Type:

== performs an identity comparison, i.e. it will only return true if both references point to the same object. While EqualsO method is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent.

For Example:
StringBuilder si = new StringBuilder(“Yes”);
StringBuilder s2 = new StringBuilder(“Yes”);
Console.WriteLine(s1 == s2);
Console. WriteLine(s1.Equals(s2));
Output:

False
True

In the above example, si and s2 are different objects hence “==” returns false, but they are equivalent hence “EqualsO” method returns true. Remember there is an exception to this rule, i.e. when you use the “==” operator with string class it compares value rather than identity.

When to use “==” operator and when to use “.EqualsO” method?

For value comparison, with Value Type use “==” operator and use “Equals( )” method while performing value comparison with Reference Type.

5. What is Partial class and What all are the What is Partial class and What all are the advantages of Partial class

Question 19.
What is a Partial class and What all are the advantages of a Partial class?
Answer:
The class declaration can be partitioned into several partial class declarations.

  • Each of the partial class declarations contains the declarations of some of the class members.
  • The partial class declarations of a class can be in the same file or in different files,
  • Each partial declaration must be labeled as a partial class, in contrast to the single keyword class.

Advantages of Partial Class:

By Using Partial Classes, multiple developers can work on the same class easily. Partial classes are mainly used by the code generators to keep different concerns separate you can also define Partial methods as well where a developer can simply define the method and the other developer can implement that.

Question 20.
What all are the Advantages and Disadvantages of Generics in C#?
Answer:

Advantages of Generics:

  • Generics provide type safety without the overhead of multiple implementations.
  • Generics eliminates boxing and unboxing.
  • There is no need to write code to test for the correct data type because it is enforced at compile time. The need for typecasting and the possibility of run¬time errors are reduced.
  • By providing strong typing, a class built from a generic lets visual studio provide IntelliSense.
  • Generic collection types generally perform better for storing and manipulating value types because there is no need to box the value types
  • Generic delegates enable type-safe callbacks without the need to create multiple delegate classes.

Disadvantages of Generics:

  •  Generic types can be derived from most base classes, such as MarshalByRefObject (and constraints can be used to require that generic type parameters derive from base classes like MarshalByRefObject). However, the .NET Framework does not support context-bound generic types. A generic type can be derived from ContextBourrdObject, but trying to create an instance of that type causes a TypeLoadException.

• Enumerations cannot have generic type parameters.
• Lightweight dynamic methods cannot be generic.
• In C#, a nested type that is enclosed in a generic type cannot be instantiated unless types have been assigned to the type parameters of all enclosing types

Question 21.
Why C# main method is static?
Answer:
The C# main method is static because the object is not required to call static method if it were non-static method, the compiler creates object first then call main() method that will lead to the problem of extra memory allocation.

Question 22.
What is Implementation Inheritance and Interface Inheritance?
Answer:

Implementation inheritance:

  1. It is achieved when a class is derived from another class in such a way that it inherits all its members.
  2. It is called Class Inheritance.
  3. In this, it uses the ‘extends’ keyword in Java.
  4. The subclass is tightly coupled with the superclass.
  5. If there are any changes to superclass will break the whole relationship.

Interface inheritance:

  1. It is achieved when a class inherits only the signatures of the functions from another class.
  2. It is called Type inheritance and also called subtyping.
  3. In this, it uses the ‘implements’ keyword in Java.
  4. It is used for code reuse and polymorphism.
  5. It reduces coupling and implementation dependencies.

Question 23.
What is Assembly Manifest?
Answer:
Within every Assembly, there is an Assembly Manifest. It contains:

  1. The assembly’s identity (its name and version).
  2. A file table describing all the other files that make up the assembly, for example, any other assemblies you created that your .exe or .dll file relies on, or even bitmap or Readme files.
  3. An assembly reference list, which is a list of all external dependencies—.dlls or other files your application needs that may have been created by someone else. Assembly references contain references to both global and private objects. Global objects reside in the global assembly cache.

Question 24.
What is Reflection and what all are the common use of Reflection?
Answer:
Reflection is a process by which a program can examine and manipulate program objects at run time.
A common use of Reflection:

  1. Load assemblies at runtime
  2. it allows you to learn what assembly defines a particular item such as a class or enumeration
  3. List a class’s field, properties, constructors, event, and methods
  4. Get information about a property such as a type and if it is read-only
  5. Get and Set property’s value
  6. Get information about the item’s attribute etc.

Question 25.
What is Encapsulation and Data hiding in C#?
Answer:
– Encapsulation is a process of hiding the members from outside of class and implemented using access specifiers
– Encapsulation is also called information hiding.
– Encapsulation provides a way to preserve the integrity of state data. Rather than defining public fields, private data fields should be defined.
– Well-encapsulated class should hide its data and the details of how it operates on data from the outside world. This is termed black box programming.
– Using this, the implementation of the method can be changed by the class author without breaking any existing code making use of it.

Question 26.
What does the tilde (~) mean in C#?
Answer:
The ~ operator performs a bitwise complement operation on its operand, which has the effect of reversing each bit. Bitwise complement operators are predefined for int, uint, long, and ulong. Also the ~ symbol is used to declare destructors.

You can read more on tilde(~) here.

Question 27.
Can you use tilde(~) with Enum in C#?
Answer:
Yes, You can use tilde(~) with Enum to flips the bits of its operand.

//using tilde(~)
[Flags]
public enum PurchaseMethod
{
All = ~0,
None = 0,
Cash = 1,
Check = 2,
CreditCard = 4
}
//Alternative:
[Flags]
public enum PurchaseMethod
{
None = 0,
Cash = 1,
Check = 2,
CreditCard = 4,
All = Cash | Check | CreditCard
}

– Source: Stack Overflow

Question 28.
What does placing a @ in front of a C# variable name do?
Answer:
It’s a way to allow declaring reserved keywords as vars. Example

1 void test(int @string)

Question 29.
How do you give a C# Auto-Property a default value?
Answer:
In C#5 and earlier, you can do it using a constructor.

class Employee
{ 
public Employee( )
{
Name = "Default Name";
}
public string Name {get; set;}
}

In C#6.0, You can do:

public string Name {get; set;} = “Default Name”

Question 30.
What is the use of the Yield keyword in C#?
Answer:
Yield keyword helps us to do custom stateful iteration over .NET collections. There are two scenarios where the “yield” keyword is useful:-

  • It helps to provide custom iteration without creating temp collections.
  • It helps to do state-full iteration

Question 31.
What is AsyncCallback in C#?
Answer:
When the async method finishes the processing, the AsyncCallback method is automatically called, where post-processing steps can be executed. With this technique, there is no need to poll or wait for the async thread to complete.

Question 32.
What is Nested types in C# and how to use it?
Answer:
Types are usually declared directly inside a namespace. You can, however, also declare types inside a class or struct declaration.
– Types declared inside another type declaration are called nested types. Like all type declarations, nested types are templates for an instance of the type.
– A nested type is declared like a member of the enclosing type.
– A nested type can be any type.
– An enclosing type can be either a class or a struct.

For example, the following code shows class MyClass, with a nested class called MyCounter.

class MyClass // Enclosing class
{
class MyCounter // Nested class
{
...
}
...
}

It is good to use Nested types if it is only meant to be used as a helper for the enclosing type.

attributes.

Question 33.
What is Null Coalescing Operator in C#?
Answer:
C# Supports a special operator called the null coalescing operator, which returns a non¬null value to an expression, in case a nullable type variable is null.
The null coalescing operator consists of two contiguous question marks and has two operands.

  • The first operand is a variable of a nullable type.
  • The second is a non-nullable value of the underlying type.
  • If at run time, the first operand (the nullable operand) evaluates to null, the non-nullable operand is returned as the result of the expression.

Example:

int? myl4 = null;
Console.WriteLine("myl4: {0}", myl4 ?? -1);
myl4= 10;
Console.WriteLine("myl4: {0}", myl4 ?? -1);
This code produces the following output:
myl4: -1
myl4:10

Question 34.
What are weak references in C#? How is it different than StrongReferences
Answer:
The garbage collector cannot collect an object in use by an application while the application’s code can reach that object. The application is said to have a strong reference to the object.

A weak reference permits the garbage collector to collect the object while still allowing the application to access the object. A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist. When you use a weak reference, the application can still obtain a strong reference to the object, which prevents it from being collected. However, there is always the risk that the garbage collector will get to the object first before a strong reference is established.

Weak references are useful for objects that use a lot of memory but can be recreated easily if they are reclaimed by garbage collection

Question 35.
What are XML namespaces for?
Answer:
XML namespaces are like packages in C#. They are for allowing multiple markup languages to be combined, without having to worry about conflicts of element and attribute names.

  • You can reuse a set of tags/attributes you define across different types of xml documents.
  • If you need to add some “aspect” to your XML; adding a namespace to your xml document is simpler than changing your whole xml schema definition.
  • Avoid polluting the “main” namespace: You don’t force your parser to work with a huge schema definition, just use the namespace you need to.

Question 36.
What is the difference between string and String in C#?
Answer:
String stands for System. String and it is a .NET Framework type, the string is an alias in the C# language for System. String. Both of them are compiled into System. String in IL (Intermediate Language), so there is no difference.

Question 37.
What’s the difference between the ‘ref and ‘out’ keywords in C#?
Answer:

The ref modifier means that:

  • The value is already set and
  • The method can read and modify it.

The out modifier means that:

  • The value isn’t set and can’t be read by the method until it is set.
  • The method must be set before returning.

semantically, ref provides both “in” and “out” functionality, whereas out only provides “out” functionality.

Question 38.
What is the difference between employee.GetType( ) and typeof(Employee) in at?
Answer:
The result of both would be exactly the same. lt will be your Employee type that derives from System. Type. The only real difference here is that when you want to obtain the type from an instance of your class, you use GetType. If you don’t have an instance, but you know the type name, you would use typeof.
GetType gets resolved at runtime, while typeof is resolved at compile time.

Question 39.
What is the difference between an EXE and a DLL?
Answer:

EXE:

  • An executable file, can run independently
  • It runs in a separate process
  • It can’t be reused in an application
  • it has the main function

DLL:

  • Dynamic-link library is used as part of EXE or other DLL’s
  • It runs in application process memory,
  • It can be reused in an application
  • It does not have the main function

Question 40.
What are the advantages and disadvantages of using the GAC?
Answer:

  • GAC is a central repository in a system in which assemblies are registered to be shared between applications.
  • GACUtil.exe is used to view and change the content of GAC in the system
  • GAC can contain multiple versions on .net assemblies -Thegautil.exe/I is used to install the assembly in GAC

Advantages & Disadvantages:

  1. Loading assemblies from GAC mean less overhead and security that your application will always load correct version of the .NET library
  2. You shouldn’t get assemblies that are outside of GAC, because there will be almost no performance gain, in many cases even loss in performance.
  3. You’re already using GAC, because all standard .NET assemblies are actually in GAC and needed (during installation).
  4. Using GAC for your own libraries adds complexity to deployment, I would try to avoid it at all costs.
  5. Your users need to be logged as administrators during installation if you want to put something into GAC, quite a problem for many types of applications.

Question 41.
What is the difference between a process and a thread?
Answer:
Process: 

  1. An executing instance of a program is called a process.
  2. Some operating systems use the term ‘task’ to refer to a program that is being executed.
  3. A process is always stored in the main memory also termed as the primary memory or random access memory.
  4. Therefore, a process is termed an active entity. It disappears if the machine is rebooted.
  5. Several processes may be associated with the same program.
  6. On a multiprocessor system, multiple processes can be executed in parallel.
  7. On a uni-processor system, though true parallelism is not achieved, a process scheduling algorithm is applied and the processor is scheduled to execute each process one at a time yielding an illusion of concurrency.

Thread:

  1. A thread is a subset of the process.
  2. It is termed as a ‘lightweight process’, since it is similar to a real process but executes within the context of a process and shares the same resources allotted to the process by the kernel.
  3. Usually, a process has only one thread of control – one set of machine instructions executing at a time.
  4. A process may also be made up of multiple threads of execution that execute instructions concurrently.
  5. Multiple threads of control can exploit the true parallelism possible on multiprocessor systems.
  6. On a uni-processor system, a thread scheduling algorithm is applied and the processor is scheduled to run each thread one at a time.
  7. All the threads running within a process share the same address space, file descriptors, stack, and other process-related attributes.
  8. Since the threads of a process share the same memory, synchronizing the access to the shared data within the process gains unprecedented importance.
  9. Source: Knowledge Quest

Question 42.
If asynchronous execution takes less total time to finish than synchronous execution, why would anybody choose synchronous execution?
Answer:
In Synchronus mode, every task executes in sequence, so it’s easier to program. That’s the way we’ve been doing it for years.
With asynchronous execution, you have few challenges:

  • You must synchronize tasks, for e.g. you run a task that must be executed after the other three have finished. You will have to create a mechanism to wait for all tasks to finish before launching the new task.
  • You must address concurrency issues. If you have a shared resource, like a list that is written in one task and read in another, make sure that it’s kept in a known state. -There is no logical sequence anymore. The tasks can end at any time, and you don’t have control of which one finishes first.

But in synchronous programming we have the below disadvantages:

  • It takes longer to finish.
  • It may stop the user interface (Ul) thread. Typically, these programs have only one Ul thread, and when you use it as a blocking

the operation, you get the spinning wheel (and “not responding” in the caption title) in your program-not the best experience for your users.

It doesn’t use the multicore architecture of the new processors. Regardless of whether your program is running on a 1-core or a 64-core processor, – it will run as quickly (or slowly) on both.

Asynchronous programming eliminates these disadvantages: it won’t hang the Ul thread (because it can run as a background task), and it can use all the cores in your machine and make better use of machine resources. So, do you choose easier programming or better use of resources? Fortunately, you don’t have to make this decision. Microsoft has created several ways to minimize the difficulties of programming for asynchronous execution.

Question 43.
Why do we need C# delegates?
Answer:
you can call methods directly on the object but in below scenarios you may consider using Delegates:

  1. You want to call series of methods by using a single delegate without writing a lot of method calls.
  2. You want to implement an event-based system elegantly.
  3. You want to call two methods the same in signature but reside in different classes.
  4. You want to pass a method as a parameter.
  5. You don’t want to write a lot of polymorphic code like in UNO., you can provide a lot of implementation to the Select method.

Question 44.
why do we use the Dictionary class instead of the Hashtable class?
Answer:
Dictionary is a generic type, Hashtable is not. That means you get type safety with Dictionary, because you can’t insert any random object into it, and you don’t have to cast the values you take out.

Hashtable supports multiple reader threads with a single writer thread, while Dictionary offers no thread safety. If you need thread safety with a generic dictionary, you must implement your own synchronization.

Question 45.
Are nullable types reference types in C#?
Answer:
Nullable types are instances of the System. Nullable struct. Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. So nullable types are not referenced types.

Question 46.
What is the difference between System exceptions and Application exceptions?
Answer:
System exceptions are derived directly from a base class System.SystemException. A System-level Exception is normally thrown when a nonrecoverable error has occurred. Application exceptions can be user-defined exceptions thrown by the applications. If you are designing an application that needs to create its own exceptions class, you are advised to derive custom exceptions from the System.ApplicationException class. It is typically thrown when a recoverable error has occurred.

Question 47.
What is the difference between Var and Dynamics in C#?
Answer:

Dynamic

Introduced in C# 4.0

Dynamically typed – This means the type of variable declared is decided by the compiler at run time.

No need to initialize at the time of declaration,

e.g., dynamic str;

Looking at the value assigned to the variable str, the compiler will treat the variable str as a string. str=”l am a string”; //Works fine and compiles

Errors are caught at runtime

Since the compiler comes to about the type and the methods and properties of the type at the run time.

Intellisense help is not available for the dynamic type of variables since their type is unknown until run time. So intellisense help is not available. Even if you are informed by the compiler as “This operation will be resolved at run-time”.

Will compile

var

Introduced in C# 3.0

Statically typed – This means the type of variable declared is decided by the compiler at compile time.

var type of variables are required to be initialized at the time of declaration or else they encounter the compile-time error: Implicitly-typed local variables must be initialized.

e.g.; var str=”l am a string”;

Errors are caught at compile time.

Since the compiler knows about the type and the methods and properties of the type at the compile time itself

Intellisense help is available for the var type of variables. This is because, its type is inferred by the compiler from the type of value it is assigned and as a result, the compiler that has all the information related to the type

will throw a compile error since the variable is not initialized. The compiler needs that this variable should be initialized so that it can infer a type from the value.

Question 48.
When to use Tuples in C#?
Answer:
Tuples are commonly used in four ways:

  • To represent a single set of data. For example, a tuple can represent a database record, and its components can represent individual fields of the record.
  • To provide easy access to, and manipulation of, a data set.
  • To return multiple values from a method without using out parameters -To pass multiple values to a method through a single parameter. For example, the Thread. The start (Object) method has a single parameter that lets you supply one value to the method that the thread executes at startup time. If you supply a Tuple object as the method argument, you can supply the thread’s startup routine with three items of data.

Question 49.
How can you create responsive Ul without impacting users?
Answer:
You can create a responsive Ul using multithreading. You can split the work into small pieces and run it in the background without impacting the user.

Question 50.
How to Force Garbage Collection?
Answer:
You can force this by adding a call to GC.Collect. Example:

StreamWriter stream = File.CreateText("temp.dat");
stream.Write("some test data");
GC.Collect( );
GC.WaitForPendingFinalizers( );
File.Delete("temp.dat");

Question 51.
What is the difference between Lock and Monitor in C#?
Answer:
Monitor and lock is the way to provide thread safety in a multithreaded application in C#.Lock is the keyword in C# that will ensure one thread is executing a piece of code at one time. The lock keyword ensures that one thread does not enter a critical section of code while another thread is in that critical section.

Question 52.
Why do we need Reflection in C#?
Answer:
We use Reflection in C#:

  1. Load assemblies at runtime
  2. it allows you to learn what assembly defines a particular item such as a class or enumeration
  3. List a class’s field, properties, constructors, event and methods
  4. Get information about a property such as a type and if it is read only
  5. Get and Set property’s value
  6. Get information about item’s attribute etc..

Question 53.
How do you mark a method as Obsolete/Deprecated?
Answer:
You can use Obsolete attribute to mark a method as Obsolete or Deprecated

Question 54.
Can you use ref and out parameters in Lambda expression, if declared outside?
Answer:
If you will use ref or out parameter outside of Larrrda Expression then you will get compile time error.

static void DoWork(int valln, out int valOut)
{
int local;

Action doCalc = ( ) =>
{
local = valln * 2; //this will work fine
//valOut = valln * i; // this will be a compile time error
};

// you can use the out parameter to assign result of lambda
Func<int> doCalc2 = () => valln * 2;
valOut = doCalc2(); //Allowed
}

Question 55.
How to return multiple values from a function in C#?
Answer:
In C#, There are several ways to return multiple values from a C# function.

  • Using KeyValue pair
  • Using ref/out parameters
  • Using Struct or Class
  • UsingTuple

of arrays.

Question 56.
How can you cancel an Async operation in C#?
Answer:
You can cancel your own async operation. There are two classes in the System.Threading.Tasks namespace that is designed for this purpose: CancellationToken and CancellationTokenSource.

A CancellationToken object contains the information about whether a task should be cancelled or not.
A task that has a CancellationToken object needs to periodically inspect it to see what the token’s state is. If the CancellationToken object’s IsCancellationRequested property is set to true, the task should halt its operations and return.
A CancellationToken is nonreversible and can only be used once. That is, once its IsCancellationRequested property is set to true, it can’t be changed.
A CancellationTokenSource object creates a CancellationToken object, which can then be given to various tasks. Any objects holding a CancellationTokenSource can call its Cancel method, which sets the CancellationToken’s IsCancellationRequested property to true.

Question 57.
Can an abstract class be Sealed in C#?
Answer:
An abstract class cannot be a sealed class because the sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.

Question 58.
What is the main use of a final block in exception^ handling? ‘
Answer:
The finally block is linked with a try block and contains a block of statements that are executed irrespective of whether an exception occurs or not within the try block. Finally defines the code that is executed always. In the normal execution it is executed after the try block When an exception occurs, it is executed after the handler if any or before propagation as the case may be.

Question 59.
How to avoid Singleton instance creation by cloning?
Answer:
We can create a copy of an object using clone( ) method.
To avoid creating a clone of our singleton class, we can do the following :

  • Implement MethodwiseClone( )
  • Override the clone() method and throw CloneNotSupportedException from it.
protected object MemberwiseClone( )
{
throw new Exception("Cloning a singleton object is not allowed");
}

Question 60.
What are generations in GC?
Answer:
After the garbage collector is initialized by the CLR, it allocates a segment of memory to store and manage objects.

This memory is called the managed heap, as opposed to a native heap in the operating system.

There is a managed heap for each managed process. All threads in the process allocate memory for objects on the same heap.

The heap is organized into generations so it can handle long-lived and short-lived objects. Garbage collection primarily occurs with the reclamation of short-lived objects that typically occupy only a small part of the heap. There are three generations of objects on the heap:

Generation 0. This is the youngest generation and contains short-lived objects. An example of a short-lived object is a temporary variable. Garbage collection occurs most frequently in this generation.

Newly allocated objects form a new generation of objects and are implicitly generation 0 collections unless they are large objects, in which case they go on the large object heap in a generation 2 collection.

Most objects are reclaimed for garbage collection in generation 0 and do not survive to the next generation.
Generation 1. This generation contains short-lived objects and serves as a buffer between short-lived objects and long-lived objects.
Generation 2. This generation contains long-lived objects. An example of a long-lived object is an object in a server application that contains static data that is live for the duration of the process.

Garbage collections occur on specific generations as conditions warrant. Collecting a generation means collecting objects in that generation and all its younger generations. A generation 2 garbage collection is also known as a full garbage collection, because it reclaims all objects in all generations (that is, all objects in the managed heap).
Generation 0 – Short-lived Objects
Generation 1- As a buffer between short-lived and long-lived objects Generation 2 – Long lived objects

Question 61.
How to catch multiple exceptions at once in C#?
Answer:
You can catch multiple exceptions using condition statements in C#. Example

catch (Exception ex)
{
if (ex is FormatException 11 ex is OverflowException)
{
testid = " ":
return;
}

throw;
}
catch (Exception ex) when (ex is FormatException 11 ex is 
OverflowException)

{

testid = " ";

return;

}

Question 62.
Write a Regular expression to validate the email address?
Answer:
A[a-zA – Z0 – 9. _%+-]+@[a-zA – ZO-9 . _%+-]+V[a-zA-Z]{2,4}$ In the above example:

  • the sequence A[a-zA – ZO-9. _%+-] matches letters,digits, underscores, %,+ and
  • The + (plus) sign after the 1st sequence means the string must include one or more of those characters
  • Next, the pattern matches @
  • Then the pattern matches another letter one or more times followed by a . and then between two to four letters

Question 63.
Can you loop through all Enum values in C#?
Answer:
Yes, you can loop through all Enum values using GetValues or the typed version.

public enum Color {
Red,
Blue,
Black,
White
}
var values = Enum.GetValues(typeof(Colors));
//Or the typed version
var values = Enum.GetValues(typeof(Colors)).Cast<Colors>( );

Question 64.
Should ‘using’ statements be inside or outside the namespace in C#?
Answer:
Let’s look at the below example to understand the difference between ‘using’ statements inside or outside the namespace, suppose there are 2 files.

// Filel.cs
using System;
namespace Outer.lnner
{
class Foo
{
static void Bar()
{
double d = Math.PI;
}
}
}

// File2.cs
namespace Outer
{
class Math
{
}
}

The compiler searches Outer before looking at those using statements outside the namespace, so it finds Outer. Math instead of System.Math. Outer. Math has no PI member, so Filel is now broken.
This changes if you put the “using” inside your namespace declaration, as follows:

// File lb. cs
namespace Outer.Inner
{
using System;
class Foo
{
static void Bar( )
{
double d = Math. PI;
}
}
}

Now the compiler searches ‘System’ before searching ‘Outer’, finds ‘System. Math’. So this will work fine. So we can say it depends on the type of system we are creating.

Question 65.
Should a return statement be inside or outside a lock statement?
Answer:
Whether you put the return statement inside or outside a lock statement, It doesn’t make any difference; they’re both translated to the same thing by the compiler.

It is recommended to put the return inside the lock. Otherwise, you risk another thread entering the lock and modifying your variable before the return statement, therefore making the original caller receive a different value than expected.

Question 66.
How to iterate over a Dictionary in C#?
Answer:
You can use key-value pair to iterate over a dictionary in C#.

for each(KeyValuePair<string, string> entry in myDic)
{
// do something with entry.Value or entry.Key
}

If you are trying to use a generic Dictionary in C# like you would use an 
associative array in another language: 

foreach(var item in my dictionary)
{

foo(item.Key);

bar(item.Value);
}
Or, if you only need to iterate over the collection of keys, use 

foreach(var item in my dictionary.Keys)
{
foo(item);
}
And lastly, if you're only interested in the values: foreach(var item in my dictionary.Values)
{
foo(item);
}

Question 67.
What is the use of the IDisposable interface in C#
Answer:
The primary use of the IDisposable interface is to clean up unmanaged resources.”unmanaged” means things like database connections, sockets, window handles, etc. The garbage collector doesn’t know how to call DeleteHandle( ) on a variable of type IntPtr, it doesn’t know whether or not it needs to call DeleteHandle( ).
So Microsoft has faciliated the Idisposable Interface and Dispose method to clean up unmanaged resources.

Implement IDisposable and Dispose method:

using System;
using System.10;
class UnmangedWrapper: IDisposable
{
public FileStream Stream {get; private set;}
public UnmangedWrapper( )
{
this.Stream = File.Open("temp.dat", FileMode.Create);
}
~UnmangedWrapper( )
{
Dispose(false);
}
public void Close()
{
Dispose();
}
public void DisposeQ
{
Dispose(true);

System.GC.SuppressFinalize(this);
}
public void Dispose(bool disposing)
{
if (disposing)
{ 
if (Stream != null)
{
Stream. CloseQ;
}
}
}

Question 68.
What all are the difference between the Dictionary class and Hashtable class?
Answer:

Hashtable

A Hashtable is a non-generic collection.

Hashtable is defined under System. Collections namespace.

In Hashtable, you can store key/value pairs of the same type or of a different type.

In Hashtable, there is no need to specify the type of the key and value.

The data retrieval is slower than Dictionary due to boxing/ unboxing.

In Hashtable, if you try to access a key that doesn’t present in the given Hashtable, then it will give null values.

It is thread-safe.

It doesn’t maintain the order of stored values.

Dictionary

A Dictionary is a generic collection.

Dictionary is defined under System.Collections.Generic namespace.

In Dictionary, you can store key/value pairs of the same type.

In Dictionary, you must specify the type of key and value.

The data retrieval is faster than Hashtable due to no boxing/ unboxing.

In Dictionary, if you try to access a key that doesn’t present in the given Dictionary, then it will give an error.

It is also thread-safe but only for public static members.

It always maintains the order of stored values.

Question 69.
When to use struct instead of class in C#?
Answer:
Consider defining a structure instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.
Do not define a structure unless the type has all of the following characteristics:

  1. It logically represents a single value, similar to primitive types (integer, double, and so on).
  2. It has an instance size smaller than 16 bytes.
  3. It is immutable.
  4. It will not have to be boxed frequently.

Question 70.
How do you generate a random number in C#?
Answer:
The Random class is used to create random numbers in C#.

//Example:

Random r = new Random( );

int n = r.Next( );

Question 71.
How to split a string using Regex in C#?
Answer:
The Regular Expressions SplitQ methods are similar to the String.split( ) method, except that Regex.split( ) method splits the string at a delimiter determined by a Regular Expression instead of a set of characters.

When using Regular Expressions you should use the following namespace:

using System.Text.RegularExpressions;
string str = "testl\n \ntest2\n \ntest3\n \n \ntest4";
string[ ] result = Regex.Split(str, "\n\\s*");
 for (int i = 0; i < result.Length; i++)
MessageBox.Show(result[i]);

//Output:
test1
test2
test3
test4

Question 72.
How can you get the assembly version in C#?
Answer:
You can get the assembly version in C#:

1 Version version = Assembly.GetEntryAssembly().GetName().Version;

Question 73.
How would you Read settings from app.config or web. config in C#?
Answer:
ConfigurationManager.AppSettings[“MySetting”]

You will need to add a reference to System. Configuration in your project’s references folder.

Question 74.
When you create and compile an application in C#, what are the files that get generated in Debug folder?
Answer:
When you will create and compile a program in C#, you will see the below files in Debug folder.

  • exe – the ‘normal’ executable
  • vshost.exe – a special version of the executable to aid debugging; see MSDN for details
  • pdb – the Program DataBase with debug symbols
  • vshost.exe.manifest – a kind of configuration file containing mostly dependencies on libraries

Question 75.
Can you add extension methods to an existing static class?
Answer:
No. Extension methods require an instance of an object. However, you can do something like this:

public static class Extensions
{
public static T Create<T>(this T @this)
where T : class, new()
{
return Utility<T>.Create();
}
}

public static class Utility<T>

where T : class, new()

{
static Utility()
{

Create =
Expression.Lambda<Func<T»(Expression.New(typeof(T).GetConstructor(Type.Empty Types))).Compile();

}
public static Func<T> Create { get; private set;}

}

Question 76.
What is the difference between Object pooling and Connection pooling in C#?
Answer:
The object pool implementation will increase the size of the pool up to the specified maximum. When the maximum is reached, instead of throwing an exception, it makes the client wait until an object is returned to the pool, and then gives the newly returned object to the waiting client.

The connection pool implementation does not have a maximum size parameter – it will keep creating new connections to meet demand (eventually it will hit some system limit and the request will fail in some way that isn’t specified.

Question 77.
What is the use of volatile keywords?
Answer:
The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.

The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access.

The volatile keyword can be applied to fields of these types:

  1. Reference types.
  2. Pointer types (in an unsafe context). Note that although the pointer itself can be volatile, the object that it points to cannot. In other words, you cannot declare a “pointer to volatile.”
  3. Integral types such as byte, byte, short, short, int, int, char, float, and bool.
  4. An enum type with an integral base type.
  5. Generic type parameters are known to be reference types.
  6. IntPtr and UlntPtr.

Question 78.
What is the use of Partial class in C#?
Answer:

  • By Using Partial Classes, multiple developers can work on the same class easily.
  • Partial classes are mainly used by the code generators to keep different concerns separate
  • you can also define Partial methods as well where a developer can simply define the method and the other developer can implement that.

Explain Constructor Overloading, Constructor Chaining, copy constructor

It is quite similar to Method overloading. It is the ability to redefine a Constructor in more than one form. A user can implement constructor overloading by defining two or more constructors in a class sharing the same name. C# can distinguish the constructors with different signatures, i.e. the constructor must have the same name but with a different parameters list.
We can overload constructors in different ways as follows:

  • By using different types of arguments
  • By using a different number of arguments
  • By using a different order of arguments

By changing the Data types of the parameters

Example:

public ADD (int a, float b);

public ADD (string a, int b);

Here the name of the class is ADD. In the first constructor there are two parameters, first one is int and another one is float and in the second constructor, also there is two parameters, the first one is a string type and another one is int type.

Here the constructors have the same name but the types of the parameters are different, similar to the concept of method overloading.

// C# program to Demonstrate the overloading of
// constructor when the types of arguments
// are different
usingSystem;


classADD {


intx, y;
doublet;
strings;


// 1st constructor
publicADD(inta, doubleb)
{
x = a;
f = b;
}


// 2nd constructor
publicADD(inta, stringb)
{
y= a;
s = b;
} 


// showing 1st constructor's result
publicvoidshow( )
{
Console.WriteLine("lst constructor (int + float): {0}",
(x+f));

}


// shows 2nd constructor's result
publicvoidshowl( )
{
Console.WriteLine("2nd constructor (int + string): {0}",
(s + y));
}
}
// Driver Class
classGFG {


// Main Method
staticvoidMain( )
{
// Creating instance and
// passing arguments
// It will call the first constructor
ADD g = newADD(10, 20.2);


// calling the method
g.show( );


// Creating instance and
// passing arguments
// It will call the second constructor
ADD q = newADD(10, "Roll No. is ");


// calling the method
q.show1( ); >
}
}

Output:

1st constructor (int + float): 30.2
2nd constructor (int + string): Roll No. is 10

By changing the number of the parameters

In this case, we will use two or more constructors having a different number of parameters. The data types of arguments can be the same but the number of parameters will be different.

Example:

public ADD (int a, int b);
public ADD (int a, int b, int c);

Here, the class name is ADD. In the first constructor, the number of parameters is two and the type of the parameters is Int. In the second constructor, the number of parameters is three and the types of the parameters are also an int, there is no problem with the data types.

// C# Program to illustrate the overloading of
// constructor when the number of parameters
// are different
using system;


classADD {


intx, y;
intf, p, s;


// 1st constructor
publicADD(inta, intb)
{
x = a;
y = b; 
} 


// 2nd constructor
publicADD(inta, intb, intc)
{
f = a;
P = b; s = c;
}
// showing 1st constructor's result
publicvoidshow( )

{
Console.WriteLine("lst constructor (int + int): {0}",
(x + y));


// showing 2nd constructor's result
publicvoidshow1( )
{
Console.WriteLine("2nd constructor (int + int + int): {0}",
(f + p + s));

}
}

// Driver Class
classGFG {


// Main Method
staticvoidMain( )
{


// will call 1st constructor
ADD g = newADD(10, 20);


// calling method
g.show( );


// will call 2nd constructor
ADD q = newADD(10, 20, 30);


// calling method
q.show1( );
}
}

Output:
1st constructor (int + int): 30
2nd constructor (int + int + int): 60

By changing the Order of the parameters

Example:

public student(double a, int x, string s)
public student(string s, int x, double a)

Here, the two constructors hold the same types of parameters, that is, each constructor has one double type, one int type, and one string type parameter, but the positions of the parameters are different. The compiler will invoke the constructor according to their argument order.

// C# program to illustrate the overloading of
// constructor by changing the order of parameters
usingSystem;


classstudent {


publicintroll;
publicdoubleHeight;
publicstringname;


publicstudent(doublea, intx, strings)
{
roll = x;
name = s;
Height = a;
}


// order of the argument is different
// with respect to 1st constructor
publicstudent(strings, intx, doublea)
{
Height = a;
roll = x;
name = s;
} 


publicvoidshow( )
{
Console.WriteLine("Roll Number:"+ roll);
Console.WriteLine("Height:"+ Height + "feet");
Console.WriteLine("Name:"+name);
}
}


// Driver Class
classVaibhav {


// Main Method
staticvoidMain( )
{


// invoking 1st constructor
student si = newstudent(5.7,10, "Vaibhav Singh");


// invoking 2nd constructor
student s2 = newstudent("Peter Perker", 11, 6.0);


Console.WriteLinef'First Constructor:");
sl.show( );


Console.WriteLine( );


Console.WriteLine("Second Constructor:");
s2.show();
}
}

Output:
First Constructor:
Roll Number: 10
Height: 5.7feet
Name: Vaibhav Singh

Second Constructor:
Roll Number: 11
Height: 6feet
Name: Peter Perker

Invoke an Overloaded Constructor using “this” keyword

We can call an overloaded constructor from another constructor using this keyword but the constructor must belong to the same class because this keyword is pointing to the members of the same class in which this is used. This type of calling the overloaded constructor is also termed as Constructor Chaining.

Example:
Let the class name is gfg,
Now
public gfg( )
public gfg(int a): this( )
public gfg(double b): this(int)

Here the first constructor is default constructor, second and third constructor is parameterized Constructors, where one has int type and another one has a double type parameter.
In the second constructor, this( ) invoke the first constructor which is the default constructor. Here, after this keyword, there is only ( ) which means the compiler invokes a constructor that has no argument, which means default constructor.
In third constructor, this(int) invoke the second constructor which is parameterized constructor. Here, after this there is (int) which means the compiler invoke constructor that has int type argument.

// C# program to illustrate the invoking of
// overloaded constructor using this keyword
usingSystem; 

classGFG {


// Private data members
privateintLength, Height;
privatedoubleWidth;


// Default Constructor
publicGFG( )
{
Console.WriteLine("Default Constructor Invoked");
}


//The constructor calls the
// Default constructor
publicGFG(intl, doublew) : this()
{
Console.WriteLine("Parameterized Constructor in 2nd Constructor");


// assigning value of
// 'Length'and 'Width'
Length = I;
Width = w;


}

// The constructor call the
// parameterized constructor
publicGFG(intl, doublew, inth): this(l, w)
{
Console.WriteLine("Parameterized Constructor in 3rd Constructor");


// assign value of 'Height'
Height = h;


}


// Public Method to calculate volume
publicdoubleVolume( )
{
return(Length * Width * Height);
}
}
// Driver Class
classVaibhav
{


// Main Method
publicstaticvoidMain()
{


// Invoking 3rd Constructor
// here Constructor chaining 
// came into existence
GFG g = newGFG(10, 20.5, 30);


// calling the 'Volume' Method
Console.WriteLine("Volume is : {0}", g.Volume( ));
}
}

Output:
Default Constructor Invoked

Parameterized Constructor in 2nd Constructor

Parameterized Constructor in 3rd Constructor

Volume is : 6150

Overloading of Copy Constructor

A parameterized constructor that contains a parameter of the same class type is called a copy constructor. Basically, copy constructor is a constructor which copies the data of one object into another object. Its main use is to initialize a new instance to the values of an existing instance.

// C# program to illustrate the
// overloading of Copy Constructor
usingSystem; 


classGFG {


publicstringpl, p2;
publicintp3, p4;


// 1st Constructor
publicGFG(stringx, stringy)
{
pi = x;
p2 = y;
} 


// Copy Constructor of 1st Constructor
publicGFG(GFG gf)
{
p1 = gf.p1;
p2 = gf.p2;
}


// 2nd Constructor with different
// types pf parameter publicGFG(inta, intb)
{
p3 = a; p4 = b;
}


// Copy Constructor of 2nd Constructor
// Flere number of parameter is different
// with respect to 1st Constructor
publicGFG(GFG a, GFG b)
{
p3 = a.p3; p4 = b.p4;
}
}


// Driver Class
classVaibhav {


// Main Method
staticvoidMain( )
{


// Create instance to class 'GFG'
GFG g = newGFGf.NET Interview Questions", "By Er.Vaibhav singh Chauhan");


// Here 'g' details will copied to 'gl'
GFG gl = newGFG(g);


Console.WriteLine(gl.pl + " to "+ gl.p2);


// Create instance to class 'GFG'
// with different types of parameter
GFG G = newGFG(10, 20);


// Here ’G' details will copied to 'Gl'
GFG G1 = newGFG(G, G);


Console.WriteLine("Overloaded values : {0} and {1}",
Gl.p3, Gl.p4);
}
}

 

Output:
.NET Interview Questions By Er.Vaibhav Singh Chauhan

Overloaded values: 10 and 20

Question 80.
Can we overload Static Constructor?
Answer:
Static Constructors cannot be overload, because Static Constructors are parameterless constructors, but for overloading, we must need the parameterized constructors.

Question 81.
Can we overload Private Constructor?
Answer:
Private Constructor cannot be overload, because of its protection level. Private members cannot be accessed from outside the class.

Question 82.
Difference between Static Constructors and Non-Static Constructors?
Answer:
Static constructors are used to initializing the static members of the class and are implicitly called before the creation of the first instance of the class. Non-static constructors are used to initializing the non-static members of the class. Below are the differences between the Static Constructors and Non-Static Constructors.

• Declaration: Static constructors are declared using a static modifier explicitly while all other remaining constructors are non-static constructors. Non-static constructors can also be called Instance Constructors as they need instances to get executed.

Example:

// C# Program to demonstrate
// how to declare the static
// constructor and non-static
// constructor
usingSystem;


class Vaibhav {
// static variable
staticints;


// non-static variable
intns;


// declaration of
// static constructor
Static Vaibhav()
{
Console.WriteLine("lt is static constructor");
}
// declaration of // non-static constructor Vaibhav ()
{ 
Console.WriteLine("lt is non-static constructor");
}


// Main Method
Static void Main(string[] args)
{


// static constructor will call implicitly
// as soon as the class start to execute
// the first block of code to execute
// will be static constructor
// calling non-static constructor
Vaibhav obj1 = new Vaibhav ();
}
}

Output:
It is static constructor
It is non-static constructor

• Calling: Static constructors are always called implicitly but the non-static constructors are called explicitly i.e by creating the instance of the class.
Example: In the above program, we have a static constructor i.e static
Vaibhav( ) which is called in the main method implicitly. See the output carefully, the code inside the static constructor is executing. But to call a non-static constructor i.e Vaibhav(), you need to create an instance of the class, i.e objl. So the creation of the object is to call the non-static constructor explicitly.
• Execution: Static constructor executes as soon as the execution of a class starts and it is the first block of code that runs under a class. But the non-static constructors execute only after the creation of the instance of the class. Each and every time the instance of the class is created, it will call the non-static constructor.

Example:

// C# Program to demonstrate
// the execution of static
// constructor and non-static
// constructor usingSystem;


class Vaibhav {


// declaration of
// static constructor
Static Vaibhav( )
{
Console.WriteLine("Static constructor");
}


// declaration of
// non-static constructor
Vaibhav( ) /
{
Console. WriteLine(" Non-Static constructor");
}
// Main Method
staticvoidMain(string[] args)
{


// static constructor will call implicitly
// as soon as the class start to execute
// the first block of code to execute /
/ inside the class will be static
// constructor


// calling non-static constructor
// here we are calling non-static
// constructor twice as we are
// creating two objects
Vaibhav objl = new Vaibhav( );
Vaibhav obj2 = new Vaibhav( );
}
}

 

Output:

Static constructor

Non-Static constructor

Non-Static constructor

Explanation: In the above program, there are two objects of Vaibhav^ class is created i.e objl and obj2. objl and obj2 will call the non-static constructor twice because each and every time the instance of the class is created, it will call the non¬static constructor. Although, in the Main method(entry point of a program), the first statement is “Vaibhav objl = new Vaibhavj);” but as soon as the compiler found the Main Method control will transfer to class and the static block will be executed first. That’s why you can see in the output that Static Constructor is called first.

• Times of Execution: A static constructor will always execute once in the entire life cycle of a class. But a non-static constructor can execute zero time if no instance of the class is created and n times if the n instances are created.
Example: In the above program, you can see the static constructor is executing only once but the non-static constructor is executing 2 times as the two instances of the class is created. If you will not create an instance of the class then the non-static constructor will not execute.

• Initialization of fields: Static constructors are used to initializing the static fields and non-static constructors are used to initialize the non-static fields.

Example:

// C# Program to demonstrate
//initialization of fields
// by using static constructor
// and non-static constructor
usingSystem;


classVaibhav {


//static variable
staticints;


// non-static variable
intns;

// declaration of
// static constructor
staticVaibhav( )
{
Console. WriteLine("Static constructor");
}


//declaration of
// non-static constructor
Vaibhav( )
{
Console.WriteLine("Non-Static constructor");
}


// Main Method
staticvoidMain(string[] args)
{
// static fields can
// be accessed directly
Console.WriteLinefValue of s is:"+ s);


// calling non-static constructor
Vaibhav objl = newVaibhav();


//printing the value
// of non-static field
Console.WriteLine("Value of ns is:"+ objl.ns);
}
}

 

Output:

Static constructor

Value of s is: 0

Non-Static constructor

Value of ns is: 0

  • Explanation: Here, both the static and non-static fields are initialized with default value. The default value of int type is zero. Static constructor will initialize only static fields. Here static field is s. While the non-static field(ns) is initialized by the non-static constructor.
  • Parameters: We cannot pass any parameters to the static constructors because these are called implicitly and for passing parameters, we have to call it explicitly which is not possible. It will give runtime error as shown in below example. However, we can pass the parameters to the non-static constructors.
    Example:
// C# Program to demonstrate
// the passing of paramters
// to constructor
usingSystem;


classVaibhav {


// static variable
staticints;



// non-static variable
intns;
// declaration of
// static constructor
// and passing parameter
// to static constructor
staticVaibhav(intk)
{


k = s;
Console.WriteLinef'Static constructor & K = "+ k);
}


// declaration of
// non-static constructor
Vaibhav( )
{
Console.WriteLine("Non-Static constructor");
}
// Main Method
staticvoidMain(string[] args)
{
}
} 

Runtime Error:
prog.cs(18,16): error CS0132: ‘Vaibhav.Vaibhav(int)’: The static constructor must be parameterless

Overloading: Non-static constructors can be overloaded but not static constructors. Overloading is done on the parameters criteria. So if you cannot pass the parameters to the static constructors then We can’t overload it.

Cases in which the constructor will be implicit:  Every class except the static class(which contains only static members) always contians an implicit constructor if the user is not defining any explicit constructor. If class contains any static fields then the static constructors are defined implicitly.