.Net Interview Questions

.Net Framework is the Foundation on which you design , develop and Deploy Applications.

CLR- is the environment where all the program using .Net technology  are executed. It provides some services such as Code Compilation, memory Allocation and Garbage Collection.

CLS- is a set of rules followed by All languages of .net framework.it enables an Object or Application to interact with object or Application of Other Language. One of the specification defined in the CLS is CTS.

CTS- defines how dataType are declared, used and managed in the Code at run time. It defines Rules that ensure that Datatype of Objects written in Various Language are able to interacts with eachOther.

Oops is one of the most Popular Methodology in Software Development. It offers powerful model for Creating Computer Program. it is based on modeling a Real world System.

MSIL is a Low Level  set of instructions understood by the JIT Compiler.

Object is the Combination of Message and Data.
Characteristics of Object: State , Behaviour, Identity.

What OOAD (Object Oriented Analysis & Design) design principals
The OOAD process is a sequential set of steps that begin with gaining a clear understanding of the needs and requirements of the customer and ends with a final blueprint or design of the application that matches, as closely as possible, the requirements of the customer. The framework is divided into four distinct phases, which include planning, requirements gathering, construction and transition.

What is DLR in .NET 4.0 framework?
DLR (Dynamic language runtime) is set of services which add dynamic programming capability to CLR. DLR makes dynamic languages like LISP, Javascript, PHP,Ruby to run on .NET framework.

Assembly is the Logical Unit of Code. It Physically Exists as the DLl or exes. An Assembly is the smallest Deployable Unit. It can be used by any Program that requires the Functionality provided by the Assembly.
             In other words, you can say that an assembly is a set of one or more modules and classes compiled in MSIL, and metadata that describes the assembly itself, as well as the functionalities of the assembly classes.

Dynamic Type in C#
It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time. The dynamic type variable is created using dynamic keyword.

cache-management-for-network-applications

What are the different types of assemblies in .net?

There are two types of assemblies are there in .net. They are, 
1. Private Assemblies and 
2. Public/Shared Assemblies. 
3. Satellite Assemblies

Private Assembly:- An assembly is used only for a particular application. It is stored in the application's directory other wise in the application's sub directory. There is no version constraint in private assembly. 
Public Assembly:- It has version constraint. This public assembly is stored inside the global assembly cache or GAC.GAC contains a collection of shared assemblies.
Satellite Assembly:- Satellite assemblies are assemblies that are used to deploy language and culture specific resources for an application. In an application, a separate product ID is assigned to each language and a satellite assembly is installed in a language specific sub-directory.

$ - string interpolation
The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolated expressions. When an interpolated string is resolved to a result string, items with interpolated expressions are replaced by the string representations of the expression results. This feature is available in C# 6 and later versions of the language.

string name = "Mark";
var date = DateTime.Now;

// Composite formatting:
Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);

// String interpolation:
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");

// Both calls produce the same output that is similar to:
// Hello, Mark! Today is Wednesday, it's 19:40 now.

AccessSpecifiers defines the Scope of a Class Member.

Properties- is a Way to access the Variables of Class in a Secure Manner. The Property Contains two Accessors- get Accessor and Set Accessor.

Stringbuilder- class can be used when u want to modify a string without Creating a new Object of it.

Destructor – are used to release the instance of Class from Memory.

GarbageCollection- is the Process that automatically frees the Memory of Objects that are no more in Use.

Why We Should Use Dispose Method?
It is always recommended to use Dispose method to clean unmanaged resources. You should not implement the Finalize method until it is extremely necessary. At runtime C#, C++ destructors are automatically converted to Finalize method.
.NET Garbage collector does almost all clean up activity for your objects. But unmanaged resources (For example, Windows API created objects, File, Database connection objects, COM objects, etc) is outside the scope of .NET framework we have to explicitly clean our resources. 
https://www.c-sharpcorner.com/

Delegate- allows you to Dynamically Change the referance to the methods in a Class.
A delegate is a referance type variable, which holds the referance to a method. This  referance can be changed at runtime . their Primary use in C# is for implementing events and  Callback functions.

Delegates provide a late binding mechanism in .NET. Late Binding means that you create an algorithm where the caller also supplies at least one method that implements part of the algorithm.

there are tow type of Delegate in c#- Single Cast, Multicast.

Structure in C#
Structure is a value type data type.it’s like a single Variable that holds related Data of different Data Type. The struct keyword is used for creating a structure.
  • Structures can have methods, fields, indexers, properties, operator methods, and events.
  • Structures can have defined constructors, but not destructors. However, you cannot define a default constructor for a structure. The default constructor is automatically defined and can't be changed.
  • Unlike classes, structures cannot inherit other structures or classes.
  • A structure can implement one or more interfaces.
Class vs Structure:
Classes and Structures have the following basic differences:
classes are reference types and structs are value types.
structures do not support inheritance.
structures cannot have default constructor.
 In structure, memory is allocated on stack, while in Class  memory is allocated on Heap.

Difference between String and string in C#.
Essentially, there is no difference between string and String (capital S) in C#.

String (capital S) is a class in the .NET framework in the System namespace. The fully qualified name is System.String. Whereas, the lower case string is an alias of System.String. click here for more

Object: They are instance of classes. It is a basic unit of a system. An object is an entity that has attributes, behavior, and identity. Attributes and behavior of an object are defined by the class definition.

system.object class?
This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.
methods defined in System.object : Equals(Object), Finalize, GetType, ToString 

What is the difference between == and object.Equals?
For value types, == and Equals() usually compare two objects by value. For example:

int x = 10;
int y = 10;
Console.WriteLinex == y );
Console.WriteLinex.Equals(y) );

will display:
True
True


However things are more complex for reference types. Generally speaking, for reference types == is expected to perform an identity comparison, i.e. it will only return true if both references point to the same object. By contrast, Equals() 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 s1 = new StringBuilder("fred");
StringBuilder s2 = new StringBuilder("fred");
Console.WriteLines1 == s2 );
Console.WriteLines1.Equals(s2) );

will display:
False
True

s1 and s2 are different objects (hence == returns false), but they are equivalent (hence Equals() returns true).

What is singleton pattern?
The singleton pattern is one of the simplest design patterns:
There are only two points in the definition of a singleton design pattern,
  1. there should be only one instance allowed for a class and
  2. we should allow global point of access to that single instance.
What is the relationship between a class and an object?

A class acts as a blue-print that defines the properties, states, and behaviors that are common to a number of objects. An object is an instance of the cass. 
For example, you have a class called Vehicle and Car is the object of that class. You can create any number of objects for the class named Vehicle, such as Van, Truck, and Auto.

The new operator is used to create an object of a class. When an object of a class is instantiated, the system allocates memory for every data member that is present in the class.

Explain the basic features of OOPs.
The following are the four basic features of OOP:
  • Abstraction - Refers to the process of exposing only the relevant and essential data to the users without showing unnecessary information.
  • Polymorphism -  Allows you to use an entity in multiple forms. In other words,  "Many forms of a single object is called Polymorphism."
  • Encapsulation - Prevents the data from unwanted access by binding of code and data in a single unit called object.
  • Inheritance - Promotes the reusability of code and eliminates the use of redundant code.       
Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time.

Static Polymorphism
  1. Function overloading
  2. Operator overloading
Dynamic Polymorphism
Dynamic polymorphism is implemented by abstract classes and virtual functions.

Collection: A collection can be defined as a group of related items that can be referred to as a single unit. The System.Collections namespace provides you with many classes and interfaces. Some of them are -ArrayList, List, Stack, ICollection, IEnumerable, and IDictionary. 

What is the difference between arrays and collection?
Array:
1.     You need to specify the size of an array at the time of its declaration. It cannot be resized dynamically.
2.     The members of an array should be of the same data type.

Collection:
1.     The size of a collection can be adjusted dynamically, as per the user's requirement. It does not have fixed size.
2.     Collection can have elements of different types. 

Can you specify the accessibility modifier for methods inside the interface?
All the methods inside an interface are always public, by default. You cannot specify any other access modifier for them.

The base keyword is used to access members of the base class from within a derived class:
Example : http://msdn.microsoft.com/en-IN/library/hfw7t1ce(v=vs.71).aspx

How is method overriding different from method overloading?
Overriding involves the creation of two or more methods with the same name and same signature in different classes (one of them should be parent class and other should be child). 

Overloading is a concept of using a method at different places with same name and different signatures within the same class.

enumeration?
Enumeration is defined as a value type that consists of a set of named values. These values are constants and are called enumerators. An enumeration type is declared using 
the enum keyword. The following is an example that creates an enumeration to store different varieties of fruits:

enum Fruits {Mango, Apple, orange, Guava}; 

In the preceding example, an enumeration Fruits is created, where number 0 is associated 
with Mango, number 1 with Apple, number 2 with Orange, and number 3 with Guava.


How do you prevent a class from being inherited ?
a) Make the class as sealed.
b) Add private constructors to the class.

Why c# does not support inheritance by structure?
Because structures are mainly used for light weight process. And if they are allowed to be inherited then they have to act as base class which is not possible as they are value types.

Can properties be marked as virtual ?
Yes 

How many types of inheritance supported by c#?
Ans: Two types of inheritance:

Implementation inheritance

Interface inheritance

Implementation inheritance-- When a class (type) is derived from another class(type) such that it inherits all the members of the base type it is Implementation 
Inheritance

Interface inheritance-- When a type (class or a struct) inherits only the signatures of the functions from another type it is Interface Inheritance.

Explain the difference between the while and for loop. Provide a .NET syntax for both loops.
Both loops are used when a unit of code needs to execute repeatedly. The difference is that the for loop is used when you know how many times you need to iterate through the code. On the other hand, the while loop is used when you need to repeat something until a given statement is true.

Shadowing is a VB.Net concept. It also known as method hiding in C#. We can also change return type of member also. Using the “new” keyword we can do the shadowing or method hiding.


What are Shallow Copy and Deep Copy in .NET?

The terms "Shallow Copy " and "Deep Copy " which refer to the way the objects are copied.

Shallow copy: This is nothing but creating a new object, and then copying the nonstatic fields of the current object to the new object. If a field is a value type then a bit-by-bit copy of the field is performed. If it is a reference type then the reference is copied but not the referred object. Therefore, the original object and its clone refer to the same object. 


Deep copy: Deep copy is partially same as shallow copy, but the difference is deep copy copies the whole object and makes a different object, it means it do not refer to the original object while in case of shallow copy the target object always refer to the original object and changes in target object also make changes in original object. It serializes the objects and deserializes the output.


you cannot overload methods based on return-type alone i.e. the following is not valid:


public class SomeClass
{
    public int GetValue() { return 1; }
    public string GetValue() { return "abc"; }
}

What is Jagged Arrays?

The array which has elements of type array is called jagged array. The elements can be of different dimensions and sizes. We can also call jagged array as Array of arrays.

Can “this” be used within a static method? 

We can’t use ‘This’ in a static method because we can only use static variables/methods in a static method.

What are value types and reference types? 

 Value types are stored in the Stack whereas reference types stored on heap.


Value types:

int, enum , byte, decimal, double, float, long

Reference Types:

string , class, interface, object

What are circular references?
Circular reference is situation in which two or more resources are interdependent on each other causes the lock condition and make the resources unusable.

What is an object pool in .NET?
 An object pool is a container having objects ready to be used. It tracks the object that is currently in use, total number of objects in the pool. This reduces the overhead of creating and re-creating objects.

How can we set class to be inherited, but prevent the method from being over-ridden?
Declare the class as public and make the method sealed to prevent it from being overridden.


What are abstract classes? 
An abstract class is a class that cannot be instantiated and is always used as a base class. The basic purpose of an abstract class is to provide a common definition of the base class that multiple derived classes can share.

Explain different types of inheritance.

Inheritance in OOP is of four types:
  • Single inheritance - Contains one base class and one derived class
  • Hierarchical inheritance - Contains one base class and multiple derived classes of the same base class
  • Multilevel inheritance - Contains a class derived from a derived class
  • Multiple inheritance - Contains several base classes and a derived class
Explain the concept of destructor?
A destructor is a special method for a class and is invoked automatically when an object is finally destroyed. The name of the destructor is also same as that of the class but is followed by a prefix tilde (~).
The main features of a destructor are as follows:
  • Destructors do not have any return type
  • Similar to constructors, destructors are also always public
  • Destructors cannot be overloaded.
What is a static constructor?
Static constructors are introduced with C# to initialize the static data of a class. CLR calls the static constructor before the first instance is created.

The static constructor has the following features:
  • No access specifier is required to define it.
  • You cannot pass parameters in static constructor.
  • A class can have only one static constructor.
  • It can access only static members of the class.
  • It is invoked only once, when the program execution begins.
Differentiate between an abstract class and an interface.

Abstract Class:
1.     A class can extend only one abstract class
2.     The members of abstract class can be private as well as protected.
3.     Any class can extend an abstract class.
4.     There can be a constructor for abstract class.
5.     The class extending the abstract class may or may not implement any of its method.
6.     An abstract class can not implement methods.

Interface
1.     A class can implement several interfaces
2.     An interface can only have public members.
3.     Only an interface can extend another interface.
4.     Interface does not have constructor.
5.     All methods of interface need to be implemented by a class implementing that interface.
6.     Interfaces cannot contain body of any of its method.

Abstraction Vs Encapsulation [ Encapsulation is the bodyguard; abstraction is the VIP.]

Abstraction - hiding implementation.
Encapsulation - hiding data.

Encapsulation: A simple definition of encapsulation is - combining the data (information) and the methods (functions) that can manipulate that data into one capsule (class/object). Depending on how you write program encapsulation, it guarantees that the encapsulated data is not accessed by any other function/method/program outside the encapsulated object. For example,

class MyCapsule
{
private int myInt;
private char myChar;
public void MyIntFunc() { myInt = 10; }
public void MyCharFunc() { myChar = 'A'};
};

In this case, no other program/function/method can access myInt other than MyIntFunc. Same is true for myChar and MyCharFunc.

Abstraction: A simple definition of abstraction is to hide actual implementation of an object from the external world that would use the object. For example, a program that is drawing circles and squares using those objects need not know how those objects are implemented. It is enough for the program to know what the behavior of these objects is, and how to use these objects (rather than how these objects are implemented internally).

So, drawing a parallel between abstraction and encapsulation, when you encapsulate data and methods that operate on data into one object, the external program that uses this object need not know the internal workings of the object to use the object. Thus making the object abstract data type to the external program. Classic examples of abstract data type in C (yes) are int, char, float, double etc. Classes are OOPL variations and extensions of the traditional abstract data types.

Access Modifiers

       Access Modifier
               Description (who can access)
         Private
        Only members within the same type.  (default for type members)
       Protected
       Only derived types or members of the same type.
         Internal                    
       Only code within the same assembly. Can also be code external to object     as long as it is in the same assembly.  (default for types)
        Protected internal
         Either code from derived type or code in the same assembly. Combination of protected OR internal.
         Public
        Any code. No inheritance, external type, or external assembly restrictions.


What are queues and stacks?
Stacks refer to a list in which all items are accessed and processed on the Last-In-First-Out (LIFO) basis. In a stack, elements are inserted (push operation) and deleted (pop operation) from the same end called top. 

Queues refer to a list in which insertion and deletion of an item is done on the First-In-First-Out (FIFO) basis. The items in a queue are inserted from the one end, called the rear end, and are deleted from the other end, called the front end of the queue.

recursion is the process in which the function keeps calling itself (with possibly a different set of arguments) till some base condition is met.

http://www.programminginterviews.info/2011/06/linq-interview-questions.html#toc 

Virtual Function: 
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 overriden in the derived class. We create a virtual method in the base class using the virtual keyword and that method is overriden in the derived class using the override keyword.
       We can't use the virtual modifier with the static, abstract, private or override modifiers. 
to Read More about Virtual Function

What is Early Binding and  Late Binding in c# ?     
In very simple terms, early binding happens at compile time and the compiler has the knowledge about the type and all it's members, and late binding happens at run time, the compiler doesn't know anything about the type and it's members.
Application will run faster in Early binding, since no boxing or unboxing are done here.

What is the default access level in c# ?      
Classes are Internal and members of a class are private.

What is Boxing/Unboxing?
Boxing is used to convert value types to object.

int x = 1;
object obj = x ;

Unboxing is used to convert the object back to the value type.
int y = (int)obj;

What is a hashtable?
Hashtable is a data structure that implements the IDictionary interface. It is used to store multiple items and each of these items is associated with a unique string key. Each item can be accessed using the key associated with it. In short, hashtable is an object holding the key-value pairs.

Operator Overloading: to perform some operation on user defined dataType we use Operator Overloading.An Operator can be overloaded by defining a function to it.
for example the Expression a+b may be taken as +(a,b). (here a and b is the Class object)

Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as sealed class, this class cannot be inherited. 
In C#, the sealed modifier is used to define a class as sealed.
Abstract Class and Sealed Class are opposite to eachother.
- Abstract Class allows Inheritence but Sealed restrict this.
- Abstract Class can not be instanciated while Sealed Class Object can be Created.
"Sealed Class says, if you want to use my members then Create my Object and Call my Functions."

Reflexion- Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System.Reflection namespace. The System.Reflection namespace contains classes that allow you to obtain information about the application and to dynamically add types, values and objects to the application.


ref and out Parameter
ref parameter pass the refrence of data instead of the actual data assighned  to them.

ref requires that the variable to be initialized before it is passed.
variables passed as out arguments do not have to be initialized before being passed, the called method is required to assign a value before the method returns.

class OutExample
{
    static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value;
        Method(out value);
        // value is now 44
    }
}

EX of ref parameter:
class RefExample
{
    static void Method(ref int i)
    {
        i = i++;
    }
    static void Main()
    {
        int value;
         value= 10;
        Method(ref value);
    }
}

Why is stringbuilder concatenation more efficient than simple string concatenation?
String is immutable. Immutable means once assigned it can not be changed. Thats why it creates more copies of the object as it can not use the same instance.String builder is mutable , in other words the same object will changed rather than creating new objects.
So string builder is more efficient as compared to simple string concatenation.

string str = "shiv";
StringBuilder objBuilder = new StringBuilder();
objBuilder.Append("shiv");

Why String Is Immutable?

what are synchoronous and asynochornous methods
asynch methods are those methods in which program does not wait for its return .
thier return will be executed when the response return.
while in synch method program stops and wait for the response to return n thn only program start executing further.

Uses of Reflection
Reflexion allows you to access Metadata information of ur application.
Check the type of an object at runtime (simple calls to typeof() for example)
It allows late binding to methods and properties
It allows creating new types at runtime and then performs some tasks using those types.
for more info: Click here
 

Managed code  and UnManaged code
The code, which is developed in .NET framework, is known as managed code.The code, which is developed outside .NET, Framework is known as unmanaged code.
Applications that do not run under the control of the CLR are said to be unmanaged, and certain languages such as C++ can be used to write such applications, which, for example, access low - level functions of the operating system. Background compatibility with code of VB, ASP and COM are examples of unmanaged code.

What is the difference between Finalize() and Dispose()
Finalize () is called by Garbage Collector implicitly to free unmanaged resources. The garbage collector calls this method at some point after there are no longer valid references to the object. There are some resources like windows handles, database connections which cannot be collected by the garbage collector. Therefore the programmer needs to call Dispose() method of IDisposable interface.
Dispose () of IDisposable interface is called by the programmer to explicitly release resources when they are no longer being used. Dispose () can be called even if other references to the object are alive. 

public void Dispose()
  {
        //Pass true in dispose method to clean managed resources too and say GC to skip finalize in next line.
          Dispose(true);
      //If dispose is called already then say GC to skip finalize on this instance.
       GC.SuppressFinalize(this);
   }

dispose method is used to clean managed resource.
And SuppressFinalize method is used to skip the finalize method.

Thread- can be defined as the execution path of a Programme.
Process- is a running instance of a Programme.
Controlling Execution of a Thread:
  • Start()- start a thread.
  • Sleep()- pause  the thread for a period of time.
  • Abort()- terminate the thread.
  • suspend()- suspend a thread.
  • Resume()- Resume the suspended thread.
Lifecycle of Thread- 
Unstarted-> Runnable-> Not Runnable-> Dead

Attribute- are used for adding metadata, such as Compiler instructions and other information such as Comments, descriptions, methods and the Classes to a Program.

Difference between exe and dll.
Exe(Executable) is the executable file which can be run standalone without support of any other file. It contains the self-executable information so it doesn’t need any external file or program to execute.
Dll(Dynamic Link Library) is the file which is not self-executable. It needs to be executed inside some other file. It is used to support the other dll’s or exe files.

A dll in GAC and a dll on a network which one is secure and why?
A dll in GAC is more secure and the most important is that in GAC, we can keep multiple versions of the dll which are having the same name while in the network we can’t keep the same name with multiple version files. So whenever there is the requirement to share the dll’s, always keep it in GAC instead of in a sharing folder in the network. 

Agile Software Development
 Agile software development is a group of software development methodologies based on iterative and incremental development, where requirements and solutions evolve (develope) through collaboration between self-organizing, cross-functional teams.  The most popular agile methodologies include Extreme Programming (XP), Scrum, Crystal, Dynamic Systems Development Method (DSDM), Lean Development, and Feature-Driven Development (FDD).
Agile methodologies are an alternative to waterfall, or traditional sequential development.

Understand the use of Override Keyword and New Keyword in C# with Example?
 Click @ me

Delegate - 

http://www.aspdotnet-suresh.com/2013/09/C-Sharp-delegates-example-use-of-delegates-in-C-Sharp.html

What are differences between Array list and Hash table?

Ans:
1) Hash table store data as name, value pair. While in array only value is store.
2) To access value from hash table, you need to pass name. While in array, to access value, you need to pass index number.
3) you can store different type of data in hash table, say int, string etc. while in array you can store only similar type of data.

What are differences between system.stringbuilder and system.string?

The main difference is system.string is immutable and system.stringbuilder is a mutable. Append keyword is used in string builder but not in system.string.
Immutable means once we created we cannot modified. Suppose if we want give new value to old value simply it will discarded the old value and it will create new instance in memory to hold the new value.

What are the differences between Application object and session object?
Ans: The session object is used to maintain the session of each user. If one user enter in to the application then they get session id if he leaves from the application then the session id is deleted. If they again enter in to the application they get different session id.
But for application object the id is maintained for whole application

How many types of memories are there in .net? 

Ans: Two types of memories are there in .net stack memory and heap memory

What are the differences between value type and reference type?
Ans: Value type contain variable and reference type are not containing value directly in its memory.
Memory is allocated in managed heap in reference type and in value type memory allocated in stack. Reference type ex-class value type-struct, enumeration

If I write System.exit (0); at the end of the try block, will the finally block still execute?

Ans: No in this case the finally block will not execute because when you say system.exit(0),the control immediately goes out of the program, and thus finally never executes.

What is the difference between .tostring(), Convert.tostring()?

Ans: The basic difference between them is “Convert” function handles NULLS while
“.ToString()” does not it will throw a NULL reference exception error. So as a good coding practice using “convert” is always safe.

Difference between Throw and Throw Ex
Throw
In Throw, the original exception stack trace will be retained. To keep the original stack trace information, the correct syntax is 'throw' without specifying an exception. It is always advised to use “throw” because it provides more accurate error information.

Declaration of throw
try
{
// do some operation that can fail
}
catch (Exception ex)
{
// do some local cleanup
throw;
}

Throw ex

In Throw ex, the original stack trace information will get override and you will lose the original exception stack trace. I.e. 'throw ex' resets the stack trace.

Declaration of throw ex

try
{
// do some operation that can fail
}
catch (Exception ex)
{
// do some local cleanup
throw ex;
}

Is it possible for a class to inherit the constructor of its base class?

No, a class cannot inherit the constructor of its base class.
   In C#, both the base class and the derived class can have their own constructor. The constructor of a base class used to instantiate the objects of the base class and the constructor of the derived class used to instantiate the object of the derived class. In inheritance, the derived class inherits all the members(fields, methods) of the base class, but derived class cannot inherit the constructor of the base class because constructors are not the members of the class. Instead of inheriting constructors by the derived class, it is only allowed to invoke the constructor of base class.

Can you allow a class to be inherited, but prevent a method from being overridden in C#?

Yes. Just declare the class public and make the method sealed.

What is a namespace?

Namespace is considered as a container that contains functionally related group of classes and other types.

Can users define their own exceptions in code?

Yes, customized exceptions can be defined in code by deriving from the System.Exception class.

What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?

The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identical object.

So the difference are :
1- CopyTo require to have a destination array when Clone return a new array.
2- CopyTo let you specify an index (if required) to the destination array.

myarray.CopyTo(myarray20);
myarray1 = myarray.Clone() as string[];

Difference between Clone and Copy method
clone - create something new based on something that exists.
copying - copy from something that exists to something else (that also already exists).

Difference between Namespace and Assembly

Namespace provides the fundamental unit of logical code grouping while an assembly provides a fundamental unit of physical code grouping.

Namespace

Namespaces is a logical group of related classes that can be used by any other language targeting the Microsoft .Net framework . 

Assembly

An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. It is an Output Unit, that is .exe or .dll file. It is a unit of Deployment and a unit of versioning and also it contain MSIL (Microsoft Intermediate Language) code. Assemblies are self describing, it contains all the metadata about the modules, types, and other elements in the form of a manifest.

Assemblies are of three types: Public, Private and Shared Assemblies.

Constructors and Its Types in C# With Examples

Basically constructors are 5 types those are
      1.    Default Constructor
      2.    Parameterized Constructor
      3.    Copy Constructor
      4.    Static Constructor
      5.    Private Constructor
For Detail Click Here

What is the difference between a field and a property?

Properties expose fields. Fields should (almost always) be kept private to a class and accessed via get and set properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.

EVENT: An event is a message sent by an object to signal the occurrence of an action. The action could be caused by user interaction, such as a mouse click, or it could be triggered by some other program logic. The object that raises the event is called the event sender. The object that captures the event and responds to it is called the event receiver.

Delegate: A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class has a signature, and it can hold references only to methods that match its signature. A delegate is thus equivalent to a type-safe function pointer or a callback. 


App Pool: An application pool is a group of one or more URLs that are served by a worker process or set of worker processes. This way, if there is an error in one app, it won't take down other applications.
IIS Application pool is feature in IIS which allows each website or a part of it to run under a corresponding w3wp.exe process. 
IIS Worker Process: An Internet Information Services (IIS) worker process is a windows process (w3wp.exe) which runs Web applications, and is responsible for handling requests sent to a Web Server for a specific application pool.

Partial method
A partial method has its signature defined in one part of a partial type, and its implementation defined in another part of the type. Partial methods enable class designers to provide method hooks, similar to event handlers, that developers may decide to implement or not. If the developer does not supply an implementation, the compiler removes the signature at compile time. The following conditions apply to partial methods:

Signatures in both parts of the partial type must match.
The method must return void.
No access modifiers are allowed. Partial methods are implicitly private.
The following example shows a partial method defined in two parts of a partial class:

namespace PM
{
    partial class A
    {
        partial void OnSomethingHappened(string s);
    }

    // This part can be in a separate file.
    partial class A
    {
        // Comment out this method and the program
        // will still compile.
        partial void OnSomethingHappened(String s)
        {
            Console.WriteLine("Something happened: {0}"s);
        }
    }
}

Q: How to Diagnose issues in .NET code deployed to a production environment, C# .NET Depending on the type of issue I am looking at, I usually go down this list:
  1. Add Soap tracing, System.Net tracing, System.Net.Sockets tracing.
  2. Custom logs (if any).
  3. Event logs.
  4. .NET, IIS and ASP.NET Performance Counters.
  5. WinDbg memory/crash dump analysis.
Q: Covariance and Contravariance Covariance enables you to use a more derived type than originally specified. Contravariance enables you to use a less derived type than originally specified.

datetime2 has larger date range, a larger default fractional precision, and optional user-specified precision.
Also depending on the user-specified precision it may use less storage. https://stackoverflow.com/questions/1334143/datetime2-vs-datetime-in-sql-server/1334193 For and Foreach Loop in C# Using for loop we can iterate a collection in both direction, that is from index 0 to 9 and from 9 to 0.
But using for-each loop, the iteration is possible in forward direction only.

Difference between asynchronous and parallel programming? When you run something asynchronously it means it is non-blocking, you execute it without waiting for it
to complete and carry on with other things. Parallelism means to run multiple things at the same time,
in parallel. Parallelism works well when you can separate tasks into independent pieces of work. Asynchonous programming solves the problem of waiting around for an expensive operation to complete
before you can do anything else. If you can get other stuff done while you're waiting for the operation to
complete then that's a good thing. Example: keeping a UI running while you go and retrieve more data
from a web service. Parallel programming is related but is more concerned with breaking a large task into smaller chunks that
can be computed at the same time. The results of the smaller chunks can then be combined to produce the
overall result.

Multithreading Multithreading in C# is a process in which multiple threads work simultaneously.
It is a process to achieve multitasking. It saves time because multiple tasks are being executed at a time.
To create multithreaded application in C#, we need to use System.Threding namespace.

1 comment:

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives