M
Martin Hart - Memory Soft, S.L.
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
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