Advanced C# – Create an HTML helper method for website with MVC framework

The idea behind this concept is to create extensions for the HtmlHelper class and thus generate shared components in our project.

Create extension

To create the extension to the HtmlHelper class we need to create an Extension Method (can search my blog post about it). This method will be responsible for creating the HTML component to be displayed on our website. For this example I will show you how to make an HTML component that generates a filter for a list. This filter is nothing more than an alphabet, each letter has a link that will filter on a list. Let’s see how should be our Extension Method.

 public static class Paginator
 {
 public static MvcHtmlString PageLink(this HtmlHelper html, List<char> col, Func<char, string> GetURL)
 {
 StringBuilder result = new StringBuilder();
 TagBuilder tag = new TagBuilder("a");
 tag.MergeAttribute("href", GetURL('*'));
 tag.InnerHtml = "ALL";
 result.Append(tag.ToString());
 result.Append(" | ");
 foreach (var letter in col)
 {
 tag = new TagBuilder("a");
 tag.MergeAttribute("href", GetURL(letter));
 tag.InnerHtml = letter.ToString().ToUpper();
 result.Append(tag.ToString());
 result.Append(" | ");
 }

 return MvcHtmlString.Create(result.ToString());
 }
 }

As we can see the method must be static like the class that contains it. The return value of our method is the type MvcHtmlString which is an HTML-encoded string. Our method receives as parameters (a condition for Extension Method) a HtmlHelper, this is the class our method will extend. The second parameter as already mentioned above is the list of characters we want to show our HTML component and finally as the third parameter will receive Func that will be used to select from our list and generate the Link component. What we will do in this method is very simple, we will generate using a plain HTML using a string.  For this we are going to use the class TagBuilder, this will generate the required tags. For our particular case we are going to generate an <a> tag but remember that you can create the component that you need. Once we complete the plain HTML that we want we will call the static method Create in the class MvcHtmlString to generate the return value.

<system .web.webpages.razor="">
<host factorytype="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<pages pagebasetype="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="WebUI.HtmlHelpers" />
</namespaces>
</pages>
</host>
</system>

Now we have to let Razor know about our component. In order to do that we need include into the Web.config the namespace of our Extension Method to make it accessible.

Using our new method

No we have out method available so is just a matter of include it in our view as I did in the following example.

@{
var collection = new List<char> { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o','p','q','r','s','t',
'u','v','w','x','y','z'};
@Html.PageLink(collection, x => Url.Action("Index", new { start = x }))
}

As you can see we extended the HtmlHelper class so we just need to call @Html class to use our new method. The Func parameter is a Lambda Expression to select in our collection and generate the ActionLink component.

This is the easiest way to generate a common component in our web sites is using HtmlHelper. This is a powerful tool and you can use it to create more complex components.

Advanced C# – Extension Methods

The extension methods came up with the version 3.0 of the .net framework. Basically it gives us the possibility to use the syntax to call a method (object.method()) defined as static method. The compiler gives us the illusion that we are invoking a method that belongs to our object but in fact we are only invoking a static method defined in another place.

Lets take a look to the following example

public static class Extensions
{
public static string Left(this string s, int num)
{
if (string.IsNullOrEmpty(s)) return string.Empty;
if (num &lt;= 0) return string.Empty;
if (num &lt;= s.Length) return s.Substring(0, num);
return s;
}
}

We defined a static class Extensions that has a static method Left until this point there is nothing new just a normal static class. Anyway you can realize that as first parameter we use the operator this which is the owner to make this normal static method into a Extension Method and allow us to make this:

var text = &quot;This is my string text&quot;;
var text2 = text.Left(17);

As you can see we can invoke the method defined in the static class as it is part of the object (in my case text is a string object). What happen internally?  The compiler invoke the static method in the normal way Extension.Left(text, 17) using as first parameter the object which has invoked the extension method.

This is how to define an extension method so lets now review a few definitions:

  • The extension methods are not part of the class which are extending. It means that an extension method can’t access to the protected method of the class that invokes it.
  • They must be defined in a static class therefore all of them must be static.
  • They can be invoked in a null reference and it doesn’t throw an exception.
  • The extended class can be a sealed class.
  • The extended class can be replaced by an interface.
  • The extended method are “normal” method for this reason you can invoke it as I did before using the normal way.
  • The extended class can be defined as Generics.

This is a good tool to extend class behavior without doing a modification on the extended class. Later on I will write another post to show how we can use this extension method to create an HTML Helper.

.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 ( &quot;not defined a value for this variable&quot; );
         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 (): &quot;null&quot; );
Console.WriteLine (variable2.HasValue ? variable2.Value.ToString (): &quot;null&quot; );
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 (): &quot;null&quot; );
Console.WriteLine (vari2.HasValue ? vari2.Value.ToString (): &quot;null&quot; );
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.

 

.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 ..”