473,320 Members | 1,921 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,320 software developers and data experts.

Polymorphism and GetType()

Hello,

I'm trying to setup a named-object list using objects of 3 different
types all derived from the same base class.

public class namedObjectList :
System.Collections.Specialized.NameObjectCollectio nBase
{
public BaseType this[string name]
{
get { return BaseGet(name); }
}

public void Add(string key, BaseType obj)
{
BaseAdd(key, obj);
}
}

I then have my 3 derived types:

public class Derive1 : BaseType {...}
public class Derive2 : BaseType {...}
public class Derive3 : BaseType {...}

I can add instances of these 3 derived types with no problem but when I
do this:

string s = myNamedObjectList["whatever"].GetType().Name

I get back "BaseType" when what I really wanted was whichever one of the
derived types was added.

Should this work? How can I get what I want?

Thanks for any help,

..pd.
Nov 15 '05 #1
7 3143
100
Hi .pd,
GetType returns the real type of the object not the type of the variable
used to reference the object. In other words it has to work for you. Are you
sure your BaseGet(...) method works correctly?

B/rgds
100
".pd." <sp*****@your.peril> wrote in message
news:Xn*****************************@194.83.179.10 2...
Hello,

I'm trying to setup a named-object list using objects of 3 different
types all derived from the same base class.

public class namedObjectList :
System.Collections.Specialized.NameObjectCollectio nBase
{
public BaseType this[string name]
{
get { return BaseGet(name); }
}

public void Add(string key, BaseType obj)
{
BaseAdd(key, obj);
}
}

I then have my 3 derived types:

public class Derive1 : BaseType {...}
public class Derive2 : BaseType {...}
public class Derive3 : BaseType {...}

I can add instances of these 3 derived types with no problem but when I
do this:

string s = myNamedObjectList["whatever"].GetType().Name

I get back "BaseType" when what I really wanted was whichever one of the
derived types was added.

Should this work? How can I get what I want?

Thanks for any help,

.pd.

Nov 15 '05 #2
100 wrote on Wed 17 Dec 2003 05:58:56p:
Hi .pd,
GetType returns the real type of the object not the type of the
variable used to reference the object. In other words it has to work
for you. Are you sure your BaseGet(...) method works correctly?


So you're telling me I have write my own GetType()? I was afraid of that.

BaseGet() is a method belonging to the
System.Collections.Specialized.NameObjectCollectio nBase class. It ain't
mine.

..pd.
Nov 15 '05 #3
..pd. <sp*****@your.peril> wrote:
100 wrote on Wed 17 Dec 2003 05:58:56p:
GetType returns the real type of the object not the type of the
variable used to reference the object. In other words it has to work
for you. Are you sure your BaseGet(...) method works correctly?


So you're telling me I have write my own GetType()? I was afraid of that.


No, you *can't* write your own GetType, but 100 was saying (correctly)
that if GetType().Name is returning "BaseType" then the object in
question really *is* an instance of *just* BaseType, and not a derived
type.

Please give a short but complete example which shows the problem you're
having. See
http://www.pobox.com/~skeet/csharp/complete.html for what I mean by
that.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #4
The Add() method in my NameObjectCollectionBase inheritor had no overloads
and accepted an instance of the base type as its argument.

By replacing this with an overload for each derived type, it now works as I
expected.

Thanks for your responses,

..pd.
Nov 15 '05 #5
..pd. <sp*****@your.peril> wrote:
The Add() method in my NameObjectCollectionBase inheritor had no overloads
and accepted an instance of the base type as its argument.
That should make no difference though, as each derived type *is* an
instance of the base type.
By replacing this with an overload for each derived type, it now works as I
expected.


Really not sure what you mean here, but never mind - I'm glad you've
got it working.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #6
100
Hi .pd,

I tried NameObjectCollectionBase and it works fine for me. I wrote only one
Add method with the parameter of the base class and it returns correct class
names of the entries as expected.

However, unlike Hashtable and DictionaryBase
System.Collections.Specialized.NameObjectCollectio nBase allows you to have
more then one entry in the collection with the same name (key). In this case
BaseGet method returns always the first one. So my guess is that due to some
error in your code you add all objects under the same name (key) and/or read
the same key regardless what you pass as a object name to your get method.
In those cases if first elemet added in the collection is of type BaseType
it will return the same object over and over again. So check how you
generate the names for the objects.
Anyway, I'm little confused that adding overloads for the Add method solves
your problem. So my next guess is that you make some kind of cloning the
objects before adding them to the collection.
For example.

class Base: ICloneable
{
public object Clone()
{
return new Base(); //Clone the object
}
}

class Deriv1:Base, ICloneable
{
public object Clone()
{
return new Deriv1(); //Clone the object
}
}

and then you have

public void Add(string name, Base obj)
{
base.BaseAdd(name, obj.Clone());
}

This will lead to the results you had. The type of the objects in the
collection will always be Base.
Ofcourse the compiler thorws warning message and underlines Deriv1.Cone
method. But there are some situations where you can miss those hints.

The fact that you had those problems means that there is something wrong in
your code.

HTH
B\rgds
100
".pd." <sp*****@your.peril> wrote in message
news:Xn*****************************@194.83.179.10 2...
100 wrote on Wed 17 Dec 2003 05:58:56p:
Hi .pd,
GetType returns the real type of the object not the type of the
variable used to reference the object. In other words it has to work
for you. Are you sure your BaseGet(...) method works correctly?


So you're telling me I have write my own GetType()? I was afraid of that.

BaseGet() is a method belonging to the
System.Collections.Specialized.NameObjectCollectio nBase class. It ain't
mine.

.pd.

Nov 15 '05 #7
100 wrote on Thu 18 Dec 2003 03:07:26p:
The fact that you had those problems means that there is something
wrong in your code.
Yeah. Jiggered if I know what though.

Jon Skeet [C# MVP] wrote on Thu 18 Dec 2003 12:18:21p:
That should make no difference though, as each derived type *is* an
instance of the base type.
By replacing this with an overload for each derived type, it now
works as I expected.


Really not sure what you mean here, but never mind - I'm glad you've
got it working.


Yeah it's weird. I wrote a reproducer but it didn't reproduce ;-)

I also reverted to a single constructor taking the base type and that
then worked. Obviously, I did something different the previous time but
failed to notice it.

I've included my sample code (which, as I say, works fine) purely as a
matter of record.

Cheers,
..pd.

// ---------8<-------------
using System;
using System.Collections;

namespace foo
{
public class myList :
System.Collections.Specialized.NameObjectCollectio nBase
{
public myBase this[string name]
{
get
{
return (myBase) BaseGet(name);
}
}

// changing this to an overload for each specific inheritor of myBase
// fixed the original problem.
// public void Add(string s, myDerived1 b) {}
// public void Add(string s, myDerived2 b) {}

public void Add(string s, myBase b)
{
BaseAdd(s, b);
}

}
public class myBase
{
}
public class myDerived1 : myBase
{
}
public class myDerived2 : myBase
{
}
public class pd
{
public static void Main()
{
myList ml = new myList();

ml.Add("fred", (myBase) new myDerived1());
ml.Add("barny", (myBase) new myDerived2());

Console.WriteLine(ml["fred"].GetType().Name);
Console.WriteLine(ml["barny"].GetType().Name);

}
}
}
Nov 15 '05 #8

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

Similar topics

6
by: Jacek Dziedzic | last post by:
Hello! First of all please forgive me for not posting a compilable snippet, but rather a simplified piece of code with the unimportant details left out. Let's say I have two classes...
10
by: Yechezkal Gutfreund | last post by:
I have two subclasses of SpriteModel (1) LocalSprite (2)Sprite Both implement a method called .ToXml() which returns an XmlDocument. But they are different. I instances of these objects...
10
by: Lino Barreca | last post by:
Take a look at this code: Class clsAnagrafica Public Overridable ReadOnly Property Codice() As Integer Get Return 1 End Get End Property End Class
14
by: Jerad Rose | last post by:
I'm relatively new to C# and polymorphism, so what I'm trying to accomplish may not be possible, or there may be a totally different approach that I should be taking. I have a base class...
2
by: sarathy | last post by:
Hi all, I need a small clarification reg. Templates and Polymorphism. I believe templates is really a good feature, which can be used to implement generic functions and classes. But i doubt...
9
by: James Crosswell | last post by:
I'm not sure if I'm going about this the right way - it may be that Generics might be able to help me out here... but here goes: I have three classes as follows class BaseEdit class WidgetEdit:...
8
by: crjjrc | last post by:
Hi, I've got a base class and some derived classes that look something like this: class Base { public: int getType() { return type; } private: static const int type = 0; };
11
by: chsalvia | last post by:
I've been programming in C++ for a little over 2 years, and I still find myself wondering when I should use polymorphism. Some people claim that polymorphism is such an integral part of C++,...
17
by: Bart Friederichs | last post by:
Hello, I created the following inheritance: class Parent { public: void foo(int i); }; class Child : public Parent {
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.