473,756 Members | 1,823 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(Bas eClass 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 4724
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.ChangeT ype 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.InvokeMemb er method.
HTH,
Tom

"Martin Hart - Memory Soft, S.L." <memorysoftsl _at_ infotelecom _dot_ es>
wrote in message news:Ox******** ********@TK2MSF TNGP12.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(Bas eClass 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******** *******@TK2MSFT NGP09.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.ChangeT ype 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.InvokeMemb er 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
2179
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 registration to business office. We are considering useing Java or Python. I for one don't like Java because I feel the GUI is clunky. I also think that we could produce quality programs faster in Python.
5
8013
by: Radde | last post by:
HI, Are ther any pitfalls for dynamic cast in type safe downcasting..
10
2781
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: "At a certain point in the code you may be unsure if a particular block is no longer needed. If you free() this piece of memory, but continue to access it (probably via a second pointer to the same
3
1681
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
1314
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 from base class, and casting, derived classes would already have their variables initialiezed(cause they have already been initialized in the base class) ....
2
673
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 very basic scenario: using System;
2
1715
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 (Object item in row.ItemArray) {
2
1607
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 operators like variable == a string or a double ore anything else in C# I thought to build a classes that wraps an object (untypized) and typize it inside it and to overload operators. In the code below there's an
13
3044
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 have two object which have a common base class, they can both be cast up to the base class, but if either of the child classes have unuque methods you will not be able to access them. Now I know about late binding and all that stuff, but I need...
2
5655
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 the tables and their links. When getting the data from the DB... well suffice to say it's ugly. I want to use one stored procedure that will return a result set as (name, value) pairs so I can display it nice and easy in the UI. So far I've managed to...
0
9456
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9275
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9872
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9843
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8713
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7248
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5142
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3358
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.