473,545 Members | 4,241 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Runtime type cast in C#

mra
I want to cast an object that I have created from a typename to the
corresponding type. Can anycone tell me how to do this?
Example:
//Here, Create the object of type "MyClass"
object obj=Activator.C reateInstance(s trAssemblyName, "MyClass");
//Now, I want to do something like ((MyClass)obj). Method
//Can I do this?
Nov 16 '05 #1
3 21207
mra,

If you have a reference to the type, then yes, you can, just cast the
return value like you would normally.

My assumption is that you do not have a reference to that type, and that
you are loading the type through a call to one of the Load overloads on the
Assembly class.

In this case, you will want to define an interface or a base class in
another assembly, and have your type implement that. Then, in the assembly
that loads and creates the type, you cast the return value to the interface,
and make your calls.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"mra" <mr*@discussion s.microsoft.com > wrote in message
news:D5******** *************** ***********@mic rosoft.com...
I want to cast an object that I have created from a typename to the
corresponding type. Can anycone tell me how to do this?
Example:
//Here, Create the object of type "MyClass"
object obj=Activator.C reateInstance(s trAssemblyName, "MyClass");
//Now, I want to do something like ((MyClass)obj). Method
//Can I do this?

Nov 16 '05 #2
mra
Hi, Nicholas, unfortunately, its not so easy.
In reality, I have a function that returns an object. What kind of object
this is (class) is defined by the typename string:
object MyFunction ([...parameters], typename);

If you call this function as indicated, it will return an integer:
object obj=MyFunction([...parameters], "System.Int32") ;

I want to do something like:
int i=MyFunction([...parameters], "System.Int32") ;
This does not work, because you cannot assign an object to an int.

Ideally, there would be a possibility to say:
int i=(runtime type cast to int)MyFunction([...parameters], "System.Int32") ;

where the (runtime type cast) should take a string with the typename as an
argument. Any idea?

"Nicholas Paldino [.NET/C# MVP]" wrote:
mra,

If you have a reference to the type, then yes, you can, just cast the
return value like you would normally.

My assumption is that you do not have a reference to that type, and that
you are loading the type through a call to one of the Load overloads on the
Assembly class.

In this case, you will want to define an interface or a base class in
another assembly, and have your type implement that. Then, in the assembly
that loads and creates the type, you cast the return value to the interface,
and make your calls.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"mra" <mr*@discussion s.microsoft.com > wrote in message
news:D5******** *************** ***********@mic rosoft.com...
I want to cast an object that I have created from a typename to the
corresponding type. Can anycone tell me how to do this?
Example:
//Here, Create the object of type "MyClass"
object obj=Activator.C reateInstance(s trAssemblyName, "MyClass");
//Now, I want to do something like ((MyClass)obj). Method
//Can I do this?


Nov 17 '05 #3
You may just be able to do this if your types have built in conversions
int i = Convert.Int32(M yFunction(...))
string s = Convert.ToStrin g(MyFunction(.. .))

If you have more complicated conversions, but a limited number of return
types, you can do it without an explicit cast. Instead of returning
"object", create a new class for return type that knows how to convert
object to whatever you want. An example is below that defines the class
MultiType and uses it for string and int.

If you want MyFunction() to return an "object" and not a MultiType
instance, you can do
int i = new MultiType(MyFun ction(...,"Syst em.Int32"));

and if you want to specify what you are converting to, you can do
int i = new MultiType("Syst em.Int32",
MyFunction(..., "System.Int32") );

Or you can add a static method Cast() to MultiType that
int i = MultiType.Cast( "System.Int 32",
MyFunction(..., "System.Int32") );
Cast() just needs to instantiate a MultiType().

There are many other things you can do, even handling types that are not
known at compile time (e.g. come from dynamically selected/loaded
assemblies). In the later case, you may need to require that the
assembly provides the necessary conversions depending on exactly what
types of conversions you are doing.
using System;

namespace casttest
{

class MultiType
{
object o;
public MultiType(objec t o) { this.o = o;}

static public implicit operator System.Int32(Mu ltiType m)
{
return int.Parse(m.o.T oString());
// or
// return (int)o;
// if you know it is an int
}

static public implicit operator System.String(M ultiType m)
{
return m.o.ToString();
}
}

/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
MultiType MyFunction(obje ct oin,string typename)
{
object o = null;
if (typename.Equal s("System.Int32 "))
{
o = (int)oin;
}
else if (typename.Equal s("System.Strin g"))
{
o = (string)oin;
}
return new MultiType(o);
}

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Class1 c = new Class1();
int i = c.MyFunction(1, "System.Int32") ;
string s = c.MyFunction("t ext","System.St ring");
Console.WriteLi ne("results " + i + " " + s);
}
}
}
mra wrote:
Hi, Nicholas, unfortunately, its not so easy.
In reality, I have a function that returns an object. What kind of object
this is (class) is defined by the typename string:
object MyFunction ([...parameters], typename);

If you call this function as indicated, it will return an integer:
object obj=MyFunction([...parameters], "System.Int32") ;

I want to do something like:
int i=MyFunction([...parameters], "System.Int32") ;
This does not work, because you cannot assign an object to an int.

Ideally, there would be a possibility to say:
int i=(runtime type cast to int)MyFunction([...parameters], "System.Int32") ;

where the (runtime type cast) should take a string with the typename as an
argument. Any idea?

"Nicholas Paldino [.NET/C# MVP]" wrote:

mra,

If you have a reference to the type, then yes, you can, just cast the
return value like you would normally.

My assumption is that you do not have a reference to that type, and that
you are loading the type through a call to one of the Load overloads on the
Assembly class.

In this case, you will want to define an interface or a base class in
another assembly, and have your type implement that. Then, in the assembly
that loads and creates the type, you cast the return value to the interface,
and make your calls.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"mra" <mr*@discussion s.microsoft.com > wrote in message
news:D5****** *************** *************@m icrosoft.com...
I want to cast an object that I have created from a typename to the
correspondin g type. Can anycone tell me how to do this?
Example:
//Here, Create the object of type "MyClass"
object obj=Activator.C reateInstance(s trAssemblyName, "MyClass");
//Now, I want to do something like ((MyClass)obj). Method
//Can I do this?


Nov 17 '05 #4

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

Similar topics

2
2424
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
5476
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.
11
3535
by: JohnR | last post by:
I'm trying to find a way to create a variable of a given type at runtime where I won't know the type until it actually executes. For example, dim x as object = "hi" x is declared as an object but x.gettype returns 'string', so it knows it contains a string. If I want to create a variable "y" as the same type that variable x contains...
7
11922
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...
10
13460
by: Rich | last post by:
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);
2
2014
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
3020
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...
15
7075
by: Anthony Paul | last post by:
Let's say that I would like a generic type that supports Min/Max properties and can be double or integer or even datetime if need be, something flexible. So I go about creating the following generic interface : *note : in reality I implement the IComparable and IEquatable generic interfaces and associated overriden methods, but I've cut...
4
2686
by: Bill Fuller | last post by:
I am trying to determine the type for ActiveControls using 3rd party controls (Infragistics in this case) during runtime and getting a rather odd return type at runtime for the UltraWinEditor. Code shippet is as follows: if ( ActiveControl.GetType() == typeof(UltraTextEditor)) { UltraTextEditor tb = (UltraTextEditor) this.ActiveControl;...
0
7464
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...
0
7656
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. ...
1
7413
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...
0
7751
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 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...
0
5968
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...
0
4943
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
3440
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1874
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
1012
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.