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
}
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
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){
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With