Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Is it possible to pass a type into a method and have the method return an object of that type?

Tags:

c#

This seems like it would be possible.

protected SameObjectTypeAsInputParameterObjectType GetAValue(someObject,TypeOrReturnObjectYouWant){

//check to see if someObject is null, if not, cast it and send the cast back

}
like image 939
jim Avatar asked Jan 15 '10 13:01

jim


2 Answers

In your given example you are probably better served just doing the following:

MyClass val = myObject as MyClass;

However to answer your question - yes, the answer is to use generics:

protected T GetAValue<T>(object someObject)
{
    if (someObject is T)
    {
        return (T)someObject;
    }
    else
    {
        // We cannot return null as T may not be nullable
        // see http://stackoverflow.com/questions/302096/how-can-i-return-null-from-a-generic-method-in-c
        return default(T); 
    }
}

In this method T is a type parameter. You can use T in your code in exactly the same way that you would any other type (for example a string), however note that in this case we haven't placed any restriction on what T is, and so objects of type T only have the properties and methods of the base object (GetType(), ToString() etc...)

We must obviously declare what T is before we can use it - for example:

MyClass val = GetAValue<MyClass>(myObject);
string strVal = GetAValue<string>(someObject);

For more information take a look at the MSDN documentation on Generics

like image 129
Justin Avatar answered Oct 22 '22 11:10

Justin


This seems like it would be done better inline.

What you can do is something like:

var requestedObject = someObject as TheTypeYouWant;

When you declare something like so, you will not get a null reference exception. Then you can just do a simple

if(requestedObject != null){
    ...
}
like image 20
MunkiPhD Avatar answered Oct 22 '22 10:10

MunkiPhD