Chapter 2 – Creating Versatile Types

SAMS CSHARP 4.0 (P.44)

In your class, by default ToString() will display the type’s name. To have a ToString(0 that print something, override it.

public override string ToString() {
return string.Format(“({0}, {1}, {2})”, X, Y, Z)

Implement Custom Formatting for Fine Control

By implementing Iformattable on your type, you can create a version of ToString() that is very flexible.

Make Types Equatable

need to determine if two objects are equal.

By default, Equals() on a reference type checks to see if the objects refers to the same location in Memory. With value types, the default behavior is to reflect over each field and do a bit-by-bit comparison. This is bad for performance so you should have your own implementation.

Make Type Sortable

Highly recommended when possible

typeName: IComparable<typename>

And then define method:

public int CompareTo(typename other) {
// return -1, 0 or 1

Notify Clients when Changes Happen

You want users of your class to know when data insode te class changes – implement INotifyPropertyChanged interface. In the OnPropertyChanged()

Overload Appropriate Operators

define what +, *, == and I= do when you use them on your type

Convert One Type to Another

two types: implicit and explicit

explicit: Has loss of information. need to cast;

Implicit: No loss of information – simply assign to the new type, no casting is needed.

Prevent Inheritance

You don’t want user of your class to inherit it: using sealed

sealed class MyClass{

Preventing Overriding of a Method

adding sealed to the method definition:
public sealed Myfunction() {

Allow Value Type to be NULL

Either one:
Nullable<int> _id;
int? _id;

If a variable is NULLABLE, then you can assign null value to it. Such as:

Post a comment or leave a trackback: Trackback URL.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: