473,842 Members | 1,372 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 21228
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
2448
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
5484
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
3573
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
11967
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
13539
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
2030
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
3053
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
7111
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
2705
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
9876
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
9717
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
10952
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...
1
10683
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,...
0
10320
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9459
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
5699
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
5887
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3148
bsmnconsultancy
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...

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.