.NET Interview Questions – What are the nullable variable?

What problem resolved?

As everyone knows the value type (structs) not allow null as a value, this quire that if we declare a variable of type int for example you will never be able a comparison for null because this variable does not support null as a value. A possible elegant solution to this problem would define our own Integer structure to support null values as I did in the example below.

public struct NullInteger
{
  private int _value;
  private bool _hasValue;

  public NullInteger ( int value)
  {
     _value = value;
     _hasValue = true ;
  }

  public int Value
  {
     get
     {
         if (!_hasValue )
             throw new InvalidOperationException ( "not defined a value for this variable" );
         return _value;
     }
     set
     {
         _value = value;
         _hasValue = true ;
     }
  }

  public bool HasValue
  {
      get { return _hasValue; }
  }

  public static implicit operator NullInteger ( int value)
  {
      return new NullInteger (value);
  }

  public static NullInteger Null
  {
      get { return new NullInteger (); }
  }
 }

As we can see basically add two properties to the structure, one flag to validate if there is or not value and the other value in itself. Thus the consultation of this structure would be something like this.

static void Main ( string [] args)
{
NullInteger variable = 3;
NullInteger variable2 = Entero.Null;

Console.WriteLine (variable.HasValue ? variable.Value.ToString (): "null" );
Console.WriteLine (variable2.HasValue ? variable2.Value.ToString (): "null" );
Console.ReadKey ();
}

Now this workaround works fine but it has a high cost for us. For this reason the .net framework defined a new nullable data type which basically accepts null values.

How to define the types nullables?

Well basically  the way to define a nullable data is adding the operator ? the data type that we are specifying as I did in the following example.

static void Main ( string [] args)
{
int ? vari = 3;
int ? vari2 = null ;

Console.WriteLine (vari.HasValue ? vari.Value.ToString (): "null" );
Console.WriteLine (vari2.HasValue ? vari2.Value.ToString (): "null" );
Console.ReadKey ();
}

As you can see the use is very similar to what we had previously defined so basically we don’t need to create our own data type to support null values. On the other hand when using Nullables value we can use of the operator ?? because Nullable <T> offers several methods to make use of this as we can see below.

static void Main ( string [] args)
{
int ? vari = 3;

value = vari.HasValue? vari.Value: 7;
value = vari.GetValueOrDefault (7);
value = vari ?? 7;
Console.WriteLine (vari.HasValue ? vari.Value.ToString (): &quot;null&quot; );
Console.ReadKey ();
}

With any of the three options previously showed we can see that depending on the value of the variable we will assign the value that has or failing another value (or default).
As you can see this data type gives us the flexibility to work with properties that might have null values.

 

Advertisements

.Net Interview Questions – Differences between Abstract Class and Interface

This question appears almost in every interview for .NET developer role. It is very important that we clearly list the differences between them, explain the concepts behind each of these differences, theoretical and practical concepts behind the implementation. And finally we can give an opinion on which to use when and why.

What is an Abstract Class?

First, let’s explain clearly what is an abstract class. An Abstract class provides a model for his derived classes. It means that in an abstract class we define a framework for derived classes, functionality (which can be overwritten or defining contracts that must be implemented). It is important to say that you can’t create an instance of an abstract class so if you want to use an abstract class you must create a derived non-abstract class. There are two ways to declare functionality in an abstract class as we can see in the following example.

public abstract class Vehicle
{
    virtual public string Run ()
    {
        return &quot;I'm working&quot;;
    }

    abstract public string Stop ();
}

public class Car: Vehicle
{
    public override string Stop ()
    {
        return &quot;just stop&quot;;
    }
}

As we can see in our abstract class we declared two methods, the method Run uses the  keyword virtual, this is used to define a method that has a defined basic behavior but leaves the door open for the class that derives from this can overwrite this behavior. The method Stop in the other hand uses the reserved keyword abstract, this method doesn’t have a predefined  behavior. This allow us define a contract that must be implemented in the derived class as shown in the example above. Thus two ways in which we can use an abstract class and is to define behavior or to define a contract.
There is something to be stressed at this point that abstract classes are governed by rules heritage with which a class can only inherit from a class (or abstract ).

What is an Interface?

Interfaces are a resource that contains a definition of functionalities that must be implemented in a class. It is important to highlight that an interface does not define behavior, the same whether or must be defined in classes that implement it. Those classes must define behavior for all members of the interface. Because the interfaces are not classes a class can implement as many interfaces as desired as can be seen in the following example.

public interface IDraw
{
   string Draw ();
   string Set ();
}

public interface IDrawHexagon
{
   string Draw ();
}

public class Hexagon: IDraw, IDrawHexagon
{

   string IDraw.Draw ()
   {
      return &quot;Draw method implementation&quot; ;
   }

   public string Set ()
   {
      return &quot;Method implementation Set&quot; ;
   }

   string IDrawHexagon.Draw ()
   {
      return &quot;Draw method implementation Vertices&quot; ;
   }
}

 

You can see our class implements two interfaces. This behavior is not allowed with classes, a class cannot inherit from more than one class because C# doesn’t support multiple inheritance.

You can realize the method Draw is defined by both Interfaces. For this reason in our class Hexagon we need to explicit to which interfaces the method we are defining belongs. We can define which method we want to use implementing a cast.

hexa var = new Hexagono ();
IDraw test1 = (IDraw) hexa;
Console.WriteLine (test1.Draw());
IDrawHexagon test2 = (IDrawHexagon) hexa;
Console.WriteLine (test2.Draw());

The differences

To sum up we can say that either Abstract Classes or Interfaces allow us to define behavior. Using Interfaces we can implement more than one, in the other hand a class can inherit from only one class (abstract or not). A down side of the Interfaces is that the implementations are “all or nothing” which means that when you are implementing an interface must specify all the methods defined in the interface. As we said before Interfaces doesn’t define basic behavior to the method, only the signature.

To wrap up we can define the following rules to remember the diferences:

  • When a class implement an Interface answer the question: “it works like …”
  • When a class inherit from another class answer the question: “it is a ..”

.Net Interview Questions – Can you explain Generics?

In this post we are going to continue with entries dedicated to analyze the most common questions that come up in a .net interview. Today I will try to answer a question that appear in almost all interviews and is: Can you explain Generics?

Normally the first thought we have speaking about generics is about the generics collections and it is normal because most of the collections in .net use generics but there are not the concept itself.

Generics in a nutshell

Generics is an availability expose by the .net framework that allow us to split the behavior and the data type. Let see an example to show it clearly how it works. Suppose that we have a class that exposed a method to compare two strings variables and return if they are equals or not.

class check
{
    public static bool Compare(string a, string b)
    {
         return a.Equals(b);
    }
}

As you can see this is a really simple class but if we take a closer watch we will quickly realize a problem. That method only allow us to compare strings. If we want to compare another data type we should create an overload of this method as many times as data type we want to compare. We can see that this code is not clean and the maintenance is really complex.

class check
{
    public static bool Compare(string a, string b)
    {
        return a.Equals(b);
    }
    public static bool Compare(int a, int b)
    {
        return a.Equals(b);
    }

    public static bool Compare(DateTime a, DateTime b)
    {
        return a.Equals(b);
    }
}

There is another way to do it more “generic”

We can change the data type of the variables as object. This is a valid option but it will generate an overloading during the boxing and unboxing which is unnecessary. To solve this kind of problems we want to split the behavior and the data type. The first step is define a generic data type to use it in our method. We will use < and > to define our new generic data type. As a non written rule we are going to use the letter T to name our new generic data type but be aware that we can use whatever descriptor we want as you can see in the following code.

class check
{
    public static bool Compare&lt;UNKNOWTYPE&gt;(UNKNOWTYPE a, UNKNOWTYPE b)
    {
        return a.Equals(b);
    }
}

Now that we already have our generic method lets see how to use it.

	Console.WriteLine(&quot;comparing numbers: &quot; + check.Compare&lt;int&gt;(1,2));
	Console.WriteLine(&quot;comparing strings: &quot; + check.Compare&lt;string&gt;(&quot;hello&quot;, &quot;hello&quot;));

Now our method is flexible enough to work with all data type. Something important to highlight is that the data type used to call our method should be the same for the parameters because we define it in that way. If you want to can define several data types I let you make this test.

So next time someone ask to explain generics without doubt you have to explain that allow us to split the behavior and the data type and this technique can be use at class or method level.

 

.Net Interview Questions – Difference between var and dynamic

This will be the first entry about common questions in a .net interview. The main idea is explain clearly the most common concepts every .net developer should have. I know most of the questions in an interview make no sense but be aware when an Interviewer is asking is because he is expecting an specific answer from our side.

Difference between var and dynamic

For those are not familiar with those keywords, var and dynamics allow us to do not define the data type when we are declaring a variable. In this way a variable declaration looks like this.

var x = &quot;string&quot;;
dynamic y = &quot;string&quot;;

If we make a comparison between those variables the result will be that both variables are strings and both have the word “string”.

Both give us the result of the same object type, then what there are two keywords that make the same for? They appear to make the same but they do  not.  How is that possible? Well it is easy. The main difference  between those keywords is when they  join the variable with the data type and in my opinion this is the biggest advantage of dynamics over var.

When we declare a variable using the keyword var we must initialize this variable right away. Why? Well the data type is going to be joined to the variable while we are coding. It means when we initialize the variable this will be joined to the data type  we are using to initialize it. Even if you have the impression that you are not defining a data type you are using one so your code is still strongly typed and you wont be able to store in that variable something else that you stored during the initialization.

In the other hand when we declare a variable using dynamic it is not necessary initialize the variable to make it works. Why? Because dynamic is going to join the data type during the execution using reflection.  As you can imagine one of the strongest point of dynamic is become the variable a weakly typed. This allow us to make the following usage.

dynamic y = &quot;string&quot;;
Console.WriteLine(&quot;It is: {0}&quot;, y);
y = 1;
Console.WriteLine(&quot;It is: {0}&quot;, y);

The biggest advantage of dynamic is the flexibility as we could see before anyway a disadvantage, as every weakly typed language is that we are more plausible to make a mistake and do not know what is store in this variable. Because is using reflection we wont know the issue until running time.

The advantage of var is that allow us to reduce the space during the initialization or we might do not know which is the data type of a LINQ execution. In those cases var allow us to declare quickly a variable with out many problems.

In my opinion what the interviewer is looking with this question is to know how much we know of the .net framework or if we just repeat because some one tells you you have to do it in that way.