Reputation: 5279
Is it possible to create a method which returns a type and use it?
for example, assume I have a Person type and Object parameter. As you probably know, If we want to cast our Object parameter, we can write:
object param;
((Person)param).executePersonMethod();
My question is how can I write a method which return Person type and use it instead the concrete Person cast - I want write something like this:
public Type GetPersonType()
{
//return here type of person
}
and then use
((GetPersonType())param).executePersonMethod();
Is it possible? If yes, how?
Upvotes: 1
Views: 329
Reputation: 8502
You cannot execute methods on a Type
, you can only execute methods on an instance of a particular Type
. If I am understanding correctly, you should be able to use the answer @LavG gives to:
return not the type but the object itself from the GetPersonType method
Type
using fully
qualified namespace and other techniques:Type.GetType("namespace.a.b.ClassName") returns null
generating a class dynamically from types that are fetched at runtime
Upvotes: 0
Reputation: 10476
Although you can use Generic as a better option, however it is possible using Type Convertor in combination with reflection:
Type type = GetPersonType();
var converted = Convert.ChangeType(param, type);
converted
.GetType()
.GetMethod(/*your desired method name in accordance with appropriate bindings */)
.Invoke(converted, /* your parameters go here */);
Upvotes: 0
Reputation: 153
Yes you can. There is a new type called dynamic which will avoid static type check during compilation.
public dynamic GetPersonOrObjectWhichHasExecutePersonMethod()
{
//return not the type but the object itself
return new Person();
}
public class Person
{
public void executePersonMethod()
{
// do something
}
}
// this is how you invoke it
public void ExecuteMethod()
{
dynamic obj = GetPersonOrObjectWhichHasExecutePersonMethod();
obj.executePersonMethod();
}
Upvotes: 2
Reputation: 125
You can also use dynamic
for this.
Note that using dynamic
will skip any compile time checking whether that method exists and will throw an exception at runtime if it doesn't.
Due to this risk, I would only do this if I have no other choice, but it's good to know that the option exists:
dynamic d = param;
d.executeWhateverMethodHereWithoutCompileTimeChecking();
Upvotes: 2
Reputation: 721
Use
TypeOf()
Example :
if (data.GetType() == typeof(Personne))
return (Personne)data;
else
return new Personne();
After, check your object is not null to know if it's ok
Upvotes: 0
Reputation: 1090
Maybe you can use something like that:
Convert.ChangeType(param, typeof(Person));
It would returns param as a Person.
Upvotes: 1
Reputation: 2378
You can use interface.
((IPerson)param).executePersonMethod();
each type of person must be an IPerson and in IPerson you declare executePersonMethod()
Upvotes: 4