473,857 Members | 2,117 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 21230
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
2450
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 example, I want a linked lists of ints. I want to be able to say:
2
5485
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
3574
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 how would I do that without having to iterate thru every possible
7
11969
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 started well and dandy! Now the problem; some of the properties of the DirectoryEntry objects being...
10
13541
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
2032
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
3056
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...
15
7112
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 everything down to the bare minimum for this example.
4
2706
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; if (tb.Multiline == true)
0
9923
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
9767
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
11082
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9549
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...
0
7104
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();...
0
5774
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
5967
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4592
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
2
4190
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.