Monday, July 14, 2014

Method Hiding in C#

Introduction

Method hiding in C# is similar to the function overriding feature in C++. Functions of the base class are available to the derived class. If the derived class is not happy, one of the functions available to it from the base class can define its own version of the same function with the same function signature, just differing in implementation. This new definition hides the base class definition. Take the following program for example.

P1.cs

class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{

}

class Demo
{
  public static void Main()
  {
     DC obj = new DC();
     obj.Display();
  }
}

Output

BC::Display
The above program compiles and runs successfully to give the desired output. The above program consists of a base class BC which consists of a public function named Display(). Class DC is derived from BC. So Display() of BC is Inherited by Class DC. It's as if DC has a function called Display(). Class Demo has the entry point function Main(). Inside Main we create an object obj of class DC and invoke the function Display(). What is called is the Display ofBC because its inherited by the derived class DC.
For some unknown reason the derived class was not happy with the implementation of the Display() function that it had inherited from its Base class BC. So the derived class made a bold decision to define its own version of the functionDisplay(). Thus, you could see code for Display() function in class BC as well as in class DC.

P2.cs

class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{
  public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class Demo
{
  public static void Main()
  {
     DC obj = new DC();
     obj.Display();
  }
}

Output

DC::Display
On compilation the above program threw a warning which said
P2.cs(11,15): warning CS0108: 'DC.Display()' hides inherited member 
'BC.Display()'. Use the new keyword if hiding was intended. P2.cs(3,15): 
(Location of symbol related to previous warning)
The compiler warns us about Display() of DC forcibly hiding Display() of BC. The compiler smells something dicy and requests us to use the new keyword if the hiding was intentional.
The above program compiles to produce an executable. We run the executable to get the desired output as shown above. The Display() of derived class DC is invoked as it hides the Display() of base class BC. But an executable with warnings is like a neatly dressed man with unpolished shoes. We need to remove the warning. We need to tell the compiler that the implementation of Display() in derived class was intentional. We do this by using the modifier new as shown in the program below.

P3.cs

class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class Demo
{
  public static void Main()
  {
     DC obj = new DC();
     obj.Display();
  }
}

Output

DC::Display
The addition of the modifier new to the function Display() in Derived class informs the compiler that the implementation of Display() in Derived class was intentional, thus stopping the compiler from throwing any warnings at us. Can you tell what the output of the above program will be?

P4.cs

class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class TC : DC
{

}

class Demo
{
  public static void Main()
  {
     TC obj = new TC();
     obj.Display();
  }
}

Output

DC::Display
The above program compiles and runs successfully to give the desired output. Class TC is derived from DC. SoDisplay() of DC is Inherited by Class TC. It's as if TC has a function called Display(). Class Demo has the entry point function Main(). Inside Main we create an object obj of class TC and invoke the function Display(). What gets called is the Display of DC because its inheritted by the derived class TC. Now what if we were to define and invoke classTC's own version of Display() ? Simple! We would have to define a function Display inside class TC with a new modifier as follows.

P5.cs

class BC
{
  public void Display()
  {
     System.Console.WriteLine("BC::Display");
  }
}

class DC : BC
{
  new public void Display()
  {
     System.Console.WriteLine("DC::Display");
  }
}

class TC : DC
{
  new public void Display()
  {
     System.Console.WriteLine("TC::Display");
  }
}

class Demo
{
  public static void Main()
  {
     TC obj = new TC();
     obj.Display();
  }
}

Output

TC::Display
The above program comples and runs successfully to give the desired output.

Polymorphism, Method Hiding and Overriding in C#


Overview
One of the fundamental concepts of object oriented software development is polymorphism. The term polymorphism (from the Greek meaning "having multiple forms") in OO is the characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow a variable to refer to more than one type of object.
Example Class Hierarchy
Let's assume the following simple class hierarchy with classes AB and C for the discussions in this text. A is the super- or base class, B is derived from A and C is derived from class B. In some of the easier examples, we will only refer to a part of this class hierarchy.
Inherited Methods
A method Foo() which is declared in the base class A and not redeclared in classes B or C is inherited in the two subclasses
    using System;
    namespace Polymorphism
    {
        class A
        {
            public void Foo() { Console.WriteLine("A::Foo()"); }
        }

        class B : A {}

        class Test
        {
            static void Main(string[] args)
            {
                A a = new A();
                a.Foo();  // output --> "A::Foo()"

                B b = new B();
                b.Foo();  // output --> "A::Foo()"
            }
        }
    }
     
The method Foo() can be overridden in classes B and C:
    using System;
    namespace Polymorphism
    {
        class A
        {
              public void Foo() { Console.WriteLine("A::Foo()"); }
        }

        class B : A
        {
              public void Foo() { Console.WriteLine("B::Foo()"); }
        }

        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;

                a = new A();
                b = new B();
                a.Foo();  // output --> "A::Foo()"
                b.Foo();  // output --> "B::Foo()"

                a = new B();
                a.Foo();  // output --> "A::Foo()"
            }
        }
    }
     
There are two problems with this code.
  • The output is not really what we, say from Java, expected. The method Foo() is a non-virtual method. C# requires the use of the keyword virtual in order for a method to actually be virtual. An example using virtual methods and polymorphism will be given in the next section.
  • Although the code compiles and runs, the compiler produces a warning:
...\polymorphism.cs(11,15): warning CS0108: The keyword new is required on 'Polymorphism.B.Foo()' because it hides inherited member 'Polymorphism.A.Foo()'
This issue will be discussed in section Hiding and Overriding Methods.
Virtual and Overridden Methods
Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.
    using System;
    namespace Polymorphism
    {
        class A
        {
            public virtual void Foo() { Console.WriteLine("A::Foo()"); }
        }

        class B : A
        {
            public override void Foo() { Console.WriteLine("B::Foo()"); }
        }

        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;

                a = new A();
                b = new B();
                a.Foo();  // output --> "A::Foo()"
                b.Foo();  // output --> "B::Foo()"

                a = new B();
                a.Foo();  // output --> "B::Foo()"
            }
        }
     }
Method Hiding
Why did the compiler in the second listing generate a warning? Because C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:
    using System;
    namespace Polymorphism
    {
        class A
        {
            public void Foo() { Console.WriteLine("A::Foo()"); }
        }

        class B : A
        {
            public new void Foo() { Console.WriteLine("B::Foo()"); }
        }

        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;

                a = new A();
                b = new B();
                a.Foo();  // output --> "A::Foo()"
                b.Foo();  // output --> "B::Foo()"

                a = new B();
                a.Foo();  // output --> "A::Foo()"
            }
        }
    }
Combining Method Overriding and Hiding
Methods of a derived class can both be virtual and at the same time hide the derived method. In order to declare such a method, both keywords virtual and new have to be used in the method declaration:
            class A
            {
                public void Foo() {}
            }

            class B : A
            {
                public virtual new void Foo() {}
            }
     
A class C can now declare a method Foo() that either overrides or hides Foo() from class B:
            class C : B
            {
                public override void Foo() {}
                // or
                public new void Foo() {}
            }
Conclusion
  • C# is not Java.
  • Only methods in base classes need not override or hide derived methods. All methods in derived classes require to be either defined as new or as override.
  • Know what your doing and look out for compiler warnings.

Thursday, July 10, 2014

ActionResult Return Type in MVC 3.0

Introduction

An ActionResult is a return type of a controller method in MVC. Action methods help us to return models to views, file streams, and also redirect to another controller's Action method. 

There are many derived ActionResult types in MVC that you may use to return the results of a controller method; these are more specific for a particular view. All Action Result Classes are derived from "ActionResult". In other words ActionResult is an abstract class that has several subtypes.

ViewResult

It renders a specified view to the response stream. The "ViewResult" class inherits from the abstract class "ViewResultBase" and is used to render a view. This class contains methods for finding the view to render and also for executing the result. This class also contains properties that identify the view (view Name) to render for the application.
public ViewResult ViewResultTest()
{
    return View("ViewResultTest");
}

http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.view.aspx

PartialViewResult

The PartialViewResult class is inherited from the abstract "ViewResultBase" class and is used to render a partial view. This class contains methods for finding the partial view to render and also for executing the result. This class also contains properties that identify the partial view (View Name) to render for the application. PartialViews are not common as action results. PartialViews are not the primary thing being displayed to the user, which is the View. The partial view is usually a widget or something else on the page.
public PartialViewResult PartialViewResultTest()
{
    return PartialView("PartialViewResult");
}


RedirectResult

It is used to perform an HTTP redirect to a given URL. This class is inherited from the "ActionResult" abstract class.
public ActionResult RedirectResultTest()
{
    return Redirect("http://www.google.com/");
public RedirectResult RedirectResultTest()
{
    return Redirect("http://www.google.com/");
}

http://msdn.microsoft.com/en-us/library/system.web.mvc.redirectresult.aspx
RedirectToRouteResult

RedirectToResult is used to redirect by using the specified route values dictionary. This class is inherited from the "ActionResult" abstract class.
public ActionResult RedirectToRouteResultTest(int? Id)
{
    return new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { controller = "Home", action = "List", Id = new int?() }));
}

http://msdn.microsoft.com/en-us/library/system.web.mvc.redirecttorouteresult.aspx

ContentResult

The ContentResult may be used to return to an action as plain text. This class is inherited from the "ActionResult" abstract class. 
public ActionResult ContentResultTest()
{
    return Content("Hello My Friend!");
public ContentResult ContentResultTest()
{
    return Content("Hello My Friend!");
}

JsonResult

Action methods on controllers return JsonResult (JavaScript Object Notation result) that can be used in an AJAX application. This class is inherited from the "ActionResult" abstract class. Here Json is provided one argument which must be serializable. The JSON result object that serializes the specified object to JSON format.
public JsonResult JsonResultTest()
{
    return Json("Hello My Friend!");
}

http://msdn.microsoft.com/en-us/library/system.web.mvc.jsonresult(v=vs.98).aspx

Difference Between ViewResult() and ActionResult()

public ViewResult Index()
{
    return View();
}

public ActionResult Index()
{
    return View();
}
ActionResult is an abstract class that can have several subtypes.
ActionResult Subtypes Resources
public ActionResult Foo() { if (someCondition) return View(); // returns ViewResult else return Json(); // returns JsonResult }
ViewResult is a subclass of ActionResult. The View method returns a ViewResult. So really these two code snippets do the exact same thing. The only difference is that with the ActionResult one, your controller isn't promising to return a view - you could change the method body to conditionally return a RedirectResult or something else without changing the method definition.
  • ViewResult - Renders a specifed view to the response stream
  • PartialViewResult - Renders a specifed partial view to the response stream
  • EmptyResult - An empty response is returned
  • RedirectResult - Performs an HTTP redirection to a specifed URL
  • RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
  • JsonResult - Serializes a given ViewData object to JSON format
  • JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
  • ContentResult - Writes content to the response stream without requiring a view
  • FileContentResult - Returns a file to the client
  • FileStreamResult - Returns a file to the client, which is provided by a Stream
  • FilePathResult - Returns a file to the client
ActionResult is an abstract class.
ViewResult derives from ActionResult. Other derived classes include JsonResult andPartialViewResult.
You declare it this way so you can take advantage of polymorphism and return different types in the same method.
e.g:
ActionResult is an abstract class, and it's base class for ViewResult class.
In MVC framework, it uses ActionResult class to reference the object your action method returns. And invokes ExecuteResult method on it.
And ViewResult is an implementation for this abstract class. It will try to find a view page (usually aspx page) in some predefined paths(/views/controllername/, /views/shared/, etc) by the given view name.
It's usually a good practice to have your method return a more specific class. So if you are sure that your action method will return some view page, you can use ViewResult. But if your action method may have different behavior, like either render a view or perform a redirection. You can use the more general base class ActionResult as the return type.