Advanced .Net Interview Questions


Can static constructors use optional arguments?

As MSDN says, A static constructor is called automatically to initialize the class before the first instance is created. Therefore you can’t send it any parameters. If the CLR must call a static constructor how will it know which parameters to pass it?

Name design patterns and principles you know and how they are utilized in .NET Framework?

Creational Design Pattern
Factory Method, Abstract Factory, Builder, Prototype, Singleton
Structural Design Patterns
Adapter, Bridge, Composite, Decorator, Façade, Flyweight, Proxy
Behavioral Design Patterns
Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Visitor, Template Method

What is boxing and unboxing? What are the performance implications?

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit.

Performance
In relation to simple assignments, boxing and unboxing are computationally expensive processes. When a value type is boxed, a new object must be allocated and constructed. To a lesser degree, the cast required for unboxing is also expensive computationally.

What is shadowing and overriding, when do you prefer to use one over the other?

There is no control of a base class on shadowing. In other words, a base class element cannot enforce or stop shadowing. … The same as shadowing, overriding an element is inherited further in a derived class and the overridden element is still overridden. In shadowing, the signature of an element could be different.

What is Marshalling?

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)

How to create a shared assembly or add an assembly to GAC?

A shared assembly is an assembly that resides in a centralized location known as the GAC (Global Assembly Cache) and that provides resources to multiple applications. If an assembly is shared then multiple copies will mot be created even when used by multiple applications. The GAC folder is under the Windows folder.

:\windows\assembly <– GAC folder

We can find all base class libraries under GAC. We can only get a strong named assembly into the GAC. GAC contains multiple assemblies and it is identified by PUBLIC KEY TOKEN.

How to generate a public key token:

A tool named strong name utility is used to do this, which is a command line tool …

Sn -k E.g.:\ > sn -k key.snk

The above statement generates a key value and writes it into “key.snk”.

We can use sn or snk for the extension of key files.

Creating A shared assembly

Step 1: Generate a key file. Open a VS command prompt. Go into your folder and generate a key file as: :\ sn -k key.snk

Step 2: create a project and associate a key file to it before compilation so that the generated assembly will be strong named.

Open a new project of type class library and name it sAssembly; under class1 write the following:

Public string sayhello()
{
Return “hello from shared assembly”;
}

To associate a key file we generated with the project, open the project properties and select the “signing” tab on the LHS which displays a CheckBox as “sign the assembly” select it that displays ComboBox below it from it select browse and select key.snk from its physical location then compile the project using build which will generate assembly Assembly.dll that is strong named.

Step 3: copying the assembly into GAC

.Net provides a command line utility to be used as shown in the following:

Gacutil -I | -u I:install u:uninstall. Open a VS command prompt; go to the location where the Assembly.dll is present and write the following:

:\\sAssembly\ sAssembly\bin\Debug>gacutil -I Assembly.dll

Describe the windows service life cycle

A service goes through several internal states in its lifetime. First, the service is installed onto the system on which it will run. This process executes the installers for the service project and loads the service into the Services Control Manager for that computer. The Services Control Manager is the central utility provided by Windows to administer services.

After the service has been loaded, it must be started. Starting the service allows it to begin functioning. You can start a service from the Services Control Manager, from Server Explorer, or from code by calling the Start method. The Start method passes processing to the application’s OnStart method and processes any code you have defined there.

A running service can exist in this state indefinitely until it is either stopped or paused or until the computer shuts down. A service can exist in one of three basic states: Running, Paused, or Stopped. The service can also report the state of a pending command: ContinuePending, PausePending, StartPending, or StopPending. These statuses indicate that a command has been issued, such as a command to pause a running service, but has not been carried out yet. You can query the Status to determine what state a service is in, or use the WaitForStatus to carry out an action when any of these states occurs.

You can pause, stop, or resume a service from the Services Control Manager, from Server Explorer, or by calling methods in code. Each of these actions can call an associated procedure in the service (OnStop, OnPause, or OnContinue), in which you can define additional processing to be performed when the service changes state.

 What is something substantive that you’ve done to improve as a developer in your career?

You’ve just been assigned to a project in a new technology how would you get started?

What elements of OO design are most prone to abuse? How would you mitigate that?

Inheritance, by large measure. It brings more power than containment and is usually easier to code, but it comes at a steep price.

* It breaks encapsulation. Instances of child classes have more access to the parent class than most classes. It’s very common for inheriting classes to have code that violates invariants of the parent. This is the heart of the notorious Fragile base class problem. If a Foo contains a Bar, on the other hand, Bar has much more control about what Foo can and cannot do with it.
* In many OO languages, once you say Foo extends Bar, Foo: Bar, Foo <: Bar or whatever, you have no flexibility to change the relationship between Foo and Bar at all, and in the ones where you can change it you typically can’t do it on a per object basis, you have to change the relationship for all Foos. That means, for instance, you can’t use a mock Bar to test a Foo in isolation of the code in Bar. If a Foo contains a Bar then mocking is straightforward and well understood.
* Inheritance + virtual methods can lead to a super class trying to call methods on an incompletely initialized sub class, which is a source of null dereferencing errors.  On the other hand, if Foo contains a Bar then Foo can’t hold a Bar until the Bar is fully constructed.
* In languages with multiple inheritance, the super class initialization rules are often very complicated and easy to mess up, which is a big part of the reason many OO languages have noped away from multiple inheritance. Containment of multiple objects doesn’t require any complicated rules.

In spite of all the downsides, inheritance is still over-used. It’s often harder to use containment + delegation because that requires more code. And if you need to “override” the behavior of both method x() and method y() where x() calls y() then delegation requires a change in interface on the contained object whereas that’s easy to do using inheritance.

What is Thread and explain states of a thread in C#?

Thread in C# is a set of guidelines or instructions that are executed, and enable the program to do concurrent processing. The concurrent processing of a program helps the developers handle more than one operation at a given time.

The different states of thread are listed below-
  1. Unstarted
  2. Running
  3. WaitSleepJoin
  4. Suspended
  5. Aborted
  6. Stopped

What do you mean by stack and heap in C#?

In C#, Stack is used during the static memory allocation. The variables that are allocated on the stack are stored directly in memory and access to this memory is fast. Heap is used during the dynamic memory allocation. The variables that are allocated on heap have memory allocated during runtime and access to this memory is slow.

Describe the Async method of C#?

Async (asynchronous programming) can be described as a method that returns to the calling method before finishing its work fully. It then proceeds to complete its work while the calling method goes along with its execution.

Is it possible to serialise hash tables?

It is not possible to serialise hash tables – a collection of key-value pairs – as the .NET Framework prevents serialisation of any object that implements the IDictionary interface. The XmlSerializer class will display an error when an attempt is made to serialise a Hashtable.

Explain the differences between “out” and “ref” parameters in C#?

Although quite similar, the “out” parameter can be passed to a method and doesn’t require to be initialised whereas the “ref” parameter has to be initialised and set to something before it is used.

Why singleton pattern is considered an Anti-pattern ?

Why singleton pattern is considered an Anti-pattern ?

– Singletons aren’t easy to handle with unit tests. You can’t control their instantiation and they may retain state across invocations.
– Memory allocated to an Singleton can’t be freed.
– In multithreaded environment, access to the singleton object may have to be guarded (e.g. via synchronization).

– Singletons promote tight coupling between classes, so it is hard to test

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

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

What is the use of volatile keyword?
The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.
The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access.
The volatile keyword can be applied to fields of these types:
– Reference types.
– Pointer types (in an unsafe context). Note that although the pointer itself can be volatile, the object that it points to cannot. In other words, you cannot declare a “pointer to volatile.”
– Integral types such as sbyte, byte, short, ushort, int, uint, char, float, and bool.
– An enum type with an integral base type.
– Generic type parameters known to be reference types.
– IntPtr and UIntPtr.

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

What are indexers in C# .NET? What is the difference between property & indexers?
An indexer is a pair of get and set accessors, similar to those of properties. Like a property, an indexer does not allocate memory for storage.
Both indexers and properties are used primarily for giving access to other data members with which they are associated and for which they provide get and set access.
− A property usually represents a single data member.
− An indexer usually represents multiple data members.
Like a property, an indexer can have either one or both of the accessors.
Indexers are always instance members; hence, an indexer cannot be declared static. Like properties, the code implementing the get and set accessors does not have to be associated with any fields or properties. The code can do anything, or nothing, as long as the get accessor returns some value of the specified type.

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

What is the use of Yield keyword in C#?
Yield keyword helps us to do custom stateful iteration over .NET collections.
There are two scenarios where “yield” keyword is useful:-
– It helps to provide custom iteration without creating temp collections.
– It helps to do state-full iteration

What is Null Coalescing Operator in C#?
C# Supports a special operator called the null coalescing operator, which returns a non-null value to an expression, in case a nullable type variable is null.
The null coalescing operator consists of two contiguous question marks and has two operands.
– The first operand is a variable of a nullable type.
– The second is a non-nullable value of the underlying type.
– If, at run time, the first operand (the nullable operand) evaluates to null, the non nullable operand is returned as the result of the expression.


1
2
3
4
int? myI4 = null;
Console.WriteLine(“myI4: {0}”, myI4 ?? -1);
myI4 = 10;
Console.WriteLine(“myI4: {0}”, myI4 ?? -1);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s