jim
jim

Reputation: 27386

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

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

}

Upvotes: 9

Views: 17614

Answers (7)

Justin
Justin

Reputation: 86729

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

Upvotes: 12

Chris Marisic
Chris Marisic

Reputation: 33098

I think you might actually be looking for a Convert.ChangeType mechanism.

private static object ChangeTypeTo<T>(this object value)
{
    if (value == null)
        return null;

    Type underlyingType = typeof (T);
    if (underlyingType == null)
        throw new ArgumentNullException("value");

    if (underlyingType.IsGenericType && 
           underlyingType.GetGenericTypeDefinition().Equals(typeof (Nullable<>)))
    {
        var converter = new NullableConverter(underlyingType);
        underlyingType = converter.UnderlyingType;
    }

    // Guid convert
    if (underlyingType == typeof (Guid))
    {
        return new Guid(value.ToString());
    }

    // Check for straight conversion or value.ToString conversion
    var objType = value.GetType();

    // If this is false, lets hope value.ToString can convert otherwise exception
    bool objTypeAssignable2typeT = underlyingType.IsAssignableFrom(objType);

    // Do conversion
    return objTypeAssignable2typeT ? Convert.ChangeType(value, underlyingType)
            : Convert.ChangeType(value.ToString(), underlyingType);
}

Upvotes: 1

user47322
user47322

Reputation:

Use generics:

T foobar<T>() where T : new()
{
    return new T();
}
void somefunc()
{
    Guid g = foobar<Guid>();
}

Upvotes: 4

mfeingold
mfeingold

Reputation: 7154

Such conversion can be done using as

requestedObject as RequestedType

Wrapping this expression in a method does not really buy your anything

Upvotes: 1

GvS
GvS

Reputation: 52518

If you know the type at compile time (when writing the code) you can use generics.

If you only know the type at runtime (via Type), you can use the Activator class.

Upvotes: 1

saret
saret

Reputation: 2227

You can define the method like this:

protected TReturnType GetAValue<TReturnType>(Object someObject) where TReturnType : class
{
 if(someObject is TReturnType) return (TReturnType) someObject;
 return null;
}

Alternatively if you can't guarantee that TReturnType is a reference type you could leave off the generic constraint (TReturnType : class) and return default(TReturnType) instead of null - this would return the default type of TReturnType which would be 0 for an int...

Upvotes: 1

MunkiPhD
MunkiPhD

Reputation: 3644

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){
    ...
}

Upvotes: 5

Related Questions