473,387 Members | 1,611 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Generic Class example and how to use Generic Classes (format)

Here is an example of a home grown generic class, representing a pair
of values. Adapted from Jon Skeet's book "C# In Depth".

The generic class is "sealed" for some reason (I think for
performance) so you cannot derive from it, but that's optional. The
main thing in this example is to show the right format for using these
generic classes, which was not present in the code snippet in Skeet's
book.

Does anybody know why the .Equals does not work below? See //DOES NOT
WORK--WHY? below
I suspect it's because the equals is only compairing the shallow copy
or references (see the hash code)

RL

(C) 2008 by Ray Lopez, all world rights reserved

// Generics – from p. 84 of Jon Skeet C# in Depth
// OUTPUT (works as expected)
101 is: 101
string is: Generics1.Class1, while myClass1Pair.First.i is: 101
myC 2: Generics1.Class1
myClassTwo2.myClass1Pair.First.i: 123
myClassTwo2.myClass1Pair.Second.i: 321
myClassTwo2.myClass1Pair.First.j: 321
myClassTwo2.myClass1Pair.Second.j: 123
myCl2 != myClassTwo2
hash's are: 58225482, 54267293 //note: hash's are different so objects
not 'equal'

Press any key to continue . . .

//////////////////

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Generics1
{
class Program
{
static void Main(string[] args)
{
Class1 myCl1 = new Class1();
Class2 myCl2 = new Class2();

Console.WriteLine("101 is: {0}", myCl1.i);
string s= myCl2.myClass1Pair.First.ToString();
int j1 = myCl2.myClass1Pair.First.i;
Console.WriteLine("string is: {0}, while
myClass1Pair.First.i is: {1}", s,j1);

Class2 myClassTwo2 = new Class2(11.11, 123, 321);
string s2 = myClassTwo2.myClass1Pair.First.ToString();
Console.WriteLine("myC 2: {0}", s2);
int j2 = myClassTwo2.myClass1Pair.First.i;
Console.WriteLine("myClassTwo2.myClass1Pair.First. i: {0}",
j2);
int j3 = myClassTwo2.myClass1Pair.Second.i;
Console.WriteLine("myClassTwo2.myClass1Pair.Second .i: {0}",
j3);
int j4 = myClassTwo2.myClass1Pair.First.j;
Console.WriteLine("myClassTwo2.myClass1Pair.First. j: {0}",
j4);
int j5 = myClassTwo2.myClass1Pair.Second.j;
Console.WriteLine("myClassTwo2.myClass1Pair.Second .j: {0}",
j5);
if (myCl2 != myClassTwo2) Console.WriteLine("myCl2 !=
myClassTwo2");
Class2 myClassTwo22 = new Class2(11.11, 123, 321);

if ((myClassTwo2.Equals(myClassTwo22)))
Console.WriteLine("(myClassTwo2 == myClassTwo22)");
// above DOES NOT WORK--WHY? Because different references
pointed to, even though contents equal

int HashCode01 = myClassTwo2.GetHashCode();
int HashCode02 = myClassTwo22.GetHashCode();
Console.WriteLine("hash's are: {0}, {1}", HashCode01,
HashCode02);

}
}
}
///////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Generics1
{
class Class1
{
public int i;
public int j;
Pair<int, intmyPair;

public Class1()
{
myPair = new Pair<int, int>(10,10);
i = 101;
j = 0;
}
public Class1(int i, int j)
{
this.i = i; this.j = j;
}
}
class Class2
{
public double d;
public Pair<Class1, Class1myClass1Pair;
public Class2()
{
d = 10.0;
myClass1Pair = new Pair<Class1, Class1>(new Class1(), new
Class1());
}
public Class2(double d, int Class1Int01, int Class1Int02)
{
this.d = d;
myClass1Pair = new Pair<Class1, Class1>(new
Class1(Class1Int01, Class1Int02), new Class1(Class1Int02,
Class1Int01));
}
}

////////// THe below is from Jon Skeet's book ////////////

public sealed class Pair<TFirst, TSecond>
: IEquatable<Pair<TFirst, TSecond>>
{
private readonly TFirst first;
private readonly TSecond second;
public Pair(TFirst first, TSecond second)
{
this.first = first;
this.second = second;
}
public TFirst First
{
get { return first; }
}
public TSecond Second
{
get { return second; }
}
public bool Equals(Pair<TFirst, TSecondother)
{
if (other == null)
{
return false;
}
return EqualityComparer<TFirst>.Default
..Equals(this.First, other.First) &&
EqualityComparer<TSecond>.Default
..Equals(this.Second, other.Second);
}
public override bool Equals(object o)
{
return Equals(o as Pair<TFirst, TSecond>);
}
public override int GetHashCode()
{
return EqualityComparer<TFirst>.Default
..GetHashCode(first) * 37 +
EqualityComparer<TSecond>.Default
..GetHashCode(second);
}
}

}
//////////////////////
Oct 9 '08 #1
1 2435
On Oct 9, 11:39*am, raylopez99 <raylope...@yahoo.comwrote:
Here is an example of a home grown generic class, representing a pair
of values. *Adapted from Jon Skeet's book "C# In Depth".

The generic class is "sealed" for some reason (I think for
performance) so you cannot derive from it, but that's optional.
The class is immutable, and immutable types are generally sealed. In
addition, I'm a fan of the idea of sealing any class which isn't
designed specifically to be derived from.
>*The main thing in this example is to show the right format for using these
generic classes, which was not present in the code snippet in Skeet's
book.
Except you've only shown examples where TFirst = TSecond, rather than
(say) Pair<string,intwhich might represent the count of a particular
word within a corpus of text.
Does anybody know why the .Equals does not work below? *See //DOES NOT
WORK--WHY? below
I suspect it's because the equals is only compairing the shallow copy
or references (see the hash code)
No, it's comparing them with the default equality comparer, which will
use Equals/GetHashCode where appropriate. You haven't overridden
either Equals or GetHashCode in Class1 or Class2, so you end up
getting identity comparisons. Override those methods appropriately and
all will be well.

Jon
Oct 9 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Rod Bass | last post by:
I was disappointed to see that you can't use a parameter type as a base class for a generic class. I would find it extremely useful to extend a generic type of class (as is done nicely using C++...
17
by: Andreas Huber | last post by:
What follows is a discussion of my experience with .NET generics & the ..NET framework (as implemented in the Visual Studio 2005 Beta 1), which leads to questions as to why certain things are the...
16
by: tshad | last post by:
This is a little complicated to explain but I have some web services on a machine that work great. The problem is that I have run into a situation where I need to set up my program to access one...
25
by: Lars | last post by:
Hi, I have a base class holding a generic list that needs to be accessed by both the base class and its subclasses. What is the best solution to this? I am fairly new to generics, but I am...
3
by: Tigger | last post by:
I have an object which could be compared to a DataTable/List which I am trying to genericify. I've spent about a day so far in refactoring and in the process gone through some hoops and hit some...
9
by: Steve Richter | last post by:
in a generic class, can I code the class so that I can call a static method of the generic class T? In the ConvertFrom method of the generic TypeConvert class I want to write, I have a call to...
13
by: rkausch | last post by:
Hello everyone, I'm writing because I'm frustrated with the implementation of C#'s generics, and need a workaround. I come from a Java background, and am currently writing a portion of an...
10
by: phancey | last post by:
I'm quite new to generics. I have 2 generic classes: MyClass<Tand MyOtherClass<T>. MyClass<Thas 2 public Add methods Add(MyOtherClass<T>); Add(MyOtherClass<Wrapper<T>>); (Wrapper<Tis another...
2
by: =?Utf-8?B?Sm9obk1TeXJhc29mdA==?= | last post by:
I have a generic class defined. My "server" code wants to call methods on the generic class after I've assigned the type to it. I was trying to do this via a SELECT CASE statement but I can't...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.