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 2 4727
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
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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.
|
by: Radde |
last post by:
HI,
Are ther any pitfalls for dynamic cast in type safe downcasting..
|
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
|
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;
}
|
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) ....
| |
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;
|
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)
{
|
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
|
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...
|
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...
|
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,...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
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...
|
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,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |