473,569 Members | 2,555 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generics for Customer and Phones.... should be easy!

Hi,
I'm building an application where I've defined a custom class Customer.
Customer can have many phones (defined by phoneType and phoneNumber). I want
to check that a phoneNumber is not already present in customer phones. So
i've build a PhoneCollection class inheriting for List<Phoneand defined an
Add method to check if the phoneNumber already exists. Then I added the
PhoneCollection to Customer properties.
Everything works fine, and I can add new phones to customer using
cust.Phones.Add ("1234") but Customer.Phones has Count=0 and if I look at it
in the debugger the phones are inside rawData (??). Strange thing is that if
I use customer.Phones[i] i got the i phone object!
What am I missing?? Below you can find the classes used.
Any help is welcome!
Bye,
Stefano

public class Customer
{
private String id;
private readonly PhoneCollection phones = new PhoneCollection ();

public Customer(string id)
{
this.id = id;
}

public PhoneCollection Phones
{
get
{
return this.phones;
}
}
}

public class Phone
{
private string id;
private string ownerId;
private int phoneType;
private string phonenumber;

public Customer(string id)
{
this.id = id;
}

public int PhoneType
{
get{return phoneType;}
set{phoneType = value;}
}

public string PhoneNumber
{
get{return phoneNumber;}
set{phoneNumber = value;}
}
}

public class PhoneCollection : List<Phone>
{
private List<Phonem_Pho nes = new List<Phone>();

public PhoneCollection ()
{
m_Phones.Capaci ty = 10;
}

public void Add(string phoneNumber)
{
//Here I add a new Phone to m_Phones if the phoneNumber is not present
}
}


Oct 9 '06 #1
5 1929
You are mixing inheritance and encapsulation; badly. Either you *are* a
list, or you *contain* the list. In your case, you do both. The methdos
you haven't overridden are pointing at the inherited list, where-as
..Add is looking at the contained list.

Basically, remove m_Phones completely; you *are* the list. Replace the
m_Phones.Someth ing() methods to base.Something( ) - i.e. call the base
version of this method - i.e.

public void Add(string number) {
if(!Contains(nu mber)) base.Add(number );
}

Although, personally I don't like this usage as people generally expect
..Add to either add or throw.

Marc

Oct 9 '06 #2
"Stefano Peduzzi" <pe***@interfre e.ita écrit dans le message de news:
Ot************* *@TK2MSFTNGP03. phx.gbl...

| public class PhoneCollection : List<Phone>
| {
| private List<Phonem_Pho nes = new List<Phone>();

If you are inheiting from List<Phone>, then you do not need to also have an
internal list.

| public PhoneCollection ()
| {
| m_Phones.Capaci ty = 10;
| }
|
| public void Add(string phoneNumber)
| {
| //Here I add a new Phone to m_Phones if the phoneNumber is not present
| }
| }

The problem is that you are inheriting from a class and then using an inner
list to store the numbers rather than the instance of the PhoneCollection
class, which is a list in itself. Also, declaring your own Add method will
hide the original Add method and should have given you a warning.

If I were you I would restructure this to declare your own class that no
longer inherits, but that simply contains a list, or better still a
Dictionary<K,V> .

public class PhoneCollection
{
private Dictionary<stri ng, Phonephones; = new Dictionary<stri ng,
Phone>();

public void Add(string phoneNumber)
{
if (!phones.Contai nsKey(phoneNumb er))
phones.Add(phon eNumber, new Phone(...));
}

public Phone this[string number]
{
get { return phones[number]; }
}

public Phone this[int index]
{
get { return phones.Values[index]; }
}
}

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Oct 9 '06 #3
Hi Joanna,
Thanks for your help! I tried the "route" you proposed and it is really
interesting (it works with 5 lines of code!). I've found 2 problems with it:
- public Phone this[int index]{ get { return phones.Values[index]; }}
gives me this compiler error:
Cannot apply indexing with [] to an expression of type
'System.Collect ions.Generic.Di ctionary<string ,BusinessEntity .Phone>.ValueCo llection'
C:\Progetti\Tes t\BusinessEntit y\PhoneCollecti on2.cs 28 18 BusinessEntity
-If I write
foreach (Phone tmp in c.Phones2)
I get this compiler error:
Error 1 foreach statement cannot operate on variables of type
'BusinessEntity .PhoneCollectio n2' because 'BusinessEntity .PhoneCollectio n2'
does not contain a public definition for 'GetEnumerator'
C:\Progetti\Tes t\Test\Form1.cs 97 13 Test

As you can see... if you have some good link on Dictionary it would be
useful!
Thanks,
Stefano
"Joanna Carter [TeamB]" <jo****@not.for .spamha scritto nel messaggio
news:eb******** ********@TK2MSF TNGP04.phx.gbl. ..
"Stefano Peduzzi" <pe***@interfre e.ita écrit dans le message de news:
Ot************* *@TK2MSFTNGP03. phx.gbl...

| public class PhoneCollection : List<Phone>
| {
| private List<Phonem_Pho nes = new List<Phone>();

If you are inheiting from List<Phone>, then you do not need to also have
an
internal list.

| public PhoneCollection ()
| {
| m_Phones.Capaci ty = 10;
| }
|
| public void Add(string phoneNumber)
| {
| //Here I add a new Phone to m_Phones if the phoneNumber is not present
| }
| }

The problem is that you are inheriting from a class and then using an
inner
list to store the numbers rather than the instance of the PhoneCollection
class, which is a list in itself. Also, declaring your own Add method will
hide the original Add method and should have given you a warning.

If I were you I would restructure this to declare your own class that no
longer inherits, but that simply contains a list, or better still a
Dictionary<K,V> .

public class PhoneCollection
{
private Dictionary<stri ng, Phonephones; = new Dictionary<stri ng,
Phone>();

public void Add(string phoneNumber)
{
if (!phones.Contai nsKey(phoneNumb er))
phones.Add(phon eNumber, new Phone(...));
}

public Phone this[string number]
{
get { return phones[number]; }
}

public Phone this[int index]
{
get { return phones.Values[index]; }
}
}

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer


Oct 9 '06 #4
Hi Marc,
As for Joanna... thanks for your help! Also your hints worked, so I removed
m_Phones. I have now a problem with Contains that always returns true. I've
implemented the Phone class inheriting from IComparable<Pho neand I defined
Equals and CompareTo.. I think (...) it is not enough: what should I
implement to have Contains working?

Thanks,
Stefano
"Marc Gravell" <ma**********@g mail.comha scritto nel messaggio
news:11******** **************@ i3g2000cwc.goog legroups.com...
You are mixing inheritance and encapsulation; badly. Either you *are* a
list, or you *contain* the list. In your case, you do both. The methdos
you haven't overridden are pointing at the inherited list, where-as
.Add is looking at the contained list.

Basically, remove m_Phones completely; you *are* the list. Replace the
m_Phones.Someth ing() methods to base.Something( ) - i.e. call the base
version of this method - i.e.

public void Add(string number) {
if(!Contains(nu mber)) base.Add(number );
}

Although, personally I don't like this usage as people generally expect
.Add to either add or throw.

Marc

Oct 9 '06 #5
"Stefano Peduzzi" <pe***@interfre e.ita écrit dans le message de news:
%2************* **@TK2MSFTNGP05 .phx.gbl...

| Thanks for your help! I tried the "route" you proposed and it is really
| interesting (it works with 5 lines of code!). I've found 2 problems with
it:
| - public Phone this[int index]{ get { return phones.Values[index]; }}
| gives me this compiler error:
| Cannot apply indexing with [] to an expression of type
|
'System.Collect ions.Generic.Di ctionary<string ,BusinessEntity .Phone>.ValueCo llection'

Sorry, my bad, I was mixing List<Tcode :-) Do you really need an integer
index ?

| C:\Progetti\Tes t\BusinessEntit y\PhoneCollecti on2.cs 28 18 BusinessEntity
| -If I write
| foreach (Phone tmp in c.Phones2)
| I get this compiler error:
| Error 1 foreach statement cannot operate on variables of type
| 'BusinessEntity .PhoneCollectio n2' because
'BusinessEntity .PhoneCollectio n2'
| does not contain a public definition for 'GetEnumerator'
| C:\Progetti\Tes t\Test\Form1.cs 97 13 Test

Then add the IEnumerable<Pho neinterface to PhoneCollection and wire it to
the dictionary.

public class PhoneCollection : IEnumerable<Pho ne>
{
IEnumerator<Pho neGetEnumerator ()
{
return phones.Values.G etEnumerator();
}
}

| As you can see... if you have some good link on Dictionary it would be
| useful!

Take a look at the examples in the help.

Joanna

--
Joanna Carter [TeamB]
Consultant Software Engineer
Oct 9 '06 #6

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

Similar topics

3
5243
by: Thomas Weholt | last post by:
Hi, Is it at all possible to use python to make apps on cellular/mobile phones, using something like Jython etc. ? Hm ... ?? Thomas
11
3980
by: andrew queisser | last post by:
I've read some material on the upcoming Generics for C#. I've seen two types of syntax used for constraints: - direct specification of the interface in the angle brackets - where clauses I looked at the files in the Gyro download but I couldn't find any mention of constraints. Can anyone enlighten me what the current status is and what we...
17
3300
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 way they are. ***** Summary & Questions ***** In a nutshell, the current .NET generics & .NET framework make it sometimes difficult or even...
6
3056
by: russ | last post by:
Hi, We have stumbled across an issue using the type safe collection System.Collections.ObjectModel.Collection <T> to retrieve data from our data layer. Say we have a customer object and want to get a type safe collection of all customers who have spend = X Within our datalayer we would currently have the following method
9
5963
by: sloan | last post by:
I'm not the sharpest knife in the drawer, but not a dummy either. I'm looking for a good book which goes over Generics in great detail. and to have as a reference book on my shelf. Personal Experience Only, Please. ...
10
1599
by: Frank Rizzo | last post by:
Given the inneficiencies of ArrayList and Hashtable on 64-bit systems, I am converting them to List<and Dictionary<respectively. It's a pretty massive system, so there are a lot of casts. For instance. ArrayList aaa = new ArrayList(); aaa.Add(new Customer()); aaa.Add(new Customer()); aaa.Add(new Customer()); Customer c = (Customer)...
4
1936
by: Random | last post by:
I want to define a generics method so the user can determine what type they expect returned from the method. By examining the generics argument, I would determine the operation that needs to be performed and do just that. However, out of the two possible ways of doing this, neither seems to work. I thought I could either... 1) overload...
1
1164
by: =?Utf-8?B?YmlsbHI=?= | last post by:
Sorry if this is the wrong group, but I cna think not of where else to post. I have an inheritance hierarchy in place as follows ... PersonVisitor<T<-- AlphabeticVisitor<T<-- FamilyNameVisitor<T> public interface IPerson { string GivenName { get; set; } string FamilyName { get; set; }
4
1471
by: Bruno Neves Pires Silva | last post by:
Hello, Programmers. How can I access a member of an object using generics? I've got the following problem:I Have a class that uses generics like below: class ClassName<typename> { public void method(typename var) {
0
7701
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7615
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7677
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7979
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5514
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5219
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1223
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
940
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.