unknow return type

  • Thread starter Thread starter Jeroen Ceuppens
  • Start date Start date
J

Jeroen Ceuppens

How can you set that a function returns a type, but you don't know it from
before?

voidunknow Function() ?
unknow Function()?

Thx
 
Thx,

Now I have got this problem, I want to search the type
when i found it, i need to do the Run() method of that object

But it isn't possible: C:\Documents and Settings\Eindwerk\Mijn
documenten\BARCO\Eindwerk\Project
Files\thuis\13december\Aviewerversie02\FileLoad.cs(401): 'object' does not
contain a definition for 'Run'


So I need a solution, because I know that that object has the type which has
a run........ But C# doens't like it.......

Help me
Thx
JC
 
You need to get involved in some design work. If you are sure (because of
your design) that whatever "unknown" object is returned has a "Run" method,
then you should cast to the appropriate type and then call the Run method. I
would use an interface to do this. You probably need to read up on this
stuff a bit. Check www.msdn.com and www.gotdotnet.com, www.codeproject.com,
etc.
 
Jeroen Ceuppens said:
Thx,

Now I have got this problem, I want to search the type
when i found it, i need to do the Run() method of that object

But it isn't possible: C:\Documents and Settings\Eindwerk\Mijn
documenten\BARCO\Eindwerk\Project
Files\thuis\13december\Aviewerversie02\FileLoad.cs(401): 'object' does not
contain a definition for 'Run'


So I need a solution, because I know that that object has the type which has
a run........ But C# doens't like it.......

Create an interface for all your objects that will have a run method, then
check if the returned object implements that interface, and if so, cast it
and execute it:

// Class
public myRunableClass : IRun
{
// class stuff her
}


// Interface
public interface IRun
{
public void Run();
}


// Code

// code here that returns "h" cast as an object

if (h is IRun) // If h implements IRun
{
// Cast to IRun (which will have just one method and no properties, as
defined in the interface above)
// and call Run() on cast object
((IRun)h).Run();
}

HTH
 
One of two solutions:

1) use Interfaces. Create an interface that contains the Run method - let's
call it IRunnable for an example. Then all your objects that use a Run
method would Implement the IRunnable interface. Now, your function can
return a variable of IRunnable type (and many object types potentially can
be returned as long as they implement this interface). You will now be able
to call the Run method from the function return.

2) use Reflection (System.Reflection namespace). Use the GetType method on
the object returned, and then use one of the InvokeMember overloads to call
the Run function.

From a purely elegance-of-structure point of view, and from a performance
point of view, (1) is the preferred choice.

-Rob Teixeira [MVP]
 
Back
Top