Using Component (Overloading Methods and Constructors) in ASP.NET - Part 5


Introduction

This is very important to know all web developers that how we overload any methods or constructors. When a method is overloaded a component contains two methods with exactly the same name. Many methods in the .NET Framework are overloaded, including the String.Replace() method, the Random.Next() method and the Page.FindControl() method.

For example, here is a list of the three overloaded versions of the Random.Next() method:

·         Next(): Returns a random number between 0 and 2,147,483,647.
·         Next(upperbound): Returns a number between 0 and the upper bound.
·         Next(lowerbound, upperbound): Returns a number between the lower bound and the upper bound.

Because all three methods do the same thing they all return a random number it makes sense to overload the Next()method. The methods differ only in their signatures. A method signature consists of the order and type of parameters that a method accepts. We cannot overload two methods that have exactly the same set of parameters (even if the names of the parameters differ). Overloading is useful when we want to associate related methods. Overloading is also useful when we want to provide default values for parameters. Here is example given below, StoreProduct component contains three overloaded versions of its SaveProduct() method.



Class1.vb File Code

Imports Microsoft.VisualBasic

Public Class StoreProduct

    Public Sub SaveProduct(ByVal name As String)
        SaveProduct(name, 0, String.Empty)
    End Sub

    Public Sub SaveProduct(ByVal name As StringByVal price As Decimal)
        SaveProduct(name, price, String.Empty)
    End Sub

    Public Sub SaveProduct(ByVal name As StringByVal price As DecimalByVal description As String)
        ' Here we can process name, price and description for further use
    End Sub

End Class


Default.aspx.vb File Code

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As ObjectByVal e As System.EventArgsHandles Me.Load
        Dim myDetails As New StoreProduct()
        myDetails.SaveProduct("HCL Desktop PC", 45000.75, "This PC has great configuration")
    End Sub
End Class

Note: Continue in Next Part.

Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System