Showing posts with label Csharp. Show all posts
Showing posts with label Csharp. Show all posts

Saturday, 18 March 2017

C# basic interview questions Part-8

1. Ques: What is the Environment Class in C#? 
Answer:
The System.Environment Class provides information about the current environment and platform. The System.Environment Class uses to retrieve Environment variable settings, Version of the common language runtime, contents of the call stack etc. This class cannot be inherited.

The Environment class use for getting and setting various operating system related information. You can use this class to retrieve information such as command-line arguments, exit codes, environment variable settings, contents of the call stack, time since last system boot in milliseconds (tick count), and version of the CLR.


2. Ques: What is an Exception in C#?
Answer:
 An exception is an error that occurs during program execution. Generally, an exception describes an unexpected event.

  • The advantage of using exceptions is that the program doesn’t terminate due to the occurrence of the exception.
  • Whenever an exception is occurred the .NET runtime throws an object of specified type of Exception.
  • The class ‘Exception’ is the base class of all the exceptions.

Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. The .NET framework contains lots of standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) do not provide a mechanism to handle these anomalies, the .NET run time environment provide a default mechanism, which terminates the program execution.

Here are a few common types of exceptions:

System.NullReferenceException Handles errors generated from deferencing a null object.
System.DivideByZeroException Handles errors generated from dividing a dividend with zero.
System.InvalidCastException  Handles errors generated during typecasting.


3. Ques:  What is the difference between system exceptions and application ?
Answer:
 System.SystemException -> This class is for exceptions that r usually thrown by the .net run time, or which r considered to be of a generic nature and must be thrown by almost any application. For example, StackOverflowException will be thrown by the .net run time if it detects the stack is full.

 System.ApplicationException-> This class is important, because it is the intended base for any class of exception defined by third parties. Hence, if u define any exceptions covering error conditions unique to your application, u should derive these directly or indirectly from System.ApplicationException.


4. Ques:  What is the difference between object pooling and connection pooling ?
Answer:
  • object pool implementation will increase the size of the pool up to the specified maximum. When the maximum is reached, unlike the example above, 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.
  • 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).
  • With object pooling, you maintain a pool of objects in memory.
  • Connection pooling does the same thing with connections to a database.

5. Ques:  What is Extension methods in C# ? What is Benefits of extension methods ?
Answer:
Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. An extension method is a special kind of static method, but they are called as if they were instance methods on the extended

An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.
Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.

Important points for the use of extension methods are given as
  • An extension method must be defined in a top-level static class.
  • An extension method with the same name and signature as an instance method will not be called.
  • Extension methods cannot be used to override existing methods.
  • The concept of extension methods cannot be applied to fields, properties or events.
  • Overuse of extension methods is not a good style of programming.
Benefits of extension methods
  • Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code.
  • If the class is sealed than there in no concept of extending its functionality. For this a new concept is introduced, in other words extension methods.
  • This feature is important for all developers, especially if you would like to use the dynamism of the C# enhancements in your class's design.

6. Ques:  What is Marshalling?
Answer:
Marshaling is the process of creating a bridge between managed code and unmanaged code; it is the homer that carries messages from the managed to the unmanaged environment and reverse. It is one of the core services offered by the CLR (Common Language Runtime.)


7. Ques:  What is difference between Serialization and Marshaling ?
Answer:
Serialization
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file, a memory buffer, or transmitted across a network connection to be "resurrected" later in the same or another computer environment. And this sequence of bits can be of any format the user chooses; however, they are usually formed as XML or binary.

Serialization comes in many forms in .NET Framework, it can be observed in ADO.NET, Web services, WCF services, Remoting, and others.

For example, calling the WriteXml() function of a DataSet serializes this DataSet into a XML file.

ds.WriteXml("data.xml");

Marshaling
Marshaling is the process of converting managed data types to unmanaged data types. There're big differences between the managed and unmanaged environments. One of those differences is that data types of one environment is not available (and not acceptable) in the other.

For example, you can't call a function like SetWindowText() -that sets the text of a given window- with a System.String because this function accepts LPCTSTR and not System.String. In addition, you can't interpret (handle) the return type, BOOl, of the same function, that's because your managed environment (or C# because of the context of this writing) doesn't have a BOOL, however, it has a System.Boolean.


8. Ques:  What are the New Features in C# 6.0 ?
Answer:
The New Features in C# 6.0 listed bellow
  • using Static.
  • Auto property initializer.
  • Dictionary Initializer.
  • nameof Expression.
  • New way for Exception filters.
  • await in catch and finally block.
  • Null – Conditional Operator.
  • Expression – Bodied Methods
  • Easily format strings – String interpolation

9. Ques:  What is Dynamic language runtime (DLR) in Dot net ?
Answer:
The dynamic language runtime (DLR) is a runtime environment that adds a set of services for dynamic languages to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages to run on the .Net Framework and to add dynamic features to statically typed languages."

The dynamic language runtime (DLR) is a runtime environment that adds a set of services for dynamic languages to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages.
Dynamic languages can identify the type of an object at run time, whereas in statically typed languages such as C# and Visual Basic (when you use Option Explicit On) you must specify object types at design time. Examples of dynamic languages are Lisp, Smalltalk, JavaScript, PHP, Ruby, Python, ColdFusion, Lua, Cobra, and Groovy.

Advantages of dynamic languages 
  • The ability to use a rapid feedback loop (REPL, or read-evaluate-print loop). This lets you enter several statements and immediately execute them to see the results.
  • Support for both top-down development and more traditional bottom-up development. For example, when you use a top-down approach, you can call functions that are not yet implemented and then add underlying implementations when you need them.
  • Easier refactoring and code modifications, because you do not have to change static type declarations throughout the code.

10. Ques: What is type-safe in .net?
Answer:
Type-safe code accesses only the memory locations it is authorized to access. For example, type-safe code cannot read values from another object's private fields. It accesses types only in well-defined, allowable ways.

During just-in-time (JIT) compilation, an optional verification process examines the metadata and Microsoft intermediate language (MSIL) of a method to be JIT-compiled into native machine code to verify that they are type safe. This process is skipped if the code has permission to bypass verification

Verification of type safety is not mandatory to run managed code, type safety plays a crucial role in assembly isolation and security enforcement. When code is type safe, the common language runtime can completely isolate assemblies from each other. This isolation helps ensure that assemblies cannot adversely affect each other and it increases application reliability.

Thursday, 9 March 2017

C# basic interview questions Part-7

1. Ques: Explain All the version (history) of C# ?
Answer:
C# is powerful object-oriented programming language developed by Microsoft.its first release in 2000. C# was introduced with .NET Framework 1.0 and the current version of C# is 6.0.

C# 1.0:
  • C# 1.0 was released by Microsoft with Visual Studio 2002. C# 1.0 targets .NET Framework 1.0. It was the first language adopted by developers to build .NET applications.
C# 1.2
  • C# 1.2 was released by Microsoft with Visual Studio 2003. C# 1.2 targets .NET Framework 1.1.
C# 2.0
  • C# 2.0 was released by Microsoft with Visual Studio 2005. C# 2.0 targets .NET Framework 2.0.
  • The new features added in C# 2.0 are as given below:
  • Generics
  • Partial types
  • Anonymous methods
  • Iterators
  • Nullable types
  • Private setters (properties)
  • Method group conversions (delegates)
  • Covariance and Contravariance

C# 3.0
  • C# 3.0 was released by Microsoft with Visual Studio 2008. It is also compatible with Visual Studio 2010. C# 3.0 targets the .NET Framework 2.0 (Except LINQ/Query Extensions), .NET Framework 3.0 (Except LINQ/Query Extensions) and .NET Framework 3.5.
  • The new features added in C# 3.0 are as given below:
  • Implicitly typed local variables (var)
  • Object and collection initializers
  • Auto-Implemented properties
  • Anonymous types
  • Extension methods
  • Query expressions
  • Lambda expressions
  • Expression trees
  • Partial Methods
  • LINQ

C# 4.0
  • C# 4.0 was released by Microsoft with Visual Studio 2010. C# 4.0 targets .NET Framework 4.0.
  • The new features added in C# 4.0 are as given below:
  • Dynamic binding (Late binding)
  • Named and optional arguments
  • Generic Covariance and Contravariance
  • Embedded interop types ("NoPIA")

C# 5.0
  • C# 5.0 was released by Microsoft with Visual Studio 2012. C# 5.0 targets .NET Framework 4.5.
  • The new features added in C# 4.0 are as given below:
  • Asynchronous methods
  • Caller info attributes

C# 6.0
  • Expression Bodied Methods
  • Auto-property initializer
  • nameof Expression
  • Primary constructor
  • Await in catch block
  • Exception Filter
  • String Interpolation


2. Ques: Difference between value type and reference types ?
Answer:
Value Type
  • Value Type stored on stack.
  • Value Type Contains actual value.
  • Cannot contain null values. However this can be achieved by nullable types.
  • Value type is popped on its own from stack when they go out of scope.
  • Memory is allocated at compile time.
  • In value types, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other.
  • Value types are derived from System.ValueType.
Reference Type
  • Reference Type stored on heap
  • Reference Type Contains reference to a value.
  • Can contain null values.
  • Required garbage collector to free memory.
  • Memory is allocated at run time.
  • In reference types, it is possible for two variables to reference the same object and thus possible for operations on one variable to affect the object referenced by the other variable.
  • Reference types are derived from System.Object.


3. Ques:  What are params in c# ? What is the use of params in C#?
Answer:
Params enables methods to receive variable numbers of parameters. With params, the arguments passed to a method are changed by the compiler to elements in a temporary array. This array is then used in the receiving method.
Ex:

class Program
{
  static void Main()
    {
        // Call params method with one to four int arguments.
        int sum1 = SumParameters(1);
        int sum2 = SumParameters(1, 2);
        int sum3 = SumParameters(3, 3, 3);
        int sum4 = SumParameters(2, 2, 2, 2);
    }

    static int SumParameters(params int[] values)
    {
        // Loop through and sum the integers in the array.
        int total = 0;
        foreach (int value in values)
        {
            total += value;
        }
        return total;
    }
}

By using the params keyword, you can specify a method parameter that takes a variable number of arguments. You can send a comma-separated list of arguments of the type specified in the parameter declaration or an array of arguments of the specified type.


4. Ques:  What is the difference between Array and Collection?
Answer:
Array 
  • You need to specify the size of an array at the time of its declaration.It can not be resized.
  • The member of an array should be of the same data type.
  • Array is strong type. 
Collection
  • The size of a collection can be adjusted dynamically as per users requirement.It does not have fixed size
  • Collection can have different data types.
  • Collection is not strong type.

5. Ques:  What is the difference between managed and unmanaged code?
Answer:
Managed Code
  • Code which is executed by CLR (Common Language Runtime) is called Managed Code, any application which is developed in .Net framework is going to work under CLR, the CLR internally uses the Garbage Collector to clear the unused memory and also used the other functionalities like CTS, CAS etc.
  • managed code executed on fixed location in memory.
  • it  get advantages of CLR like memory management, thread managament,security, garbage mechanism etc.
Unmanaged Code
  • The unmanaged code is basically developed using other languages (other than .Net Framework), so it uses its own language runtime to execute the applications. The application runtime will take care of its memory management, security etc.
  • unmanaged code executes on random location in memory.
  • it doesn't get advantages of CLR like memory management, thread managament,security, garbage mechanism etc.

6. Ques: What is the use of using statement in C# ?
Answer:
The using statement is used to obtain a resource, execute a statement, and then dispose of that resource.

There is 2  main use using statement. 
1:- Importing namespace example:using System; 
2:- Dispose the object  
 using(SqlConnection oConnection=new SqlConnection()) { oConnection.Open(); } 
if you won't close the connection it will close the connection automatically once SqlConnection has been executed completing.



7. Ques: What is Delegates in C# ? What is Use of Delegates ?
Answer:
Delegates in c# are type safe objects which are used to hold reference of one or more methods in c#.net. Delegates concept will match with pointer concept of c++ .
The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked

Whenever we want to create delegate methods we need to declare with delegate keyword and delegate methods signature should match exactly with the methods which we are going to hold like same return types and same parameters otherwise delegate functionality won’t work if signature not match with methods.

Delegates are two types
Single Cast Delegates
Multi Cast Delegates

Single Cast Delegates
Single cast delegate means which hold address of single method like as explained in above example.

Multicast Delegates
Multi cast delegate is used to hold address of multiple methods in single delegate. To hold multiple addresses with delegate we will use overloaded += operator and if you want remove addresses from delegate we need to use overloaded operator -=

Multicast delegates will work only for the methods which have return type only void. If we want to create a multicast delegate with return type we will get the return type of last method in the invocation list


8. Ques: What is the use of “Yield” keyword in C#?  What is use the of “Yield” keyword ?
Answer:
Yield helps you to provide custom stateful iteration over .NET collections.”

Use of “yield” keyword is
  • Customized iteration through a collection without creating a temporary collection.
  • Stateful iteration.
There are a few things to note when defining a function that uses yield. The yield statement can only appear inside an iterator block, which can be implemented as the body of a method, operator, or accessor. The body of such methods, operators, or accessors is controlled by the following restrictions:
  • Unsafe blocks are not allowed.
  • Parameters to the method, operator, or accessor cannot be ref or out.
  • A yield return statement cannot be located anywhere inside a try-catch block. It can be located in a try block if the try block is followed by a finally block.
  • A yield break statement may be located in a try block or a catch block but not a finally block.

9. Ques:  What is the Task Parallel Library (TPL) in C#? 
Answer:
Task Parallel Library is new API's to simplify the process of adding parallelism and concurrency to applications. This set of API's is called the "Task Parallel Library (TPL)" and is located in the System.Threading and System.Threading.Tasks namespaces.
The Parallel class found in the System.Threading.Tasks namespace “provides library-based data parallel replacements for common operations such as for loops, for each loops, and execution of a set of statements”. In this article, we will use the  Invoke method of the Parallel class to call multiple methods, possibly in parallel.
 
   TPL handles the partitioning of the work, the scheduling of threads on the ThreadPool, cancellation support, state management, and other low-level details. By using TPL, you can maximize the performance of your code while focusing on the work that your program is designed to accomplish.

Tuesday, 7 March 2017

C# basic interview questions Part-6

1. Ques: What is design patterns ? How many design Patterns in Software Architecture ?
Answer:
Design patterns provide general solution to commonly occurring design problem. Design Patterns provide efficient solutions to software design and programming problems that are re-usable in your code. Software Architects and developers use them to build high quality robust applications.

Creational Patterns : These patterns deals mainly with creation of objects and classes.
  • Abstract Factory Pattern: Create instances of classes belonging to different families
  • Builder Pattern: Separate representation and object construction
  • Factory Method Pattern: Create instances of derived classes
  • Prototype Pattern: Clone or copy initialized instances
  • Singleton Pattern: Class with only one single possible instance

Structural Patterns : These patterns deals with Class and Object Composition.
  • Adapter Pattern: Match interfaces of classes with different interfaces
  • Bridge Pattern:: Separate implementation and object interfaces
  • Composite: Simple and composite objects tree
  • Decorator: Dynamically add responsibilities to objects
  • Facade: Class that represents subclasses and subsystems
  • Flyweight: Minimize memory usage by sharing as much data as possible with similar objects
  • Proxy: Object that represents another object

Behavioral Patterns : These mainly deals with Class - Object communication. That means they are concerned with the communication between class and objects.
  • Chain of Responsibility: Pass requests between command and processing objects within a chain of objects
  • Command: Encapsulate a method call as an object containing all necessary information
  • Interpreter: Include language elements and evaluate sentences in a given language
  • Iterator: Give sequential access to elements in a collection
  • Mediator: Encapsulates and simplifies communication between objects
  • Memento: Undo modifications and restore an object to its initial state
  • Observer: Notify dependent objects of state changes
  • State: Change object behavior depending on its state
  • Strategy: Encapsulate algorithms within a class and make them interchangeable
  • Template Method: Define an algorithm skeleton and delegate algorithm steps to subclasses so that they may be overridden
  • Visitor: Add new operations to classes without modifying them


2. Ques: What is solid principle in software development?
Answer:
S.O.L.I.D is an acronym for the first five object-oriented design principles by Robert C. Martin, popularly known as Uncle Bob.
S.O.L.I.D stands for:
  • S – Single-responsiblity principle
  • O – Open-closed principle
  • L – Liskov substitution principle
  • I – Interface segregation principle
  • D – Dependency Inversion Principle

Single-responsibility Principle:
A class should have one and only one reason to change, meaning that a class should have only one job.

Open-closed Principle
Objects or entities should be open for extension, but closed for modification.

Liskov substitution principle
Object of a derived class should be able to replace an object of the base class without bringing any errors in the system or modifying the behavior of the base class.

Interface segregation principle
A client should never be forced to implement an interface that it doesn’t use or clients shouldn’t be forced to depend on methods they do not use.

Dependency Inversion principle
Entities must depend on abstractions not on concretions. It states that the high level module must not depend on the low level module, but they should depend on abstractions.


3. Ques: What is Dependency Injection Pattern in C# ? What are the advantages of Dependency Injection pattern ?
Answer:
Dependency Injection (DI) is a software design pattern that allow us to develop loosely coupled code. DI also enables us to better manage future changes and other complexity in our software. Loose coupling offers us greater re usability, maintainability and test ability.

Advantages of Dependency Injection pattern
The main advantage of DI is, it makes our code more reusable, maintainable, testable and readable.

There are three basic type of Dependency Injection

Constructor Injection
  • Dependency Injection is done by class’s constructor when instantiating that class.
  • Injected component can be used anywhere within the class.
  • Should be used when the injected dependency is required for the class to function.
  • It addresses the most common scenario where a class requires one or more dependencies.
Advantages of Constructor Injection:

Construction Injection makes a strong dependency contract
Construction Injection supports testing, because dependencies can be passed in the constructor.
A dependency may be made immutable by making the dependency reference final by means that it prevents circular dependency.

Property injection
  • It also called Setter injection.
  • It used when a class has optional dependencies, or where the implementations may need to be swapped. Different logger implementations could be used this way.
  • May require checking for a provided implementation throughout the class.
  • Does not require adding or modifying constructors.
Method injection
  • Inject the dependency into a single method, for use by that method.
  • Could be useful where the whole class does not need the dependency, just the one method.
  • Generally uncommon, usually used for edge cases.

4. Ques: What is Pass By Reference? and  What is Pass By Reference Pass By Value?
Answer:
Pass By Reference:The calling functions passes the address of the variable instead of the actual values.Any 
changes made inside the actual method will be reflected in the calling function.

Pass By Value :Actual value is copied to another variable

5. Ques: What is enum ?
Answer:
An enum is a value type with a set of related named constants often referred to as an enumerator list. 
The enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined.
enumerations are value data type.Enums type can be integer (float, int, byte, double etc.). But if you used beside int it has to be cast.
ex:
enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };



6. Ques: What is Singleton Design Patterns and How to implement in C#? 
Answer:
Singleton Design Pattern:-In this  a class has only one instance and provides a global point of access to it. 
A singleton is a class that only allows a single instance of itself to be created, and usually gives simple access to that instance. 
Most commonly, singletons don't allow any parameters to be specified when creating the instance, since a second request of an instance with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter then the factory pattern is more appropriate.) 
There are various ways to implement the Singleton Pattern in C#. The following are the common 

Key point  of a Singleton Pattern.  
  • A single constructor, that is private and parameter less.
  • The class is sealed.
  • A static variable that holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary. 

7. Ques: How to use Nullable<> Types in .Net?  
Answer: 
A nullable Type is a data type is that contain the defined data type or the value of null. 
This nullable type concept is not compatible with "var".



8. Ques: What is the difference between a process and a thread?
Answer: 
Threads :
  • A thread is a subset of the process.
  • 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.
  • Threads share the address space of the process that created it; 
  • Threads have direct access to the data segment of its process.
  • Threads can directly communicate with other threads of its process.
  • New threads are easily created; 
  • Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; 
Process :
  • An executing instance of a program is called a process.
  • A process is always stored in the main memory also termed as the primary memory or random access memory.
  • processes have their own address space.
  • processes have their own copy of the data segment of the parent process.
  • processes must use interprocess communication to communicate with sibling processes.
  • new processes require duplication of the parent process.
  • changes to the parent process do not affect child processes.

9. Ques: What are the properties of Delegate in C# ?
Answer: 
Delegates are similar to C++ function pointers, but are type safe.
Delegates allow methods to be passed as parameters.
Delegates can be used to define callback methods.
Delegates can be chained together; for example, multiple methods can be called on a single event.
Methods don't need to match the delegate signature exactly. For more information, see Covariance and Contra variance.
C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method.

Tuesday, 28 February 2017

C# basic interview questions Part-5

1. Ques : What are the advantages of generics?
Answer:
Generics has following advantages
  • It allows creating class, methods which are type-safe
  • It is faster. Because it reduce boxing/un-boxing
  • It increase the code performance
  • It helps to maximize code reuse, and type safety

2. Ques : What is extension methods and where can we use it?
Answer:
Extension methods provide a feature 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 scope and you can call it like a regular instance method.
Extension methods need to be declared in a non generic, non-nested, static class.


3. Ques : What is difference between the “throw” and “throw ex” in .NET?
Answer:
  • throw : It throws the original exception and preserves its original stack trace.
  • throw ex: It throws the original exception but resets the stack trace, destroying all stack trace information until your catch block.

4. Ques : Can you serialize hashtable ?
Answer
No, You can’t Serialize Hash table.Because, In the C# serialization of any object not possible  that implements the IDictionary interface.


5. Ques : What is the difference between Debug.Write and Trace.Write in C#?
Answer
Debug.Write
  • It uses the Debug class.
  • It uses the time of application development.
  • It works only in debug mode.
  • It is used while debugging a project.
  • It runs in the same thread as main program executes.
  • It is used to find errors in the program.
  • If 'DEBUG' is defined during the compilation, Debug.Write will be emitted.
Trace.Write
  • It uses the Trace class.
  • It uses the time of application deployment.
  • It works in both case debug and release mode.
  • It is used in releasing version of applications.
  • It runs in different thread form main program execute thread.
  • It is used for testing and optimization even after an application is compiled and released.
  • If 'TRACE' is defined during the compilation, Trace.Write will be emitted.

6. Ques: What is the difference between an EXE and a DLL?
Answer:
EXE:
  •  Executable file can run independently.
  •  It runs in a separate process.
  •  It can’t be reused in application.
  •  it has a main function.
  • Can be started as stand alone.
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 application.
  • It does not have a main function.
  • Cannot be started as stand alone.

7. Ques:  What is strong name in .net ?
Answer:
A strong name consists of the assembly's identity  its simple text name, version number, and culture information,  a public key and a digital signature.


8. Ques: What is delay signing Dot Net ?
Answer:
Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the public key.This allows the assembly to be signed with the private key at a later stage, when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to work with shared assemblies as if they were strongly named, and it secures the private key of the signature from being accessed at different stages of development.


9 Ques: What is side by side execution in .net ?
Answer:
Side-by-side execution is the ability to run multiple versions of an application or component on the same computer. You can have multiple versions of the common language runtime, and multiple versions of applications and components that use a version of the runtime, on the same computer at the same time.


10 Ques: Can we have different access modifiers on get/set methods of a property ?
Answer:
No we can not have different modifiers same property. The access modifier on a property applies to both its get and set accessors.

Tuesday, 21 February 2017

C# basic interview questions Part-4

1. Ques: What is indexer ?
Answer:
Indexer Concept is object act as an array.When you define an indexer for a class, this class behaves similar to a virtual array. You can then access the instance of this class using the array.
  • An indexer is also similar to a property.
  • Indexer an object to be indexed in the same way as an array.
  • Indexer modifier can be private, public, protected or internal.
  • The return type can be any valid C# types.
  • Indexers in C# must have at least one parameter. Else the compiler will generate a compilation error.
public dataType this[int index]
{
    get
    {
         return aValue;
    }
    set
    {
    }
}

2. Ques: What is the difference between string and StringBuilder in c#?
Answer:
String:-
  • It’s an immutable. means once we create its object of string and if we modify it will create new instances.
  • Any action it will create new instance every time.
  • We don’t have any append keyword in string.
  • During string concatenation, additional memory will be allocated.
  • It is under System namespace.
  • Performance wise string is slow.
StringBuilder:-
  • StringBuilder is mutable.
  • StringBuilder will use same instance of object to perform any action
  • we can use append keyword along with StringBuilder.
  • During string concatenation, additional memory will be allocated if and only if the string buffer’s capacity is reached.
  • Stringbuilder belongs to System.Text namespace
  • StringBuilder gives better performance while performing repeated operation over a string. 

3. Ques: What are the differences between IEnumerable and IQueryable?
Answer:
IEnumerable:-
  • IEnumerable exists in the System.Collections namespace.
  • IEnumerable is suitable for querying data from in-memory collections like List, Array and so on.
  • IEnumerable doesn’t move between items, it is forward only collection.
IQueryable:-
  • IQueryable exists in the System.Linq Namespace.
  • IQueryable is suitable for querying data from out-memory (like remote database, service) collections.
  • If we need to do any manipulation with the collection like Dataset and other data sources, use IQueryable. 

4. Ques:  What is difference between is and as operator in C# ?
Answer:
"is" operator to check the object type. If the two objects are of the same type, it returns true and false if not.
"as" operator to check the object type. If the two objects are of the same type, it returns object else it returns null.


5. Ques: What is Automapper ?
Answer:
AutoMapper is an object-to-object mapper, which allows you to solve issues with mapping of the same properties in one object of one type to another object of another type.


6. Ques: How do install and uninstall assembly in GAC ?
Answer:
install- gacutil -i <assembly name>
uninstall-gacutil -u <assembly name>


7. Ques: What is Just In Time Compiler in dot net framework ?
Answer:
It is a compiler which converts MS IL (Microsoft Intermediate Language) code to Native Code (i.e. CPU-specific code that runs on the same computer architecture). Just-In-Time compiler- it converts the language that you write in .Net into machine language that a computer can understand.

There are 3 types of JITs
  • Pre-JIT compiler (Compiles entire code into native code completely in a single Operation)
  • Econo JIT compiler (Compiles only methods(Code) called at Runtime)
  • Normal JIT compiler (Compiles only that part of code called at Runtime and places in cache)

8. Ques: What are the advantages and disadvantages of get and set properties in C#?
Answer:
Advantages of properties (get/set):
  • Ability to add code later on without recompiling assemblies that reference this.
  • Ability to provide private/protected/internal set and public get (or any other combination).
  • Public fields are not CLS compliant.
Disadvantages of properties (get/set):
  • Slower to access (both read and write).
  • Can't pass as ref arguments to methods.

9. Ques: Do events have return type ?
Answer:
No, events do not have return type. 


10. Ques: Can event’s have access modifiers ?
Answer:
Event’s are always public as they are meant to serve every one registering to it. But you can access modifiers in events.You can have events with protected keyword which will be accessible only to inherited classes.You can have private events only for object in that class. 

Saturday, 11 February 2017

C# basic interview questions Part-3

1. Ques: What is the difference between Var and Dynamics in C# ?
Answer:
var :
  • var keyword type variable is decided by the compiler at compile time. So it is strongly typed variable.
  • var type of variables are required to be initialized at the time of declaration or otherwise it will give compile time error: e.g., var str=”I am a var variable”; 
  • It throw an Errors at compile time.
  • var variables cannot be used for property or return values from a function. They can only be used as local variable in a function.
  • Introduced in C# 3.0
dynamic:
  • dynamic keyword type variable is decided by the compiler at run time.So it is dynamically typed variable.
  • In dynamic type variable No need to initialize at the time of declaration.e.g., dynamic strr;
  • It throw an Errors at run time.
  • dynamic variables can be used to create properties and return values from a function.
  • Introduced in C# 4.0.

2. Ques: What is tuples ? When we use Tuples in C#?
Answer:
  • Tuple is new in c# 4.0.
  • A tuple allows you to combine multiple values of different types into a single object without having to create a class.
  • Tuple provides us to group elements of diffrent data type together.
  • Tuple are reference types.
  • We can create a Tuple using the Create method. This method provide to 8 overloads, so we can use a maximum of 8 data types in it. 
ex: var tuplevar= new Tuple<string, string, int>("India","mumbai",400001);

var tuplevar= Tuple.create<string, string, int>("India","mumbai",400001);

to get list item from tuplee use as
geo.Item1; //state
geo.Item2; //city
geo.Item3;//pincode

Advantages 
Tuple returns multiple values from a method.
It provides an alternative to "ref" or "out" if method that needs to return multiple new objects.


3. Ques: What is the difference between string and String Builder in c#? 
Answer:
String:-
  • String is immutable. means once we create string object we cannot modify. Any operation like insert, replace or append happened .it will create new instance in memory to hold the new value.
  • String class come under System namespace.
  • It performance degrades when continuous change of value occurs
String builder
  • String builder is mutable it means once we create string builder object we can perform any operation like insert, replace or append without creating new instance for every time.
  • String builder class come under System namespace.Text.
  • It shows better performance because any new changes are made to existing instance.

4. Ques: Difference between Direct casting, is and as operator in C# ?
Answer:
Direct casting: Direct cast is most common way of casting one type to another, however it yields exception if casting can’t be done.

Is operator: Is operator checks whether an object is compatible with given type and if it is true (if casting can be done) or false (if casting can’t be done)

As operator: As operator is like a casting except that it yields null on conversion failure instead of raising an exception. So run time exception can be avoided using null check.


5. Ques: What are the differences between Const & Readonly ?
Answer:
Const :
  • Const can only be initialized at the time of declaration of the field.
  • Const values will evaluate at compile time only.
  • Const value can’t be changed these will be same at all the time.
  • Can't be static.
  • This type of fields are required when one of the field values remains constant throughout the system like Pi will remain same in your Maths Class.

Readonly :
  • The value will be initialized either declaration time or the constructor of the class allowing you to pass the value at run time.
  • Read only values will evaluate at runtime only.
  • Can be either instance-level or static.

6. Ques: How many types of collection in C#?
Answer:
There are the 2 types of collections:
1.Generic
2.Non-Generic


Generic
Non-generic  
   ArrayList    

         List
HashTable  
       Dictionary

SortedList  

       SortedList  
Stack           
        Stack

Queue        
       Queue














7. Ques: What are generics in C#.NET?
Answer:
Generics are the most powerful feature of C# 2.0.
Generic types to maximize code reuse, type safety, and performance.
They can be used to create collection classes.
Generic collection classes present in the System.Collections.Generic namespace.


8. Ques: What are the advantage generics in C#.NET?
Answer:
Generics is advantageous as:
- its provide type safety.
- its improved performance.
- its reduced the code.
- They promote the usage of parameterized types.
- it is type-safe data. there is no boxing & unboxing requred with Generic type.
- Code Re-usability provide by Generics.

9. Ques:  What is the difference between break and continue statement?
Answer:
The break statement is used to terminate the current enclosing loop or conditional statements in which it appears. We have already used the break statement to come out of switch statements.
The continue statement is used to alter the sequence of execution. Instead of coming out of the loop like the break statement did, the continue statement stops the current iteration and simply returns control back to the top of the loop.
        

Monday, 30 January 2017

C# basic interview questions Part-2

1. Ques: What is an interface in c#  and what are the advantages of interface ?
Answer:
An interface  is a type  which contains only the signatures of methods, properties, events or indexers.it has no implementation.The class contract with Interface has resposible for Implementation of the signatures of methods, properties.
  • An Interface is a reference type.
  • It does not Contains any data members.
  • No access modifier apply in interface.
  • By Default interface members is public. 
  • It Supports multiple interfaces.
Advantages of  an interface
  • Only Multiple interface supported in C#.but Multiple inheritance not supported.
  • For creating loosely coupled module.
  • Allow different objects to interact easily.
  • Extensibility.
  • Interface help for Dependency injection and inversion of control

2. Ques: What is Garbage Collection ?
Answer:
  • Garbage Collector is part of CLR in .Net Framework which is responsible to Automatic Memory Management.
  • It is collect all unused memory area and give to application to realeae the memory.
  • Garbage Collector use a system.gc.collect() method for release the memory.
  • Garbage Collector dived the heap memory into three Generation Generation 0, Generation  1, Generation 2.
  • It check the object which is short live or long live and put that object into Generation 0,1,2 respectvley.
  • garbage collector does not clean unmanaged objects it clean only managed objects.
Generation 0 (Zero): short-lived objects store in this Generation, e.g., Temporary objects. GC initiates garbage collection process frequently in this generation.
Generation 1 (One): This generation is the buffer between short-lived and long-lived objects.
Generation 2 (Two): This generation holds long-lived objects like a static and global variable.

Garbage collection happend when any one of the following conditions is true:
The system has low physical memory.
The GC.Collect method is called.


3. Ques: What is CLR ?
Answer:
Common Language Runtime (CLR) is the heart of the dot Net framework. it provides run time environment to run all the dot Net Programs. it execute MSIL (Microsoft Intermediate Language) code to native code. The code which runs under the CLR is called as Managed Code.

CLR  provides a common set of services in dot Net framework
Memory management (using Garbage Collector): it relesed unuesed obect from heap memory.
Exception handling and errors: It is allows create code and handle the exceptions.
Security managment : CLR provide Code Access Security (CAS) which restrict to run unauthorized code.
Thread management: Allows to run multiple threads of execution.
JIT compiler: JIT is part of CLR which convert MSIL code into native code.
Type loading:  Finds and loads assemblies and types.
Type safety:  It Ensures the references match compatible types.
Code Manager:  It manages the code at run time.
Class Loader: Used to load all classes at run time.


4. Ques: What is the CLS (Common Language Specification)?
Answer:
Common Language Specification and it is a subset of CTS. It defines a set of rules and restrictions that every language must follow which runs under .NET framework. CLS enables cross-language integration. CLS represents the guidelines to the compiler of a language, which targets the .NET Framework.


5. Ques: What is the CTS ?
Answer:  
Common Type System (CTS) defines a set of types that can use different dot Net languages, and after compilation of different  dot Net languages it treated as single type. It enables cross-language integration, type safety, and high-performance code execution. It provides an object-oriented model for implementation of many programming languages.


6. Ques: What is difference between dispose and finalize method in c# ?
Answer:  
Dispose
it is used to free unmanaged resources like files, database connections, unmanaged memory etc. at any time.
it is called by User Code. So we can say that it called Explicitly.
Dispose() method belongs to IDisposable interface.
Performance of application not affected with Dispose method.

finalize 
it is used to free unmanaged resources like files, database connections, unmanaged memory etc etc. before object is destroyed.
it is called by Garbage Collector. so we can say that it called Internally.
finalize() method belongs to object class.
Performance of application is affected with finalize method.


7. Ques: What is GAC ? What are the steps to create an assembly and add it to the GAC ?
Answer:
The global assembly cache (GAC) is a Directory that stores assemblies that is shared by several applications on the computer. You should share assemblies by installing them into the global assembly cache.

Steps for installing
  • Create a strong name using sn.exe tool eg: sn -k mykey.snk
  • in AssemblyInfo.cs, add the strong name eg: [assembly: AssemblyKeyFile("mykey.snk")]
  • recompile project, and then install it to GAC in two ways :
  • drag & drop it to assembly folder (C:\WINDOWS\assembly OR C:\WINNT\assembly) (shfusion.dll tool)
  •  gacutil -i abc.dll

8. Ques: What is a strong name?
Answer:
You need to assign a strong name to an assembly to place it in the GAC and make it globally accessible. A strong name consists of a name that consists of an assembly's identity (text name, version number, and culture information), a public key and a digital signature generated over the assembly.  The .NET Framework provides a tool called the Strong Name Tool (Sn.exe), which allows verification and key pair and signature generation.


9. Ques: Is it possible to force garbage collector to run?
Answer:
Yes, we can force garbage collector to run using System.GC.Collect().
It can be used to avoid calling any of the collect methods and allow the garbage collector to run independently.
It is better at determining the best time to perform a collection.

Sunday, 29 January 2017

C# basic interview questions Part-1

1. Ques: What are the version numbers of C# ? 
Answer:


Version
.NET Framework
C# 1.0
.NET Framework 1.0/1.1
C# 2.0
.NET Framework 2.0
C# 3.0
.NET Framework 3.0\3.5
C# 4.0
.NET Framework 4.0
C# 5.0
.NET Framework 4.5
C# 6.0
.NET Framework 4.6


2. Ques: What is difference between Dictionary & Hashtable ?
Answer:
Dictionary:
1.Dictionary is generic type.
2.Returns an error if the key does not exist.
3.No boxing and unboxing.
4.Faster than a Hash table.
5.dictionary is not tread safe.

Hashtable:
1.Hashtable is not generic type.
2.Returns NULL even if the key does not exist.
3.Requires boxing and unboxing.
4.Slower than a Dictionary.
5.hash table is not a generic type.
6.hash table is tread safe.


3. Ques: What is Reflection in dot net? 
Answer:
  • Reflection used for obtaining type information of assembly at runtime. 
  • It Load assemblies at runtime and give the information of field,properties, constructors, event and methods of class.
  • It is a collection of classes which allow u to query assembly (class/object) metadata at runtime.
  • Using reflection we can also create new types and their instances at runtime and invoke methods on these new instances.
  • At runtime, the Reflection mechanism uses the PE file to read information about the assembly.
  • We can dynamically invoke methods using System.Type.Invokemember
  • We can dynamically create types at runtime using System.Reflection.Emit.TypeBuilder
  • Reflection objects are used for obtaining type information at runtime. 
  • The classes belong to the System.Reflection namespace.
With reflection we can do the below task

  • we can dynamically create an instance of a type
  • bind the type to an existing object
  • get the type from an existing object
  • invoke its methods or access its fields and properties



4. Ques: What are Assemblies?
Answer:
Assembly is the smallest unit of deployment of a .net application. 
It can be either dll or an exe.

5. Ques: How many type of assembly are in .net framework?
Answer:
There are three type of assembly in .net framework?
Private: It is stored in the application's directory. 
Shared : It is stored in GAC (Global Assembly Cache).
Satelite : It is stored in specific application's directory.


6. Ques: What is array?
Answer:
  • Array as a collection of variables of the same type of fixed-size. 
  • Array are reference types.
  • array strongly type of collection.
  • arrays belong to "System.Array" namespace

ex:  int[] arr = new int[10];
       string[] arr = new string[10];
       bool[] arr = new bool[2];



7. Ques:What are different type of array in c#?
Answer : Three types  of array in C#:
Single Dimensional Array: It contains a single row. It is also known as vector array.
Multi Dimensional Array: It is rectangular and contains rows and columns.
Jagged Array: In Jagged Array the element is itself is array. It also contains rows and columns but it has an irregular shape.


8. Ques: How to create jagged arrays in c#?
Answer :
int[][] jagrray= new int[4][];
jagrray [0] = new int[5];
jagrray[1] = new int[3];
jagrray[2] = new int[2];
jagrray[3] = new int[1];

for (int i = 0; i < jagrray.Length; i++)
    {
        int[] innerArray = jagrray[i];
        for (int j = 0; j < innerArray.Length; j++)
        {
            Console.Write(innerArray[j] + " ");
        }
        Console.WriteLine();
    }


9. Ques: What is Arraylist?
Answer:
  • Arraylist collection of variables of same or different datatypes. 
  • Arraylist class found in "System.Collections” namespace.
  • Size of arraylist object will increase or decrease dynamically.
  • Arraylist very flexible because we can add & delete without any size information.
  • Arraylist not a strongly type of collection. 

10. Ques: What is a collection.how many types of collection in C#?
Answer:
Collections are data structures that holds data or objects in memory.
list of collection which supported by C# given bellow.
ArrayList
HashTable
SortedList
BitArray
Queue
Stack