Extra’s Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on Extra’s

Question 1.
What is Multi-Targeting in .NET?
Answer:
In previous versions of Visual Studio, every version was tied up with a framework. For instance, Visual Studio 2003 only works with 1.1 and Visual Studio 2005 only works with 2.0.

Extra’s Interview Questions in .NET chapter 20 img 1

From Visual Studio 2008 they have added a multi-targeting feature. You can use the same Visual Studio with different versions of the .NET framework (See Figure 20.1). So if you click on project properties you can now change the framework version to different types and check if your code is compatible with the old version.

Question 2.
What are portable class libraries?
Answer:
The whole point of creating a class library project is reusability. Now we want this reusability not only within a .NET project,not across.NET not across.NET projects but across different types of .NET projects. now different types of .NET projects. Now different types of .NET projects mean projects which we create using templates of WPF, windows, Silverlight, windows phone, etc., as shown in figure 20.2.

Extra’s Interview Questions in .NET chapter 20 img 2

Now each one of these project types runs on different platforms and has different flavors of .NET frameworks. For example Silverlight
the application runs inside a browser and has a downsized version of.NET.
So in a Silverlight project if you try to reference a simple “Class project” you would end with a below error. That’s where portable class libraries are useful (See Figure 20.3). By creating a portable class we can reference it in any kind of .NET project type.

Extra’s Interview Questions in .NET chapter 20 img 3

To create a portable class we need to use the portable class template which is available in Visual Studio as shown in Figure 20.4.

Question 3.
What is NuGet?
Answer:
The number of frameworks and libraries from both Microsoft (MVC, EF, etc.) and Non-Microsoft open sources (NUnit, Log4Net, etc.) are huge in numbers. These frameworks and libraries keep updating to newer versions and it’s very difficult to keep a track of the same.

Extra’s Interview Questions in .NET chapter 20 img 4

As a Visual Studio developer if you need to reference these frameworks or libraries, you need to do the following:

  • Search the library URL (L. from Resource Locator).
  • Install the library or probably unzip it at someplace.
  • Reference the DLL in your Visual Studio Project.
  • If library demands also make appropriate changes to the App. config or Web. config file.

In case you want to revert back you need to follow the above process in a vice-versa fashion.
This is where “NuGet” makes our life easy. “NuGet” is a Visual Studio Extension that helps us to search, locate the library, download them, reference them in the Visual Studio project and also make appropriate changes to App and Web config files (See Figure 20.5).

Extra’s Interview Questions in .NET chapter 20 img 5

So once you click on “Manage NuGet Packages…”, you can go and search the framework and click on install. Figure 20.7 shows a simple image where I have searched the new version of the Entity framework and now we need to just click on the Install button to add the same to your Visual Studio Project.

Extra’s Interview Questions in .NET chapter 20 img 6

Question 4.
How can we Unit test private methods use VSTS?
Answer:
In order to invoke private methods in VSTS (Visual Studio Team System) unit test, we have a class called “PrivateObject”. Create the object of the “PrivateObject” class and pass the class whose private method needs to be invoked. In our case “negative” is the private method that has an integer input parameter. You can then use the “PrivateObject” object to invoke the private methods/functions as shown in the below code.

PrivateObject o = new PrivateObject(typeof(Maths));
boolb = Convert.ToBoolean(o.lnvoke(“lsNegative”, -1));

Question 5.
Is it good to practice Unit test Private methods?
Answer:
No. When we say Unit it’s a class. So if we test the public methods the private methods get tested internally as well. If you are testing private methods of a class that means there is something seriously wrong with the class design.

public classmates
{
     publicint Add(int numl, int num2)
     {
          if(IsNegative(numl) && IsNegative(num2))
          {
                  thrownewExcept ion ("Number should not be negative'');
          }
          return numl + num2;
    }
    privatebool IsNegative(int num)
    {
         if (num > 0)
         {
                returntrue;
         }
         else
         {
               returnfalse;
         }
    }
}

For instance, in the above “Maths” class there is a private function “IsNegative” if you are testing this method that means the “Maths” class is overloaded with responsibility. “Maths” class should only be doing arithmetic operations (Add, Subtract, etc.), but it is also loaded with the responsibility of doing validation.

So probably it’s a good idea to move the validation to a separate class called “Validator” which will do the numeric checks and then use this class inside the “Maths” class.

You can then write test cases on the “Validator” class separately which is a cleaner approach than the previous approach of using “PrivateObject” and invoking them via reflection.

public class Validator
{
      private bool IsNegative(int num)
      {
          if (num > 0)
          {
               return true;
          }
          else
          {
              return false;
          }
     }
}

Question 5.
What is Mock testing?
Answer:
Let’s say you want to Unit test a data access layer class. But before any call is made to the data access class it calls an email class. This email component is not functional because we have still not received email server configuration details. Below is a simple code with comments that depict this situation.

Extra’s Interview Questions in .NET chapter 20 img 7

So now how do we Unit test the data access layer because the Email class will never allow us to execute the data access layer code This is achieved by mocking ( bypassing ) the e-mail code

public class Email
{
      public bool SendEmail( )
      {
            // not configured throws error
      }
}

public class ClsCustomerDAL
{
       public bool SaveRecord(string strCustomerName)
       {
            Email obj = new Email( );
            obj.SendEmail(); // This line throws a error
 
            // Data acess code goes at this place but this place is never reached because
            // the error is throw in the previous line
            return true;
      }
}

Question 6.
How can we implement Mocking?
Answer:
You can implement mocking by using open source mocking frameworks like Rhino Mocks (a dynamic mock object framework for the .NET platform), MOQ
(Mock-you; mocking library for. NET), etc. For example, if we want to mock the Email class method by using the MOQ tool we need to write the below code. Create the Email object using the Mock class of the MOQ framework.

Mock<Email> target = new Mock<Email>( );

Then write the code which you want to execute rather than executing the actual code. For instance, now I want to just “return true” in a hard code manner.

target.Setup(x => x.SendEmail()).Returns(true);

Now any calls to the “target” email object will always return true.

Question 7.
So are we saying Microsoft does not have mock frameworks?
Answer:
In Visual Studio 2012, Microsoft has introduced “Fakes” which has two great features “Stubs” and “Shims” which will help us achieve mock testing.

Question 8.
Define code coverage.
Answer:
Code coverage is a measure used during software testing which describes how much part of your source code has been tested. So if you see that a critical part of your code is not tested by your test case probably you need to update the test case accordingly to get a better coverage result.

Extra’s Interview Questions in .NET chapter 20 img 8

To see how much code coverage has been done by test cases.
Click on the TESTt menu → Analyze Code Coverage →All Tests (See Figure 20.9).

Once the coverage runs its shows a detailed report as shown in Figure 20.10 stating which sections do not have coverage. For instance, in the below report it states that the “Calculate” method of maths has 25% code which is not covered by the test cases.

Extra’s Interview Questions in .NET chapter 20 img 9

Question 9.
What is Cyclomatic complexity and how to measure the same?
Answer:
Cyclomatic complexity helps you measure code complexity. The higher the code complexity, the more it is prone to errors, and more important it becomes a unit test for that specific code. Cyclomatic complexity number depends on how many different execution paths your code can execute depending on varying inputs. More the code paths, more the complexity.

For example, take the below code. There is nothing complex in the below code, we do not have many execution paths. We just have lots of code lines which does variable initialization. So the cyclomatic complexity of the below code is “1 ”.

public void cancel( )
{
     Num1 = 0;
     Num2 = 0;
     Operation = " ";
     Pie = 3.14;
     Num5 = 0;

        Operation1 =" ";
        Num2o = 0;
        Numx = 0;
        OperationStart = " ";
        PieMore = 3.145;
        Num6 = 0;
        Operationnew = " ";
}

But now take the example of the below code. There are 4 branch conditions in the below code as shown in below Table. So the cyclomatic complexity is “4”.

Input Output
Path 1 Operation. Length ==0 Exception thrown
Path 2 Operation == “+” Num1 + Num2
Path 3 Operation == “-“ Num1 – Num2
Path 4 Any other inputs Num1 * Num2
public int Calculate( )
{
      if (Operation.Length == 0)
      {
             throw new Exception!" Operation not specified");
      }
      if (Operation == "+")
      {
             return Num1 + Num2;
      }
      else if (Operation == "-";
      {
             return Num1 - Num2
      }
      else
      {
             return Num2 * Num1
      }
      return 0;
}

To measure code complexity using Visual Studio, click on Analyze -> Calculate Code Metric for the solution. This feature is available only for Visual Studio ultimate editions. Once done you should get the cyclomatic complexity as shown in Figure 20.11.

Extra’s Interview Questions in .NET chapter 20 img 10

Question 10.
What is the use of the extern keyword and DllImport attribute?
Answer:
If you want to call functions that are not written using the .NET framework, we need to use the extern keyword. So let’s say we want to call the “MessageBox” function which belongs to Windows API (Application Programming Interface). So the first thing we need to import the “interop services” namespace.

using System. Runtime. InteropServices;

Later we need to use the extern keyword to create the method as shown below. Also, note this method has to be decorated with “DllImport” attribute.

[Dlllmport(“User32. dll")]
public static extern int MessageBox(int h, string m, string c, int type);

Once the static function is created, you can call the “MessageBox” function later as shown in the below code.

MessageBox(0, “Test”, “My Message Box”, 0);

Question 11.
What is the difference between Debug and Release?
Answer:
Debug and Release are build modes, where Debug is used to build the code in development mode and Release is for production / go live as shown in Figure 20.12 environment.

Extra’s Interview Questions in .NET chapter 20 img 11

In Release mode, the code is more optimized and any debugging-related code or debug constants are removed before going to production.

Question 12.
What is the use of Debug directive?
Answer:
#DEBUG is a preprocessor directive. Now many times you want some code to run while you are debugging but you do want those codes shipped to the production environment.

For instance, in the below code we want to display the operating system only during debugging but this code we do not want to be pushed to the production server. To achieve this we can use the DEBUG directive.

You can see the below code, we have wrapped display operating version code in #if DEBUG condition.This code will be excluded when release compiling happens.

#if DEBUG
// This code will not be shipped to production.
Console.WriteLine(System.Environment.OSVersion);
#endif
// This code will be shipped to production,
for (int i = 0; i < 5 ; i++)
{
     Console.WriteLine(i);
}

Question 13.
What do the word scalability, scale-up, and scale-out mean?
Answer:
Scalability is the ability of a system to handle a growing amount of load without degrading performance. Consider you have a system which runs with 100 users efficiently. Let’s say over a period of time your load increases to 500 users, your system still has the ability to handle the load and provide the same efficiency.

You can achieve scalability in two ways either can Scale-up or Scale-out. In scale-up, we have only one machine and we increase the processing power of the machine by adding more processors, more RAMs (Random Access Memory), more hard disks, etc. So if your load increases you add more RAMs, more processors, etc., but you do not add extra physical machines.

In Scale-out, as your load increases, you add more computers and you have load balancers in front of those machines to distribute the load appropriately.