473,403 Members | 2,293 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,403 software developers and data experts.

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 13436
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.ChangeType(). Example:

public Type RuntimeMethodReturnsSomeType(){
return typeof(CSomeObject);
}

object object1 = Convert.ChangeType( object2,
RuntimeMethodReturnsSomeType() );

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.WriteLine("a is greater");
}
else
{
Console.WriteLine("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.GetType();
if( (t)object > (t)object )
// etc

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

Thanks for the tips on Convert.ChangeType 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.GetType();
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.GetType();
if( (t)object > (t)object )
// etc Type t= someinstance.GetType();
//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.ChangeType 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.GetType();
if( (t)object > (t)object )
// etc Type t= someinstance.GetType();
//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.ChangeType 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.Invoke 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.Invoke 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.Diagnostics;
using System.Reflection;

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).GetMethod("op_Addition",
new Type[] {
typeof(Lulli),
typeof(Exception)
}
);

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
Rich wrote:
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 }
);

}

Will work if you replace "operator +" with "op_Addition" ;-):

MethodInfo mi=obj1.GetType().GetMethod( "op_Addition",new Type[]{t,t});
Dec 18 '05 #11

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

Similar topics

2
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...
2
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...
4
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
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...
4
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
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...
2
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...
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...
16
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
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...
0
tracyyun
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...
0
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...

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.