Re: return object of an unknown type
- From: "DeveloperX" <nntpDev@xxxxxxxxxxxxx>
- Date: 25 Jan 2007 03:44:49 -0800
Yes you can, but you should really have a very good reason for not
knowing in advance what the object type is.
Critically you need to understand a little about inheritence.
Everything in dotnet is derived from object, so a variable of type
object can hold anything. There are several ways of casting from one
type to another.
Here's some code.
object of;
object ot;
Form f = new Form();
TextBox t = new TextBox();
of=f;
ot=t;
f=null;
//cast example
f=(Form)of;
//this will throw an exception so commented out
//f=(form)ot;
//safe way of doing it.
f = of as Form;
if(null != f)
{
Console.WriteLine("of is a form");
}
//f should be null after this as ot points at a textbox
f = ot as Form;
if(null == f)
{
Console.WriteLine("ot is not a form");
}
On 25 Jan, 10:57, "Alexander Widera"
<a...@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx> wrote:
hi,
is it possible to return an object of an unknown (but not really unknown)
type with an method?
i have the following situation:
- a variable (A) of the type "object" which contains the object
- a variable (B) of the type "Type" which contains the type of the object in
(A) (A should be of the type B)
- a method which should return the object (A) as type (B)
it sounds very simple, if you hard-code it, but it should be a little more
dynamic.
here something in c#-pseudocode:
object myobject = ...
Type typeofobject = ...
public typeofobject GetTheObject()
{
return (typeofobject) myobject;
}Could you help me please?
Thanks in advance,
Alex
.
- Follow-Ups:
- Re: return object of an unknown type
- From: Alexander Widera
- Re: return object of an unknown type
- References:
- return object of an unknown type
- From: Alexander Widera
- return object of an unknown type
- Prev by Date: Re: consuming managed C# DLL from unmanaged VB6
- Next by Date: Re: how do you do freehand drawing on a panel
- Previous by thread: return object of an unknown type
- Next by thread: Re: return object of an unknown type
- Index(es):
Relevant Pages
|
Loading