Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Dynamic casting and dynamic variables.

0 views
Skip to first unread message

Martin Hart - Memory Soft, S.L.

unread,
Apr 5, 2004, 1:39:47 PM4/5/04
to
Hi all:

I still very new to the .NET world and don't know if what I am asking is due
to an over-imaginative imagination or the fact that I have read too many
fiction books!!

Let me show you a very basic scenario:

[Example]
using System;

namespace DynamicCasts
{
public class BaseClass
{
public int SharedInt;
public BaseClass()
{
}
}

public class DerivedClass1 : BaseClass
{
public int Int1;
public DerivedClass1()
{
}
}

public class DerivedClass2 : BaseClass
{
public int Int2;
public DerivedClass2()
{
}
}

public class Test
{
[STAThread]
static void Main()
{
DerivedClass1 dc1 = new DerivedClass1();
DerivedClass2 dc2 = new DerivedClass2();
DoSomeThing(dc1);
DoSomeThing(dc2);
}

static public void DoSomeThing(BaseClass bc)
{
Type myType = bc.GetType();
// How can I do dynamic casting?
if(myType.Name == "DerivedClass1")
((??)bc).Int1 = 33; //----------Here!!
else if(myType.Name == "DerivedClass2")
((??)bc).Int2 = 33; //----------Here!!

// Can I also define a variable based on myType's type and then
manipulate the variable?

}
}
}
[/Example]

I am looking for a way to dynamically cast the BaseClass variable to its
derived type and assign a value to one of its fields.

Secondly, through Reflection, can I define a variable based on the Type of
the object passed to the method (i.e. DerivedClass1 or DerivedClass2) and
then change the Int1 or Int2 field based on this variable?

Thanks for your time,

Martin Hart
Memory Soft


Tom

unread,
Apr 5, 2004, 1:48:17 PM4/5/04
to
Can you dynamically cast a variable to any type? Yes, one technique would be
to create multiple interfaces (IDerivedClass1, IDerivedClass2) and cast your
variable to the appropriate interface which would then let you call the
methods specific to the given interface. Another, simplier but probably less
effective technique would be to use the Convert.ChangeType method.
Unfortunately, with ChangeType, it does not mean you can then call a method
on that type at runtime using a design-time call because ChangeType returns
an object.

The only way to accomplish a truly dynamic method call would be through
reflection and the Type.InvokeMember method.


HTH,


Tom

"Martin Hart - Memory Soft, S.L." <memorysoftsl _at_ infotelecom _dot_ es>
wrote in message news:OxR%239TzGE...@TK2MSFTNGP12.phx.gbl...

Martin Hart - Memory Soft, S.L.

unread,
Apr 6, 2004, 2:07:02 AM4/6/04
to
Hmm, lots of food for thought.

Thanks Tom, I'll look into using interfaces I think this might do the trick.

Regards,
Martin.

"Tom" <answerinth...@anywhere.com> escribió en el mensaje
news:%23kZLMZz...@TK2MSFTNGP09.phx.gbl...

0 new messages