Knowledge Share

Knowledge is NOT Power IMPLEMENTATION of knowledge is Power!!!
 
HomePortalGalleryCalendarFAQRegisterUsergroupsLog in

Share | 
 

 Coding Conventions in .net

View previous topic View next topic Go down 
AuthorMessage
Admin
Admin


Posts : 142
Points : 410
Reputation : 0
Join date : 2007-12-29
Location : Chennai

PostSubject: Coding Conventions in .net   Mon Dec 31, 2007 12:10 pm

The following code example contains two calls to the default implementation of the Equals method.
[Visual Basic]
Imports System
Class SampleClass
Public Shared Sub Main()
Dim obj1 As New System.Object()
Dim obj2 As New System.Object()
Console.WriteLine(obj1.Equals(obj2))
obj1 = obj2
Console.WriteLine(obj1.Equals(obj2))
End Sub
End Class
[C#]
using System;
class SampleClass
{
public static void Main()
{
Object obj1 = new Object();
Object obj2 = new Object();
Console.WriteLine(obj1.Equals(obj2));
obj1 = obj2;
Console.WriteLine(obj1.Equals(obj2));
}
}
The output of the preceding code is the following.
False
True
Overriding the Equals method
The following code example shows a Point class that overrides the Equals method to provide value equality and a class Point3D, which is derived from Point. Because the Point class's override of Equals is the first in the inheritance chain to introduce value equality, the Equals method of the base class (which is inherited from Object and checks for referential equality) is not invoked. However, Point3D.Equals invokes Point.Equals because Point implements Equals in a manner that provides value equality.
[Visual Basic]
Imports System

Class Point
Private x As Integer
Private y As Integer

Public Overrides Overloads Function Equals(obj As Object) As Boolean
' Check for null values and compare run-time types.
If obj Is Nothing Or Not Me.GetType() Is obj.GetType() Then
Return False
End If
Dim p As Point = CType(obj, Point)
Return Me.x = p.x And Me.y = p.y
End Function
End Class

Class Point3D
Inherits Point
Private z As Integer

Public Overrides Overloads Function Equals(obj As Object) As Boolean
Return MyBase.Equals(obj) And z = CType(obj, Point3D).z
End Function

Public Overrides Function GetHashCode() As Integer
Return MyBase.GetHashCode() ^ z
End Function
End Class
[C#]
using System;
class Point: object
{
int x, y;
public override bool Equals(Object obj)
{
// Check for null values and compare run-time types.
if (obj == null || GetType() != obj.GetType())
return false;
Point p = (Point)obj;
return (x == p.x) && (y == p.y);
}
public override int GetHashCode()
{
return x ^ y;
}
}

class Point3D: Point
{
int z;
public override bool Equals(Object obj)
{
return base.Equals(obj) && z == ((Point3D)obj).z;
}
public override int GetHashCode()
{
return base.GetHashCode() ^ z;
}
}
The Point.Equals method checks that the obj argument is non-null and that it references an instance of the same type as this object. If either of the checks fail, the method returns false. The Equals method uses the Object.GetType Method to determine whether the run-time types of the two objects are identical. Note that typeof (TypeOf in Visual Basic) is not used here because it returns the static type. If the method had used a check of the form obj is Point instead, the check would return true in cases where obj is an instance of a class derived from Point, even though obj and the current instance are not of the same run-time type. Having verified that both objects are of the same type, the method casts obj to type Point and returns the result of comparing the instance variables of the two objects.
In Point3D.Equals, the inherited Equals method is invoked before anything else is done. The inherited Equals method checks to see that obj is not null, that obj is an instance of the same class as this object, and that the inherited instance variables match. Only when the inherited Equals returns true, does the method compare the instance variables introduced in the derived class. Specifically, the cast to Point3D is not executed unless obj has been determined to be of type Point3D or a class derived from Point3D.
Using the Equals method to compare instance variables
In the previous example, the equality operator (==) is used to compare the individual instance variables. In some cases, it is appropriate to use the Equals method to compare instance variables in an Equals implementation, as shown in the following example.
[Visual Basic]
Imports System

Class Rectangle
Private a, b As Point

Public Overrides Overloads Function Equals(obj As [Object]) As Boolean
If obj Is Nothing Or Not Me.GetType() Is obj.GetType() Then
Return False
End If
Dim r As Rectangle = CType(obj, Rectangle)
' Use Equals to compare instance variables.
Return Me.a.Equals(r.a) And Me.b.Equals(r.b)
End Function

Public Overrides Function GetHashCode() As Integer
Return a.GetHashCode() ^ b.GetHashCode()
End Function
End Class
[C#]
using System;
class Rectangle
{
Point a, b;
public override bool Equals(Object obj)
{
if (obj == null || GetType() != obj.GetType()) return false;
Rectangle r = (Rectangle)obj;
// Use Equals to compare instance variables.
return a.Equals(r.a) && b.Equals(r.b);
}
public override int GetHashCode()
{
return a.GetHashCode() ^ b.GetHashCode();
}
}
Overloading the equality operator (==) and the Equals method
In some programming languages, such as C#, operator overloading is supported. When a type overloads ==, it should also override the Equals method to provide the same functionality. This is typically accomplished by writing the Equals method in terms of the overloaded equality operator (==), as in the following example.
[C#]
public struct Complex
{
double re, im;
public override bool Equals(Object obj)
{
return obj is Complex && this == (Complex)obj;
}
public override int GetHashCode()
{
return re.GetHashCode() ^ im.GetHashCode();
}
public static bool operator ==(Complex x, Complex y)
{
return x.re == y.re && x.im == y.im;
}
public static bool operator !=(Complex x, Complex y)
{
return !(x == y);
}
}
Because Complex is a C# struct (a value type), it is known that no classes will be derived from Complex. Therefore, the Equals method does not need to compare the GetType results for each object. Instead it uses the is operator to check the type of the obj parameter.


Callback Function Usage
Delegates, Interfaces and Events allow you to provide callback functionality. Each type has its own specific usage characteristics that make it better suited to particular situations.
Events
Use an event if the following are true:
A method signs up for the callback function up front, typically through separate Add and Remove methods.
Typically, more than one object will want notification of the event.
You want end users to be able to easily add a listener to the notification in the visual designer.
Delegates
Use a delegate if the following are true:
You want a C language style function pointer.
You want a single callback function.
You want registration to occur in the call or at construction time, not through a separate Add method.
Interfaces
Use an interface if the callback function requires complex behavior.
Time-Out Usage
Use time-outs to specify the maximum time a caller is willing to wait for completion of a method call.
A time-out might take the form of a parameter to the method call as follows.
[Visual Basic]
server.PerformOperation(timeout)
[C#]
server.PerformOperation(timeout);
Alternately, a time-out can be used as a property on the server class as follows.
[Visual Basic]
server.Timeout = timeout
server.PerformOperation()
[C#]
server.Timeout = timeout;
server.PerformOperation();
You should favor the first approach, because the association between the operation and the time-out is clearer. The property-based approach might be better if the server class is designed to be a component used with visual designers.
Historically, time-outs have been represented by integers. Integer time-outs can be hard to use because it is not obvious what the unit of the time-out is, and it is difficult to translate units of time into the commonly used millisecond.
A better approach is to use the TimeSpan structure as the time-out type. TimeSpan solves the problems with integer time-outs mentioned above. The following code example shows how to use a time-out of type TimeSpan.
[Visual Basic]
Public Class Server
Public Sub PerformOperation(timeout As TimeSpan timeout)
' Insert code for the method here.
End Sub
End Class

Public Class TestClass
Dim server As New Server();
server.PerformOperation(New TimeSpan(0,15,0))
End Class
[C#]
public class Server
{
void PerformOperation(TimeSpan timeout)
{
// Insert code for the method here.
}
}

public class TestClass
{
public Server server = new Server();
server.PerformOperation(new TimeSpan(0,15,0));
}
If the time-out is set to TimeSpan(0), the method should throw an exception if the operation is not immediately completed. If the time-out is TimeSpan.MaxValue, the operation should wait forever without timing out, as if there were no time-out set. A server class is not required to support either of these values, but it should throw an InvalidArgumentException if an unsupported time-out value is specified.
If a time-out expires and an exception is thrown, the server class should cancel the underlying operation.
If a default time-out is used, the server class should include a static defaultTimeout property to be used if the user does not specify one. The following code example includes a static OperationTimeout property of type TimeSpan that returns defaultTimeout.
[Visual Basic]
Class Server
Private defaultTimeout As New TimeSpan(1000)

Overloads Sub PerformOperation()
Me.PerformOperation(OperationTimeout)
End Sub

Overloads Sub PerformOperation(timeout As TimeSpan)
' Insert code here.
End Sub

ReadOnly Property OperationTimeout() As TimeSpan
Get
Return defaultTimeout
End Get
End Property
End Class
[C#]
class Server
{
TimeSpan defaultTimeout = new TimeSpan(1000);

void PerformOperation()
{
this.PerformOperation(OperationTimeout);
}

void PerformOperation(TimeSpan timeout)
{
// Insert code here.
}

TimeSpan OperationTimeout
{
get
{
return defaultTimeout;
}
}
}
Types that are not able to resolve time-outs to the resolution of a TimeSpan should round the time-out to the nearest interval that can be accommodated. For example, a type that can only wait in one-second increments should round to the nearest second. An exception to this rule is when a value is rounded down to zero. In this case, the time-out should be rounded up to the minimum time-out possible. Rounding away from zero prevents "busy-wait" loops where a zero time-out value causes 100 percent processor utilization.
In addition, it is recommended that you throw an exception when a time-out expires instead of returning an error code. Expiration of a time-out means that the operation could not complete successfully and therefore should be treated and handled as any other run-time error. For more information, see Error Raising and Handling Guidelines.
In the case of an asynchronous operation with a time-out, the callback function should be called and an exception thrown when the results of the operation are first accessed. This is illustrated in the following code example.
[Visual Basic]
Sub OnReceiveCompleted(ByVal sender As System.Object, ByVal asyncResult As ReceiveCompletedEventArgs)
Dim queue As MessageQueue = CType(sender, MessageQueue)
' The following code will throw an exception
' if BeginReceive has timed out.
Dim message As Message = queue.EndReceive(asyncResult.AsyncResult)
Console.WriteLine(("Message: " + CStr(message.Body)))
queue.BeginReceive(New TimeSpan(1, 0, 0))
End Sub
[C#]
void OnReceiveCompleted(Object sender, ReceiveCompletedEventArgs asyncResult)
{
MessageQueue queue = (MessageQueue) sender;
// The following code will throw an exception
// if BeginReceive has timed out.
Message message = queue.EndReceive(asyncResult.AsyncResult);
Console.WriteLine("Message: " + (string)message.Body);
queue.BeginReceive(new TimeSpan(1,0,0));
}
Back to top Go down
http://knowledgeshare.forumotion.com
 
Coding Conventions in .net
View previous topic View next topic Back to top 
Page 1 of 1
 Similar topics
-
» open every link in a new tab?
» Banner inquiry
» XHTML - Lesson 5/5
» Pagination
» Are emails dying?

Permissions in this forum:You cannot reply to topics in this forum
Knowledge Share :: .Net-
Jump to: