Using Component (Declaring Namespace) in ASP.NET - Part 6
Introduction
Namespace enables us to group
logically related classes. We are not required to provide a class with a
namespace. To this point, all the components that we have created have been
members of the global namespace. However, several advantages result from grouping
components into namespaces.
First, namespaces prevent naming collisions. If two companies
produce a component with the same name, then namespaces provide you with a
method of distinguishing the components.
Second, namespaces make it easier to understand the purpose of a
class. If we group all your data access components into a DataAccess namespace
and all your business logic components in a BusinessLogic namespace, then we
can immediately understand the function of a particular class.
In an ASP.NET page, we import a namespace like this:
<%@ Import Namespace="System.Collections" %>
In a Visual Basic component, on the hand, we import a namespace
like this:
Imports System.Collections
We can create your own custom namespaces and group our
components into namespaces by using the Namespacestatement. Here is the
example given below.
Class1.vb File Code
Imports Microsoft.VisualBasic
Namespace AspNetUnleashed.SampleCode
Public Class Namespaced
Public Function SaySomething() As String
Return "Something"
End Function
End Class
End Namespace
Default.aspx File Code
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<%@ Import Namespace="System.Collections" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</div>
</form>
</body>
</html>
Default.aspx.vb File Code
Imports System.Collections
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim x As New AspNetUnleashed.SampleCode.Namespaced()
Label1.Text
= x.SaySomething()
End Sub
End Class
In above example code we use the Namespace statement
to group the Namespaced component into theAspUnleashed.SampleCode namespace.
Components in different files can share the same namespace, and different
components in the same file can occupy different namespaces.
Note: Continue in Next Part.
Comments
Post a Comment