Tags: .net interview questions

SQL Server interview questions, c# interview questions, .NET interview questions, ASP.NET interview questions

QuestPond’s Interview Questions & Answers on Inversion of Control (IOC) in .NET

What is Inversion of Control (IOC) and why it is required?

In order to understand Inversion of control let’s talk about a scenario.

Scenario: - We have Customer_Business_Logic class which is using FileLogger class internally for logging Exception inside file.

Understanding problems with this approach–


  • Now let’s say some time later our organization asks us to replace FileLogger with DBLogger
    so that error can be logged inside Database instead of File. In this case we
    will explicitly change the code written inside Business logic layer to achieve
    goal.
    Changes in the business logic may leads to error in business logic.

  • Testing of business logic in isolation is not possible because it is directly referencing FileLogger class.

  • FileLogger need to be available at compile time. Means we can start working on Business logic only after FileLogger is created.

Solution: - Move concrete type creating power to some external source. In short Business class won’t directly create FileLogger object rather someone else will does that and give it to business logic. This is called Inversion of control. Control of object creating is given to someone else.

How to implement Inversion of Control (IOC)?

IOC or Inversion control can be implemented using many ways like Factory Pattern, Dependency injection, Service Locator Pattern etc.

For technical trainings on various topics like WCF (Windows Communication Foundation), MVC (Model View Controller), Business Intelligence, Design Patterns, WPF, TFS and Basic fundamentals feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com

For more stuff like this, click here. Subscribe to article updates or follow at twitter @SukeshMarla

See the following video on real time scenarios on Dependency Injection and Inversion of Control (DIIOC): -



Click and see here for more learning Inversion of Control(IOC) in .NET
SQL Server interview questions, c# interview questions, .NET interview questions, ASP.NET interview questions

QuestPond’s Interview Questions & Answers on .NET

How to write a FizzBuzz program in C#?

Ok first let me explain what is FizzBuzz, Fizz

"Write a c# program that prints numbers from 1 to 100. But for multiples of 3 print “Fizz” instead of the number and for the multiples of 5 print “Buzz”. For numbers which are multiples of both 3 and 5  print “FizzBuzz”.

for (int j = 1; j <= 100; j++)
 {
      string Output = "";

      if (j % 3 == 0) Output = "Fizz";// Divisible by 3 --> Fizz

      if (j % 5 == 0) Output += "Buzz"; // Divisible by 5 --> Buzz

      if (Output == "") Output = j.ToString(); // If none then --> number

      Console.WriteLine(Output); // Finally print the complete output
 }


Click and see here for more programming algorithm in .NET
SQL Server interview questions, c# interview questions, .NET interview questions, ASP.NET interview questions

QuestPond’s Interview Questions & Answers on .NET

What are Accessors and mutators in C#?

Look at the following example,

public class Customer
{
     publicint Age;
     .
     .
     .
 }


Now in the client code we will do something like this.

Customer c=new Customer();
c.Age=55;


But do you realize one thing even we can do something like this,

c.Age=563;
OR
c.Age=-65;


This is not a valid statement logically but it’s valid syntactically. Our program will just execute perfectly fine.

One of the pillar of Object oriented principle called Encapsulation let us protect our data by creating a wrapper around our data, logic etc. by means of functions, classes etc. In short Encapsulation also let us protects our data.

Usually we will do something like this.

public class Customer
{
       privateint Age; // data is private
       .
       .
       .
       publicintGetAge() // Data is exposed to outside world via public method
       {
               Return Age;
       }
       publicvoid SetAge(intpAge) // Updating of data is only possible via public method
       {
             If(pAge>0 &&pAge<100)
             {
                    Age=pAge;
             }
             else
             {
                   throw new Exception(“Invalid Age”);
             }
        }
 }


Now our data is protected.

Client code will look like this.

Customer c=new Customer();
c.SetAge(55);
Console.WriteLine(c.GetAge());

c.SetAge(965); // It will throw exception


In the above code snippet GetAge function which usually return the data is called Accessor method and SetAge function which updates data is called Mutator method.

Good news?

Now we are in C# things become much simpler. We can make use of properties instead of creating two functions.

public class Customer
{
       privateintpAge; .
       .
       .
       publicintAge()
       {
               get
               {
                    //Accessor
                    returnpAge;
               }
               set
               {
                   //Mutator
                   If(value>0 && value<100)
                   {
                           pAge=value;
                   }
                   else
                   {
                           throw new Exception(“Invalid Age”);
                   }
              }
        }
 }


Client code will look like this,

Customer c=new Customer();
c.Age=55;
Console.WriteLine(c.Age);

c.Age = 965; // It will throw exception


For technical trainings on various topics like WCF(Windows Communication Foundation), MVC, Business Intelligence, Design Patterns, WPF, TFS and Basic fundamentals feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com

For more stuff like this, click here. Subscribe to article updates or follow at twitter @SukeshMarla

Click and see here for more .NET training.

SQL Server interview questions, c# interview questions, .NET interview questions, ASP.NET interview questions

Online guide to learn .NET for Object initializer in C#?

Object initializer let us create an instance of a class and assign values to its properties in a single line. Normally we write following things while working with classes and objects.

      1. Create Object of class

        code 1

       2. Assign values to its properties

          code 2

But with object initializer we can do it in single line as follows

        code 3

What does collection initializer do?

Just like Object initializer it will reduce the work of a developer. It will let us create an instance of any collection class and assign one or more elements to it in the same line.

This is how we normally work,

      1. Create instance of collection class.

          code 4

      2. Add elements to it

          code 5


But with collection initializer we can do it in single line.

        code 6


For technical trainings on various topics like WCF, MVC, Business Intelligence, Design Patterns, WPF, TFS and Basic fundamentals feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com

For more stuff like this, click here. Subscribe to article updates or follow at twitter @SukeshMarla

Also do not forget to visit http://www.questpond.com for step by step, technical video & trainings.
SQL Server interview questions, c# interview questions, .NET interview questions, ASP.NET interview questions

.NET interview questions: - What is the difference between arraylist and list? Are Arraylist faster

.NET interview questions: - What is the difference between arraylist and list? Are Arraylist faster or Arrays?

Difference between arraylist and list: -

  • Arrays are fixed in size while Arraylist is resizable.

  • Arrays are strongly typed, in other words when you create an array it can store only one data type data. Arraylist can store any datatype.

Are Arraylist faster or Arrays: -

Array list takes any data type which leads to boxing and unboxing. As arrays are strongly typed they do not do boxing and unboxing. So arrays are faster as compared to array list.

// Array definition
int[] str = new int[10];

// Array list definition
ArrayList MyList = new ArrayList();


Generic equivalent for array list, stack, queues and hashtable: -

Below are the listed generic equivalents for each of them:-

  • Array list generic equivalent is List<int>.

  • Stack generic equivalent is Stack<int>.

  • Queue generic equivalent is Queue<int>.

  • Hashtable generic equivalent is Dictionary<int,int>.

Also see .NET interview questions video on different types of collection in .NET and C#: -

SQL Server interview questions, c# interview questions, .NET interview questions, ASP.NET interview questions

.NET interview questions: - Explain the difference between Icomparable and IComparer?

This .NET interview questions  will show difference between Icomparable and IComparer asked by the interviewer.

“IComparable” interface helps you to implement a default sort implementation for the collection.  But what if we want to sort using multiple criteria’s?.For those instances “IComparable” has a limitation and “IComparer” is the guy.

For example if we want to sort the list by “Name” under some situation or  sort by “Age” under some other situations we need to implement “IComparer” interface.

So the first step is to create different classes for each sort criteria. These classes will implement “IComparer” interface and will have sorting logic defined in the “Compare” method. You can see we have two different classes defined “CompareByName” and “CompareByAge”. One compares on the basis of “name” and the other on the basis of “age”.


class CompareByName : IComparer
    {
       public int Compare(Person x, Person y)
       {
           return string.Compare(x.Name, y.Name);
       }
    }
    class CompareByAge : IComparer
    {
       public int Compare(Person x, Person y)
       {
          if (x.Age > y.Age) return 1;
          if (x.Age < y.Age) return -1;
           return 0;
       }
    }

If you see the logic for “CompareByName” its simple. It uses the string comparison to evaluate the “Name” value sorting. But when we talk about numeric comparison there are 3 possible outputs Greater than , less than or Equal. So if you see “CompareByAge” class it returns 3 values 1 ( Greater than) , -1 ( Less than ) and 0 ( for Equal to).

Now that we have created the separate logics we can now invoke the “Peoples’ list by passing the class object. So for example if we want to sort by name, you will use the below code snippet.

Peoples.Sort(new CompareByName());

The output of the above code is nothing but alphabetically sorted data.

Ajay 20
Loki 40
Madan 20
Raju 20
Shiv 20
Sukesh 30


If you invoke the sort method of the list by using the age logic it will throw an output sorted on age value.

Peoples.Sort(new CompareByAge());

Ajay 20
Raju 20
Shiv 20
Madan 20
Sukesh 30
Loki 40

So the difference is really default internal implementation or customizable external implementation.  When we use “IComparable” we can have only one default sorting logic and that logic goes inside the collection itself. For “IComparator” the logic is outside the collection , in other words more extensible and the collection is not disturbed.
Icomparer
SQL Server interview questions, c# interview questions, .NET interview questions, ASP.NET interview questions

.NET interview questions: - What is GAC? How to add/remove an assembly from GAC? How to make choice

.NET interview questions: - What is GAC? How to add/remove an assembly from GAC? How to make choice from two versions of the same assembly?

This is .NET interview questions asked by the interviewer to the juniors and also to senior candidates. This question will clear theory as well as practical part.

GAC (Global Assembly Cache) is where all shared .NET assembly resides. GAC is used in the following situations: -

  • If the application has to be shared among several application available in same computer.

  • If the assembly has some special security, requirements like only administrators can remove the assembly. If the assembly is private then a simple delete of assembly the assembly file will remove the assembly.

Adding/removing an assembly from GAC:

You can use the ‘GacUtil’ tool which comes with visual studio. So to register an assembly in to GAC go to “Visual Studio Command Prompt” and type “gacutil –i (assembly name)”, where (assembly name) is the DLL name of the project.

One you have installed the assembly the DLL can be seen in ‘c:\windows\assembly\’ folder.

When we have many DLL’s to be deployed we need to create setup and deployment package using windows installer. So the common way of deploying GAC DLL in production is by using windows installer.

Choosing from two versions of the same assembly in GAC:

When we have two version of the same assembly in GAC we need to use binding redirect  tag and specify the version we want to use in the new version property as shown in the below “app.config” file.

<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="ComputerName" publicKeyToken="cfc68d722cd6a164" />
<publisherPolicy apply="yes" />
<bindingRedirect oldVersion="1.1.0.0" newVersion="1.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
 
Also see .NET interview questions video on checking assembly manifest for supported CLR version: -

SQL Server interview questions, c# interview questions, .NET interview questions, ASP.NET interview questions

.NET interview questions: - How to maintain performance and can clean unmanaged objects?

We need to follow the below steps:-

  • Implement IDisposable interface and implement the dispose function.

  • In Dispose function calls the “GC.SuppressFinalize” method.

  • At the client side ensure that the “Dispose” function is called when the object is no more required.

Below goes the code, this is also called as “Finalize and Dispose pattern”. This ensures that your objects are created in Generation 0 rather than Generation 1. “GC.SuppressFinalize” tells the garbage collector to not worry about destructor and destroy the objects in the first call itself.

 class clsMyClass : IDisposable
    {
        ~clsMyClass()
        {
            // In case the client forgets to call
            // Dispose , destructor will be invoked for
            Dispose(false);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                // Free managed objects.
            }
            // Free unmanaged objects
        }

        public void Dispose()
        {
            Dispose(true);
            // Ensure that the destructor is not called
            GC.SuppressFinalize(this);
        }
    }

Also see our .NET interview questions video on Garbage Collector, Gen 0, 1 & 2:  -

SQL Server interview questions, c# interview questions, .NET interview questions, ASP.NET interview questions

.NET interview questions: - All about Design Patterns in .NET

Q. What are Design Patterns?

A. Design patterns are reusable and documented solutions for commonly occurring problem in software development.

Q. Which Design Pattern you have implemented in your project?

A. Singleton, Strategy pattern, Factory pattern, Facade

Q. What is Facade?

A. Facade is all about simplifying. Example in N-layer application Business Layer is example of Facade. Business layer creates object of data access layer, work with data, perform some logic, perform many functionality using different classes. From UI we will straight forward call single method of BAL and that’s it. BAL is a facade over complexities.

Q. How will you explain Strategy Pattern?

A. In strategy pattern we will create one class for one algorithm.
We make all algorithms (classes) belong the same family with the help of interfaces.

Q. In what scenario you implemented Strategy Pattern?

A. We had discount calculation which was different for different days of the week. Calculations were complex and modification chances more.

For technical trainings on various topics like WCF, MVC, Business Intelligence, Design Patterns, WPF, TFS and basic fundamentals feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com

For more stuff like this, click here. Subscribe to article updates or follow at twitter @SukeshMarla

Also see our .NET interview questions video on Composite Design Pattern: -

SQL Server interview questions, c# interview questions, .NET interview questions, ASP.NET interview questions

.NET interview questions: - What is an Interface and what are abstract classes?

Interface is a contract that defines the signature of the functionality. It looks like a class but has no implementation. It has only empty definition of methods, functions, events, and indexer.

Interfaces provide forced implementation. For instance in the below code snippet we have created a simple interface called as “IDbCompulsory”. The below classes who implement interface “IDbCompulsory” has to provide implementation for “ExecSql”.

interface IDbCompulsory
{
void ExecSql();
}
public class SQLServer : IDbCompulsory
{
public void ExecSql()
{
// Here code for firing SQL Server SQL statements
// are written
}
}
public class Oracle : IDbCompulsory
{
public void ExecSql()
{
// Here code for firing Oracle SQL statements
// are written
}
}
 

Abstract classes: -

Abstract class is a half defined parent class. The full implementation of abstract class is defined by the child classes.

For example below code snippet shows a simple abstract class / half defined class called “DatabaseCommon” and later the concrete classes i.e. “SQLServer” and “Oracle” inherit and define a complete implementation for the same.

To define an abstract class we need to use the abstract keyword.

public abstract class DatabaseCommon
{
}
public class SQLServer : DatabaseCommon
{
}
public class Oracle : DatabaseCommon
{
}


Also see another .NET interview questions video on implement interfaces with same method names in C#: -