473,569 Members | 2,536 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

runtime casting

I want to replace CSomeObject class with some kind of runtime method
that returns type CSomeObject that I can use as cast.

How do I specify type of explicit cast at runtime?

eg:

object object1 = new CSomeObject(22) ;
object object2 = new CSomeObject(2);
if ( ( runtime method returns class CSomeObject ) object1 > ( runtime
method returns CSomeObject ) object2 )
// ... etc
// won't work because compiler error "Operator '>' cannot be applied to
operands of type 'object' and 'object' " :

if (object1 > object)
// ...etc
Richard

Dec 16 '05 #1
10 13475
I think you are asking 2 different questions:
1) How do I convert an object to a type that is returned at runtime
2) How do I compare 2 objects when I do not know their type at compile time?

I separate them, because I can answer each one, but not necessarily your
original question.

To convert an object to a type that is determined at runtime, you
Covert.ChangeTy pe(). Example:

public Type RuntimeMethodRe turnsSomeType() {
return typeof(CSomeObj ect);
}

object object1 = Convert.ChangeT ype( object2,
RuntimeMethodRe turnsSomeType() );

Now object2 has been converted to a CSomeObject. However, it is still
stored in an 'object' variable, so you can still only perform actions
that can be performed on an object (which does not include comparisons
using >).
If you want to compare 2 objects without knowing their type, you can
cast them to IComparable.

object a = 3;
object b = 4;

if ( ((IComparable)a ).CompareTo( b ) > 0 )
{
Console.WriteLi ne("a is greater");
}
else
{
Console.WriteLi ne("b is greater");
}

If you can't guarantee that the underlying type implements IComparable,
or are the same type, you may want to do some additional checking...

object a = 3;
object b = 4;

IComparable aComparable = a as IComparable;
if ( a != null && a.GetType() == b.GetType() ) {
if (a.CompareTo(b) > 0) {
// do stuff when a is greater than b
}
else {
// do stuff when b is greater (or equal) to a
}
}
else {
// do stuff when the objects cannot be compared
}
Hope this helps

Joshua Flanagan
http://flimflan.com/blog
Dec 16 '05 #2
I understand what you are getting at. I was hoping for a much simpler
solution like this:

Type t = someinstance.Ge tType();
if( (t)object > (t)object )
// etc

Maybe MS can add this feature in the next release of C#?

Thanks for the tips on Convert.ChangeT ype and IComparable.

Richard

Dec 16 '05 #3
What is the underlying problem you're trying to solve? What is that
you're trying to do? Maybe there's a better way to approach the problem
that doesn't require new language features. Post the details of your
problem, and perhaps someone here can suggest a different approach.

Dec 16 '05 #4
Rich wrote:
I understand what you are getting at. I was hoping for a much simpler
solution like this:

Type t = someinstance.Ge tType();
if( (t)object > (t)object )
// etc


I don't foresee that being added as a feature. In order for that to
work, the compiler would have to be able to guarantee that the >
operator is a valid operation for an object of type T. If type T can be
any type, there is no way the compiler could assert that as a valid line
of code.
It would only work if you could restrict T to being only types that
support the > comparison operation. That is exactly what you accomplish
by casting to IComparable.
Dec 17 '05 #5
Rich wrote:
I understand what you are getting at. I was hoping for a much simpler
solution like this:

Type t = someinstance.Ge tType();
if( (t)object > (t)object )
// etc Type t= someinstance.Ge tType();
//operator< with two arguments of type t
MethodInfo mi = t.GetMethod("op _LessThan", new Type[]{t, t} )
//execute op<. operators are static, so pass null for the instance
bool b = (bool)mi.Invoke (null, new object[]{object1, object2});

Maybe MS can add this feature in the next release of C#?

Thanks for the tips on Convert.ChangeT ype and IComparable.

Richard

This feature is senseless, as the information has to be retrieved at
runtime, not static at compile time. And as shown above, it already
works at runtime :-)

HTH,
Andy

Dec 17 '05 #6
Rich wrote:
I understand what you are getting at. I was hoping for a much simpler
solution like this:

Type t = someinstance.Ge tType();
if( (t)object > (t)object )
// etc Type t= someinstance.Ge tType();
//operator< with two arguments of type t
MethodInfo mi = t.GetMethod("op _LessThan", new Type[]{t, t} )
//execute op<. operators are static, so pass null for the instance
bool b = (bool)mi.Invoke (null, new object[]{object1, object2});
Maybe MS can add this feature in the next release of C#?

Thanks for the tips on Convert.ChangeT ype and IComparable.

Richard

This feature is senseless, as the information has to be retrieved at
runtime, not static at compile time. And as shown above, it already
works at runtime :-)

HTH,
Andy
Dec 17 '05 #7
A - Thanks for that answer. Unfortunately, I won't be able to call the
overloaded operator (eg static CSomeClass operator +(CSomeClass
a,CSomeClass b); ) through the MethodInfo.Invo ke method. Same issue
with the interface method.

Richard

Dec 17 '05 #8
Rich wrote:
A - Thanks for that answer. Unfortunately, I won't be able to call the
overloaded operator (eg static CSomeClass operator +(CSomeClass
a,CSomeClass b); ) through the MethodInfo.Invo ke method. Same issue
with the interface method.

Richard

Can you be more specific? Operators are static methods of a type. You
example can be done like this:

using System;
using System.Diagnost ics;
using System.Reflecti on;

namespace Xox
{
class Lulli
{
public static int operator +(Lulli e, Exception a)
{
return 42;
}
public static int operator +(Lulli e, Attribute a)
{
return 55;
}
}
class Program
{
static void Main(string[] args)
{
MethodInfo mi =
typeof(Lulli).G etMethod("op_Ad dition",
new Type[] {
typeof(Lulli),
typeof(Exceptio n)
}
);

Debug.Assert(mi != null);

int i = (int)mi.Invoke( null, new object[] { new Lulli(),
new Exception() });
Debug.Assert(i == 42);
}
}
}
Dec 18 '05 #9
Here is the eg:

public class CDouble
{
private double d;
public CDouble(double d)
{
this.d = d;
}
public static CDouble operator +(CDouble d1,CDouble d2)
{
return new CDouble(d1.d + d2.d);
}
}
public class App
{

object obj1 = new CDouble(2.0);
object obj2 = new CDouble(3.33);

Type t = obj1.GetType();
MethodInfo mi = obj1.GetType(). GetMethod( "operator +",new
Type[]{t,t} ); // this won't work
object obj_result = mi.Invoke( null , new object[]{ obj1 , obj2 }
);

}

Dec 18 '05 #10

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

Similar topics

2
2427
by: Dave | last post by:
Hello all, I am creating a linked list implementation which will be used in a number of contexts. As a result, I am defining its value node as type (void *). I hope to pass something in to its "constructor" so that I will be able to manipulate my list without the need for constant casting; some sort of runtime type-safety mechanism. For...
2
5478
by: MattC | last post by:
Hi, How can do runtime casting? MyCollection derives from ArrayList I will store lost of different objects that all derive from the same parent class. I then want to be able to pass in the object type and collection type I have a number of classes that derive from ArrayList and have if pick out on ly those i asked for.
4
2275
by: AdamM | last post by:
How can I change an object's type at runtime? For example, here's what I want to do in psedocode: object animal; if (dog) { animal=(dog)animal;
0
1007
by: Eric Chaves | last post by:
Hi folks, Im writing a small GUI application to deploy objects that allows a user to create my objects, set it's properties, serialize it into a binary package for futher load into production enviroment. Among those "properties", the GUI allows a user to create delegates at runtime and bind it to the object's events. Hoever I'could see a...
4
219
by: Marco | last post by:
I can't convert data to runtime. class User { public User(string first,string last) { this.first=first; this.last=last;
7
11928
by: Martin Robins | last post by:
I am currently looking to be able to read information from Active Directory into a data warehouse using a C# solution. I have been able to access the active directory, and I have been able to return "DirectoryEntry" objects within the path that I specify (either using the DirectoryEnrtry.Children or using the DirectorySearcher class) and all...
2
2019
by: eric.dennison | last post by:
In the sample below: testClass is derived from object. We can cast object to testClass, no problem We can cast testClass to object no problem Compiler is ok with cast object to testClass but fails at runtime. Why?
13
3027
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...
16
5404
by: desktop | last post by:
I have read that using templates makes types know at compile time and using inheritance the types are first decided at runtime. The use of pointers and casts also indicates that the types will first be know at runtime. But is there some strict definitions that defines runtime code and compile time code that can be used in general?
0
7924
Oralloy
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. ...
0
8125
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...
0
6284
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...
1
5513
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...
0
5219
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...
0
3653
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...
0
3642
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2114
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1221
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.