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

Dynamic casting and dynamic variables.

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
Nov 16 '05 #1
2 4669
Tom
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:Ox****************@TK2MSFTNGP12.phx.gbl...
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

Nov 16 '05 #2
Hmm, lots of food for thought.

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

Regards,
Martin.

"Tom" <an******************@anywhere.com> escribió en el mensaje
news:%2***************@TK2MSFTNGP09.phx.gbl...
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

Nov 16 '05 #3

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

Similar topics

12
by: Jason Tesser | last post by:
I work for at a college where I am one of 2 full-time developers and we are looking to program a new software package fro the campus. This is a huge project as it will include everything from...
5
by: Radde | last post by:
HI, Are ther any pitfalls for dynamic cast in type safe downcasting..
10
by: s.subbarayan | last post by:
Dear all, I happen to come across this exciting inspiring article regarding memory leaks in this website: http://www.embedded.com/story/OEG20020222S0026 In this article the author mentions:...
3
by: Kurt | last post by:
i just can't figure out why something im doing is not working correctly.... public interface IInterface { int someProperty { get; set; }
0
by: Kurt Lange | last post by:
no... the array is created dynamically. and no... that defeats the purpose of what im trying todo.. encapsulate all initializing of variables in base class... derive from it... by deriving...
2
by: Martin Hart - Memory Soft, S.L. | last post by:
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...
2
by: keithb | last post by:
I'm trying to understand C# type casting. The following code will not compile unless I Cast item to a String. private static String myData; foreach (DataRow row in MyTable.Rows) { foreach...
2
by: Giulio Petrucci | last post by:
Hi everybody, here's my problem: I have to dymanically build (and compile, of course) some code, from some ECMAScript function. ECMAScript variables I get are not typezed, so I should have...
13
by: DaTurk | last post by:
Hi, This is a question brought about by a solution I came up with to another question I had, which was "Dynamic object creation". So, I'm curious if you can dynamically cast an object. If you...
2
by: IuliaS | last post by:
Hello everyone! I want to create a stored procedure, so I can more easily, and transparent retrieve data from db2. Long story short: when a user wants to put some data in the DB, he also creates...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
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: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
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...
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: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.