Pages

Thursday 28 November 2013

Understanding virtual, override and new keyword

As you know Polymorphism is the concepts of OOPS which includes method overriding and method overloading. Virtual and Override keyword are used for method overriding and new keyword is used for method hiding. Let's have look on these keywords in C# and try to understand each importance.

Simple Class Inheritance

Consider the below class hierarchy with classes A, B and C. A is the super/base class, B is derived from class A and C is derived from class B.
If a method Test() is declared in the base class A and classes B or C has no methods as shown below.
  1. using System;
  2. namespace Polymorphism
  3. {
  4. class A
  5. {
  6. public void Test() { Console.WriteLine("A::Test()"); }
  7. }
  8.  
  9. class B : A { }
  10.  
  11. class C : B { }
  12.  
  13. class Program
  14. {
  15. static void Main(string[] args)
  16. {
  17. A a = new A();
  18. a.Test(); // output --> "A::Test()"
  19.  
  20. B b = new B();
  21. b.Test(); // output --> "A::Test()"
  22.  
  23. C c = new C();
  24. c.Test(); // output --> "A::Test()"
  25.  
  26. Console.ReadKey();
  27.  
  28. }
  29. }
  30. }
Suppose you have Test() method in all the classes A, B, C as shown below:
  1. using System;
  2. namespace Polymorphism
  3. {
  4. class A
  5. {
  6. public void Test() { Console.WriteLine("A::Test()"); }
  7. }
  8.  
  9. class B : A
  10. {
  11. public void Test() { Console.WriteLine("B::Test()"); }
  12. }
  13.  
  14. class C : B
  15. {
  16. public void Test() { Console.WriteLine("C::Test()"); }
  17. }
  18.  
  19. class Program
  20. {
  21. static void Main(string[] args)
  22. {
  23. A a = new A();
  24. B b = new B();
  25. C c = new C();
  26.  
  27. a.Test(); // output --> "A::Test()"
  28. b.Test(); // output --> "B::Test()"
  29. c.Test(); // output --> "C::Test()"
  30.  
  31. a = new B();
  32. a.Test(); // output --> "A::Test()"
  33.  
  34. b = new C();
  35. b.Test(); // output --> "B::Test()"
  36.  
  37. Console.ReadKey();
  38. }
  39. }
  40. }
When you will run the above program, it will run successfully and gives the O/P. But this program will show the two warnings as shown below:
  1. 'Polymorphism.B.Test()' hides inherited member 'Polymorphism.A.Test()'. Use the new keyword if hiding was intended.
  2. 'Polymorphism.C.Test()' hides inherited member 'Polymorphism.B.Test()'. Use the new keyword if hiding was intended.

Method Hiding (new keyword)

As you have seen in the above example the compiler generate the warnings since C# also supports method hiding. For hiding the base class method from derived class simply declare the derived class method with new keyword. Hence above code can be re-written as :
  1. using System;
  2. namespace Polymorphism
  3. {
  4. class A
  5. {
  6. public void Test() { Console.WriteLine("A::Test()"); }
  7. }
  8.  
  9. class B : A
  10. {
  11. public new void Test() { Console.WriteLine("B::Test()"); }
  12. }
  13.  
  14. class C : B
  15. {
  16. public new void Test() { Console.WriteLine("C::Test()"); }
  17. }
  18.  
  19. class Program
  20. {
  21. static void Main(string[] args)
  22. {
  23. A a = new A();
  24. B b = new B();
  25. C c = new C();
  26.  
  27. a.Test(); // output --> "A::Test()"
  28. b.Test(); // output --> "B::Test()"
  29. c.Test(); // output --> "C::Test()"
  30.  
  31. a = new B();
  32. a.Test(); // output --> "A::Test()"
  33.  
  34. b = new C();
  35. b.Test(); // output --> "B::Test()"
  36.  
  37. Console.ReadKey();
  38. }
  39. }
  40. }
Moreover, if you are expecting the fourth and fifth output should be "B::Foo()" and "C::Foo()" since the objects a and b are referenced by the object of B and C respectively then you have to re-write the above code for Method Overriding.

Method Overriding (virtual and override keyword)

In C#, for overriding the base class method in derived class, you have to declare base class method as virtual and derived class method as override as shown below:
  1. using System;
  2. namespace Polymorphism
  3. {
  4. class A
  5. {
  6. public virtual void Test() { Console.WriteLine("A::Test()"); }
  7. }
  8.  
  9. class B : A
  10. {
  11. public override void Test() { Console.WriteLine("B::Test()"); }
  12. }
  13. class C : B
  14. {
  15. public override void Test() { Console.WriteLine("C::Test()"); }
  16. }
  17. class Program
  18. {
  19. static void Main(string[] args)
  20. {
  21. A a = new A();
  22. B b = new B();
  23. C c = new C();
  24. a.Test(); // output --> "A::Test()"
  25. b.Test(); // output --> "B::Test()"
  26. c.Test(); // output --> "C::Test()"
  27. a = new B();
  28. a.Test(); // output --> "B::Test()"
  29. b = new C();
  30. b.Test(); // output --> "C::Test()"
  31.  
  32. Console.ReadKey();
  33. }
  34. }
  35. }

Mixing Method Overriding and Method Hiding

You can also mix the method hiding and method overriding by using virtual and new keyword since the method of a derived class can be virtual and new at the same time. This is required when you want to further override the derived class method into next level as I am overriding Class B, Test() method in Class C as shown below:
  1. using System;
  2. namespace Polymorphism
  3. {
  4. class A
  5. {
  6. public void Test() { Console.WriteLine("A::Test()"); }
  7. }
  8.  
  9. class B : A
  10. {
  11. public new virtual void Test() { Console.WriteLine("B::Test()"); }
  12. }
  13.  
  14. class C : B
  15. {
  16. public override void Test() { Console.WriteLine("C::Test()"); }
  17. }
  18.  
  19. class Program
  20. {
  21. static void Main(string[] args)
  22. {
  23.  
  24. A a = new A();
  25. B b = new B();
  26. C c = new C();
  27.  
  28. a.Test(); // output --> "A::Test()"
  29. b.Test(); // output --> "B::Test()"
  30. c.Test(); // output --> "C::Test()"
  31.  
  32. a = new B();
  33. a.Test(); // output --> "A::Test()"
  34.  
  35. b = new C();
  36. b.Test(); // output --> "C::Test()"
  37.  
  38. Console.ReadKey();
  39. }
  40. }
  41. }

Note

  1. The virtual keyword is used to modify a method, property, indexer, or event declared in the base class and allow it to be overridden in the derived class.
  2. The override keyword is used to extend or modify a virtual/abstract method, property, indexer, or event of base class into derived class.
  3. The new keyword is used to hide a method, property, indexer, or event of base class into derived class.

Understanding Model View Controller in Asp.Net MVC

The Model-View-Controller (MVC) pattern was introduced in 1970s. It is a software design pattern that splits an application into three main aspects : Model, View and Controller. Moreover, MVC pattern forces a separation of concerns within an application for example, separating data access logic and business logic from the UI.

Model - The "M" in "MVC"

The Model represents a set of classes that describes the business logic and data. It also defines business rules for how the data can be changed and manipulated.
Moreover, models in Asp.Net MVC, handles the Data Access Layer by using ORM tools like Entity Framework or NHibernate etc. By default, models are stored in the Models folder of the project.

The Model can be broken down into several different layers as given below:

  1. Objects or ViewModel Layer

    This layer contains simple objects or complex objects which are used to specify strongly-typed view. These objects are used to pass data from controller to strongly-typed view and vice versa. The classes for these objects can have specific validation rules which are defined by using data annotations. Typically, these classes have those properties which you want to display on corresponding view/page.
  2. Data Access Layer

    This layer provides objects to access and manipulate the database of your application. Typically, this layer is made by using ORM tools like Entity Framework or NHibernate etc.
  3. Business Layer

    This layer helps you to implement your business logic and validations for your application. This layer make use of Data Access Layer for persisting data into database. Also, this layer is directly invoked by the Controller to do processing on input data and sent back to view.

View - The "V" in "MVC"

The View is responsible for transforming a model or models into UI. The Model is responsible for providing all the required business logic and validation to the view. The view is only responsible for displaying the data, that is received from the controller as the result.
Moreover, views in Asp.Net MVC, handles the UI presentation of data as the result of a request received by a controller. By default, views are stored in the Views folder of the project.

Controller - The "C" in "MVC"

The Controller is responsible for controlling the application logic and acts as the coordinator between the View and the Model. The Controller receive input from users via the View, then process the user's data with the help of Model and passing the results back to the View.
Moreover, controllers in Asp.Net MVC, respond to HTTP requests and determine the action to take based upon the content of the incoming request. By default, controllers are stored in the Controllers folder of the project.

Difference Between Constant and ReadOnly and Static

Constant and ReadOnly keyword are used to make a field constant which value cannot be modified. Static keyword is used to make members static that can be shared by all the class objects. In this article, I am going to explain the difference among these three.

Constant

Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static.
  1. public const int X = 10;
A const field is a compile-time constant. A constant field or local variable can be initialized with a constant expression which must be fully evaluated at compile time.
  1. void Calculate(int Z)
  2. {
  3. const int X = 10, X1 = 50;
  4. const int Y = X + X1; //no error, since its evaluated a compile time
  5. const int Y1 = X + Z; //gives error, since its evaluated at run time
  6. }
You can apply const keyword to built-in value types (byte, short, int, long, char, float, double, decimal, bool), enum, a string literal, or a reference type which can be assigned with a value null.
  1. const MyClass obj1 = null;//no error, since its evaluated a compile time
  2. const MyClass obj2 = new MyClass();//gives error, since its evaluated at run time
Constants can be marked as public, private, protected, internal, or protected internal access modifiers.
Use the const modifier when you sure that the value a field or local variable would not be changed.

ReadOnly

A readonly field can be initialized either at the time of declaration or with in the constructor of same class. Therefore, readonly fields can be used for run-time constants.
  1. class MyClass
  2. {
  3. readonly int X = 10; // initialized at the time of declaration
  4. readonly int X1;
  5.  
  6. public MyClass(int x1)
  7. {
  8. X1 = x1; // initialized at run time
  9. }
  10. }
Explicitly, you can specify a readonly field as static since, like constant by default it is not static. Readonly keyword can be apply to value type and reference type (which initialized by using the new keyword) both. Also, delegate and event could not be readonly.
Use the readonly modifier when you want to make a field constant at run time.

Static

The static keyword is used to specify a static member, which means static members are common to all the objects and they do not tied to a specific object. This keyword can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.
  1. class MyClass
  2. {
  3. static int X = 10;
  4. int Y = 20;
  5. public static void Show()
  6. {
  7. Console.WriteLine(X);
  8. Console.WriteLine(Y); //error, since you can access only static members
  9. }
  10. }

Key points about Static keyword

  1. If the static keyword is applied to a class, all the members of the class must be static.
  2. Static methods can only access static members of same class. Static properties are used to get or set the value of static fields of a class.
  3. Static constructor can't be parameterized and public. Static constructor is always a private default constructor which is used to initialize static fields of the class.

Understanding Type Casting or Type Conversion in C#

Different Types of Type Casting or Type Conversion

  1. Implicit conversion

    Implicit conversion is being done automatically by the compiler and no data will be lost. It includes conversion of a smaller data type to a larger data types and conversion of derived classes to base class. This is a safe type conversion.
    1. int smallnum = 654667;
    2. // Implicit conversion
    3. long bigNum = smallnum;
    1. class Base
    2. {
    3. public int num1 { get; set; }
    4. }
    5.  
    6. class Derived : Base
    7. {
    8. public int num2 { get; set; }
    9. }
    10.  
    11. class Program
    12. {
    13. static void Main(string[] args)
    14. {
    15. Derived d = new Derived();
    16. //Implicit Conversion
    17. Base b = d;
    18. }
    19. }
  2. Explicit conversion

    Explicit conversion is being done by using a cast operator. It includes conversion of larger data type to smaller data type and conversion of base class to derived classes. In this conversion information might be lost or conversion might not be succeed for some reasons. This is an un-safe type conversion.
    1. long bigNum = 654667;
    2. // Explicit conversion
    3. int smallnum = (int)bigNum;
    1. class Base
    2. {
    3. public int num1 { get; set; }
    4. }
    5.  
    6. class Derived : Base
    7. {
    8. public int num2 { get; set; }
    9. }
    10.  
    11. class Program
    12. {
    13. static void Main(string[] args)
    14. {
    15. Base b = new Base();
    16. //Explicit Conversion
    17. Derived d = (Derived)b;
    18. }
    19. }
  3. User-defined conversion

    User-defined conversion is performed by using special methods that you can define to enable explicit and implicit conversions. It includes conversion of class to struct or basic data type and struct to class or basic data type. Also, all conversions methods must be declared as static.
    1. class RationalNumber
    2. {
    3. int numerator;
    4. int denominator;
    5.  
    6. public RationalNumber(int num, int den)
    7. {
    8. numerator = num;
    9. denominator = den;
    10. }
    11.  
    12. public static implicit operator RationalNumber(int i)
    13. {
    14. // Rational Number equivalant of an int type has 1 as denominator
    15. RationalNumber rationalnum = new RationalNumber(i, 1);
    16. return rationalnum;
    17. }
    18.  
    19. public static explicit operator float(RationalNumber r)
    20. {
    21. float result = ((float)r.numerator) / r.denominator;
    22. return result;
    23. }
    24.  
    25. }
    26. class Program
    27. {
    28. static void Main(string[] args)
    29. {
    30. // Implicit Conversion from int to rational number
    31. RationalNumber rational1 = 23;
    32.  
    33. //Explicit Conversion from rational number to float
    34. RationalNumber rational2 = new RationalNumber(3, 2);
    35. float d = (float)rational2;
    36. }
    37. }

What is the Upcasting and Downcasting?

There are two more casting terms Upcasting and Downcasting. basically these are parts of Implicit conversion and Explicit conversion.
Implicit conversion of derived classes to base class is called Upcasting and Explicit conversion of base class to derived classes is called Downcasting.
  1. class Base
  2. {
  3. public int num1 { get; set; }
  4. }
  5.  
  6. class Derived : Base
  7. {
  8. public int num2 { get; set; }
  9. }
  10.  
  11. class Program
  12. {
  13. static void Main(string[] args)
  14. {
  15. Derived d1 = new Derived();
  16. //Upcasting
  17. Base b1 = d1;
  18.  
  19. Base b2 = new Base();
  20. //Downcasting
  21. Derived d2 = (Derived)b2;
  22. }
  23. }

Thursday 21 November 2013

Difference Between ASP.NET WebForms and ASP.NET MVC

One of the frequently asked questions about ASP.NET MVC is that how is different from ASP.NET WebForms. Is ASP.NET MVC a replacement for WebForms.
The answer is No. ASP.NET MVC, is not a replacement for WebForms. Both ASP.NET MVC and ASP.NET WebForms are built on top of the Core ASP.NET Framework. In fact a lot of features we use in ASP.NET such as Roles, Membership, Authentication and a lot of namespaces, classes and interfaces can be used in an ASP.NET MVC application
Here are some points that I wrote in an article for www.dotnetcurry.com that differentiate ASP.NET WebForms from ASP.NET MVC:
ASP.NET WebForms
ASP.NET MVC
Uses the ‘Page Controller’ pattern. Each page has a code-behind class that acts as a controller and is responsible for rendering the layout.Uses the ‘Front Controller’ pattern. There is a single central controller for all pages to process web application requests and facilitates a rich routing architecture
Uses an architecture that combines the Controller (code behind) and the View (.aspx). Thus the Controller has a dependency on the View. Due to this, testing and maintainability becomes an issue.ASP.NET MVC enforces a "separation of concerns". The Model does not know anything about the View. The View does not know there’s a Controller. This makes MVC applications easier to test and maintain
The View is called before the Controller.Controller renders View based on actions as a result of the User Interactions on the UI.
At its core, you ‘cannot’ test your controller without instantiating a View. There are ways to get around it using tools.At its core, ASP.NET MVC was designed to make test-driven development easier. You ‘can’ test your Controller without instantiating a View and carry out unit-tests without having to run the controllers in an ASP.NET process.
WebForms manage state by using view state and server-based controls.ASP.NET MVC does not maintain state information by using view state
WebForms supports an event-driven programming style that is like Windows applications and is abstracted from the user. The State management is made transparent by using sessions, viewstate etc. In the process, the HTML output is not clean making it difficult to manage later. The ViewState also increases your page size.In ASP.NET MVC, the output is clean and you have full control over the rendered HTML. The orientation is towards building standard compliant pages and provides full control over the behavior of an application.
Deep understanding of HTML, CSS and JavaScript is not required to a large extent since the WebForm model abstracts a lot of these details and provides automatic plumbing. While abstracting details to provide ease of use, sometimes a solution is overcomplicated, than it needs to be.A thorough understanding of how HTML, CSS and JavaScript work together is required. The advantage is you can do a lot of jQuery and AJAX stuff in an efficient and simple manner than you would do in an ASP.NET application.
WebForms can drastically reduce time while building up intranet and internet applications that use a lot of controls (drag and drop model). Although this is true for development, a lot of time is spent later to code around limitations.You lose the 'drag and drop' quick model of building your web applications. The focus is on control over the application behavior and test-driven development. The model is extensible and you do not have to spend time working around limitations.
Relatively simple to learn and pickup. Works very well for developers who initially have trouble with the HTTP/HTML model and are coming from a similar WinForms oriented event model.There is a learning curve to understand the why, when and how of ASP.NET MVC.
Lesser amount of code is required to build webapps since a lot of components are integrated and provided out of the box. You can also use a lot of data controls provided out of the box that rely on ViewState.Since the application tasks are separated into different components, amount of code required is more. Since ASP.NET MVC does not use ViewState, you cannot use Data controls like GridView, Repeater.
Works very well for small teams where focus is on rapid application developmentWorks well for large projects where focus in on testability and maintainability