472,334 Members | 1,507 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,334 software developers and data experts.

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.CreateInstance(strAssemblyName, "MyClass");
//Now, I want to do something like ((MyClass)obj).Method
//Can I do this?
Nov 16 '05 #1
3 21071
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.com

"mra" <mr*@discussions.microsoft.com> wrote in message
news:D5**********************************@microsof t.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.CreateInstance(strAssemblyName, "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.com

"mra" <mr*@discussions.microsoft.com> wrote in message
news:D5**********************************@microsof t.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.CreateInstance(strAssemblyName, "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(MyFunction(...))
string s = Convert.ToString(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(MyFunction(...,"System.Int32"));

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

Or you can add a static method Cast() to MultiType that
int i = MultiType.Cast("System.Int32",
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(object o) { this.o = o;}

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

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

/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
MultiType MyFunction(object oin,string typename)
{
object o = null;
if (typename.Equals("System.Int32"))
{
o = (int)oin;
}
else if (typename.Equals("System.String"))
{
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("text","System.String");
Console.WriteLine("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.com

"mra" <mr*@discussions.microsoft.com> wrote in message
news:D5**********************************@micros oft.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.CreateInstance(strAssemblyName, "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
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...
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...
11
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, ...
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...
10
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...
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...
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...
15
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...
4
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...
0
better678
by: better678 | last post by:
Question: Discuss your understanding of the Java platform. Is the statement "Java is interpreted" correct? Answer: Java is an object-oriented...
0
by: teenabhardwaj | last post by:
How would one discover a valid source for learning news, comfort, and help for engineering designs? Covering through piles of books takes a lot of...
0
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
by: CD Tom | last post by:
This happens in runtime 2013 and 2016. When a report is run and then closed a toolbar shows up and the only way to get it to go away is to right...
0
by: CD Tom | last post by:
This only shows up in access runtime. When a user select a report from my report menu when they close the report they get a menu I've called Add-ins...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific...

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.