How: To get true dynamic polymorphism (i.e. smalltalk)

  • Thread starter Thread starter Yechezkal Gutfreund
  • Start date Start date
Y

Yechezkal Gutfreund

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 stored in a Hashtable. Extracting them from the
Hashtable means that I get a object that is tentatively an instance of Class
Object (or Type Object to use the correct C# word).

I can HARD cast the object to a SpriteModel, and then invoke the .ToXml()
method, but if either of these sublcasses overrides or NEWs the default
method in SpriteModel. I can't get to it.

What I want to do is dynamically cast the object extracting from the
Hashtable to it's .GetType

realType = spriteList.Value.GetType()

and then do something like a dynamic cast (realType)spriteList.Value

Obviously, this is very wrong syntacically, but there most be something that
is kosher that does the same effect? right? I don't have to resort to
Reflection and P/Invoke do I?



public override string ToString()
{
StringBuilder response = new StringBuilder();
lock (this.spriteTable) {
IDictionaryEnumerator spriteList = this.spriteTable.GetEnumerator();
while (spriteList.MoveNext())
{
SpriteModel sprite = (SpriteModel)spriteList.Value;
response.Append(Tools.PrettyPrint(sprite.ToXml().DocumentElement));
response.Append("\r\n");
}
}
return response.ToString();
}
 
To put this in TCL/TK or Smalltalk way of speaking I am looking for the
equivelent of

(random object).performMethod("named method")

I.e. I want to invoke methods dynamically at run-time

Assume I already did the checking that this method is implemented by the
object, so that I don't get a run-time error

[Yes, I am not a fan of 100% rigidly hard-typed systems, since there are
times where one needs to get around this]


--
==================================
Yechezkal Gutfreund
Chief Scientist
Kesser Technical Group, Inc.
==================================
 
Yechezkal said:
I.e. I want to invoke methods dynamically at run-time

Then all you need do is mark the ToXml method as virtual in the
SpriteModel class. In each of the drived classes, mark the ToXml method
as an override. Just as in C++ and many other languages, this will cause
the most derived implementation of the method to execute when invoked
from a reference to a base class.

Once done, you can cast every object as a SpriteModel and you'll get the
correct results.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)
 
Then go code SML or some other weird language.


Yechezkal Gutfreund said:
To put this in TCL/TK or Smalltalk way of speaking I am looking for the
equivelent of

(random object).performMethod("named method")

I.e. I want to invoke methods dynamically at run-time

Assume I already did the checking that this method is implemented by the
object, so that I don't get a run-time error

[Yes, I am not a fan of 100% rigidly hard-typed systems, since there are
times where one needs to get around this]


--
==================================
Yechezkal Gutfreund
Chief Scientist
Kesser Technical Group, Inc.
==================================


Yechezkal Gutfreund said:
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 stored in a Hashtable. Extracting them from the
Hashtable means that I get a object that is tentatively an instance of Class
Object (or Type Object to use the correct C# word).

I can HARD cast the object to a SpriteModel, and then invoke the ..ToXml()
method, but if either of these sublcasses overrides or NEWs the default
method in SpriteModel. I can't get to it.

What I want to do is dynamically cast the object extracting from the
Hashtable to it's .GetType

realType = spriteList.Value.GetType()

and then do something like a dynamic cast (realType)spriteList.Value

Obviously, this is very wrong syntacically, but there most be something that
is kosher that does the same effect? right? I don't have to resort to
Reflection and P/Invoke do I?



public override string ToString()
{
StringBuilder response = new StringBuilder();
lock (this.spriteTable) {
IDictionaryEnumerator spriteList = this.spriteTable.GetEnumerator();
while (spriteList.MoveNext())
{
SpriteModel sprite = (SpriteModel)spriteList.Value;
response.Append(Tools.PrettyPrint(sprite.ToXml().DocumentElement));
response.Append("\r\n");
}
}
return response.ToString();
}
 
Try reflection:

someobject.GetType().GetMethod("ToXml").Invoke
(m_someobject,new object[] {});

Or:

You could try an instance factory, setup your types in
there and make sure your objects implement an interface
you setup in there (look at .NET remoting for an example I
know thats not what your doing but its essentially what
that does), i.e.

public interface IImplementXML
{
XmlDocument ToXml
}

public class SomeObject: IImplement
{
public XmlDocument ToXml
{
get xml document
}
}

public class SomeOtherObject: IImplement
{
public XmlDocument ToXml
{
get xml document
}
}

IImplement iXMLDocument = (IImplement)
BusinessInstanceFactory.CreateInstance(typeof(IImplement));

iXMLDocument.ToXml
 
You could use reflection to navigate the class hierarchie of your object and
choose the implementation of the method XYZ you are looking for. (look into
System.Reflection namespace)

JPRoot



Yechezkal Gutfreund said:
To put this in TCL/TK or Smalltalk way of speaking I am looking for the
equivelent of

(random object).performMethod("named method")

I.e. I want to invoke methods dynamically at run-time

Assume I already did the checking that this method is implemented by the
object, so that I don't get a run-time error

[Yes, I am not a fan of 100% rigidly hard-typed systems, since there are
times where one needs to get around this]


--
==================================
Yechezkal Gutfreund
Chief Scientist
Kesser Technical Group, Inc.
==================================


Yechezkal Gutfreund said:
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 stored in a Hashtable. Extracting them from the
Hashtable means that I get a object that is tentatively an instance of Class
Object (or Type Object to use the correct C# word).

I can HARD cast the object to a SpriteModel, and then invoke the ..ToXml()
method, but if either of these sublcasses overrides or NEWs the default
method in SpriteModel. I can't get to it.

What I want to do is dynamically cast the object extracting from the
Hashtable to it's .GetType

realType = spriteList.Value.GetType()

and then do something like a dynamic cast (realType)spriteList.Value

Obviously, this is very wrong syntacically, but there most be something that
is kosher that does the same effect? right? I don't have to resort to
Reflection and P/Invoke do I?



public override string ToString()
{
StringBuilder response = new StringBuilder();
lock (this.spriteTable) {
IDictionaryEnumerator spriteList = this.spriteTable.GetEnumerator();
while (spriteList.MoveNext())
{
SpriteModel sprite = (SpriteModel)spriteList.Value;
response.Append(Tools.PrettyPrint(sprite.ToXml().DocumentElement));
response.Append("\r\n");
}
}
return response.ToString();
}
 
Hi Yechezkal,

In .Net you can reflection to dynamic determine a reference's type.
So you can do like John said, use reflection to dynamic create subclass's
method.

What I want to supplement is that you can use "as" or "is" keyword in C# to
dynamic detect the reference's type.
For more usage and information of these 2 keyword, please refer to :
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/
vclrfispg.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/
vclrfAs.asp

Hope this helps,

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
Yechezkal said:
I have two subclasses of SpriteModel (1) LocalSprite (2)Sprite

Both implement a method called .ToXml() which returns an XmlDocument. But
they are different.

Being a *really* long time Smalltalker (among other languages) I can tell
you: dont try to emulate the inheritance/method lookup/polymorphism of an
untyped language in a type language. Class trees grow differently in C#
compared to Smalltalk (and I prefer the way of Smalltalk of real life
modelling).

You have to understand that typed class hierarchies model implementation
variance while a Smalltalk class hierarchy models a behaviour variance.

To achive a Smalltalk-alike model you need to group classes of similar
behavior (behavior equivalence classes) in your implementation class trees
through interfaces. That means, all classes of a Smalltalk model that can be
used in Smalltalk at the same place because they have the same behavior now
need to be put into an interface. Since you cannot predict who is using your
class hierarchy using what polymorphy, you either implement as many
interfaces as sensible or you distribute source.

In you trivial example, introduce an interface encapsuling ToXml() and cast
your subclass instances to that interface. Then the right method is invoked
(irregardless of new, virtual and override modifiers).

Summary: translate a Smalltalk model class hierarchy by putting the class
behavior into interfaces and let possibly unrelated C# classes implement
these interfaces. Then to use instances in a polymorphic way, cast to the
interfaces.

Hope that helped a bit.

Andreas
 
Frank,

Are you really sure this works?

As you can see from my code, the object of type Sprite and SpriteLocal are
stored in a Hashtable.
When you pull then out (e.g. mySprite = theHashTable[key]) you are given
something of type
object. You will get a syntax error unless you say:

Object mySprite = theHashTable[key]

or

SpriteMode mySprite = (SpriteModel)theHashTable[key]

This is gotcha of strong type-ing.

I have to forcibly cast this object to either an Object, Sprite,
SpriteModel, or SpriteLocal. But since there
are mixed items in this table, I don't know the answer till runtime.

Currenly, I am casting everything to (SpriteModel) but then it never invokes
the child's ToXML() method. but rather the SpriteModel version.

Reflection, on the other hand, should allow runtime invokation.
 
Currenly, I am casting everything to (SpriteModel) but then it never
invokes
the child's ToXML() method. but rather the SpriteModel version.

That doesn't sound right. With C#, if the ToXML() method is marked as
"virtual" or "abstract", and if the ToXML() method on the child classes is
marked as "override," then the runtime SHOULD and WILL use runtime
polymorphism. It doesn't matter if your object is cast to "SpriteModel" or
the specific child class. The runtime handles it for your (using a vtable).

Can you give us an example of your code? I'm having trouble understanding
why a "virtual" in the parent and "override" in the child won't do what you
want.

Or am I not understanding your problem?

--Matthew W. Jackson
 
Andreas said:
In you trivial example, introduce an interface encapsuling ToXml()
and cast your subclass instances to that interface. Then the right
method is invoked (irregardless of new, virtual and override
modifiers).

While interfaces are quite useful, they should be used as intended: for
homogeneous handling of heterogeneous objects. Such is not the case
here. A little attention to detail, not additional layers of
indirection, is all that is needed to solve the problem.

--
There are 10 kinds of people. Those who understand binary and those who
don't.

http://code.acadx.com
(Pull the pin to reply)
 
Yechezkal,
This is gotcha of strong type-ing.
If you want to avoid the benefits of strong type-ing, then you may want to
stay with Small Talk or try your hand at VB.NET. VB.NET is not as "loose-ly"
typed as Small Talk, however when you have Option Strict Off in VB.NET you
have much the same benefits as small talk, as you incur the expense of a
runtime check to see if the method is implemented on that object.

In other words VB.NET hides the reflection lookup from you, in much the same
method as Small Talk does, and allows you to call any method on a object you
want. At runtime it will either succeed or fail, depending on whether the
object actually supports that method.

Personally I find the performance & safety of strong type-ing far outways
the perceived benefits of late binding. However the late binding (Option
Strict Off) in VB.Net is very helpful in a number of cases...

Hope this helps
Jay


Yechezkal Gutfreund said:
Frank,

Are you really sure this works?

As you can see from my code, the object of type Sprite and SpriteLocal are
stored in a Hashtable.
When you pull then out (e.g. mySprite = theHashTable[key]) you are given
something of type
object. You will get a syntax error unless you say:

Object mySprite = theHashTable[key]

or

SpriteMode mySprite = (SpriteModel)theHashTable[key]

This is gotcha of strong type-ing.

I have to forcibly cast this object to either an Object, Sprite,
SpriteModel, or SpriteLocal. But since there
are mixed items in this table, I don't know the answer till runtime.

Currenly, I am casting everything to (SpriteModel) but then it never invokes
the child's ToXML() method. but rather the SpriteModel version.

Reflection, on the other hand, should allow runtime invokation.
 
[This followup was posted to microsoft.public.dotnet.framework and a
copy was sent to the cited author.]

To put this in TCL/TK or Smalltalk way of speaking I am looking for the
equivelent of

(random object).performMethod("named method")

I.e. I want to invoke methods dynamically at run-time

Assume I already did the checking that this method is implemented by the
object, so that I don't get a run-time error

[Yes, I am not a fan of 100% rigidly hard-typed systems, since there are
times where one needs to get around this]
In my opinion Frank Oquendo's response is in the correct track.
 
Back
Top