Re: Runtime type cast in C#
From: mra (mra_at_discussions.microsoft.com)
Date: 03/23/05
- Next message: Stefan Simek: "Re: How to do this ?"
- Previous message: perspolis: "Column Header"
- In reply to: Nicholas Paldino [.NET/C# MVP]: "Re: Runtime type cast in C#"
- Next in thread: fred christianson: "Re: Runtime type cast in C#"
- Reply: fred christianson: "Re: Runtime type cast in C#"
- Messages sorted by: [ date ] [ thread ]
Date: Wed, 23 Mar 2005 05:51:02 -0800
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]
> - mvp@spam.guard.caspershouse.com
>
> "mra" <mra@discussions.microsoft.com> wrote in message
> news:D50776AD-FDF9-42F0-B574-F3B59BE162A7@microsoft.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?
>
>
>
- Next message: Stefan Simek: "Re: How to do this ?"
- Previous message: perspolis: "Column Header"
- In reply to: Nicholas Paldino [.NET/C# MVP]: "Re: Runtime type cast in C#"
- Next in thread: fred christianson: "Re: Runtime type cast in C#"
- Reply: fred christianson: "Re: Runtime type cast in C#"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|