Reputation: 4051
I am attempting to hide a whole set of legacy methods behind a single extension method using generics. These legacy methods are all called GetValidXXX and have a similar signature (and yes they should really be out not ref). The old GetValidXXX need to be kept for backwards compatibility.
public static T GetAttributeValue<T>(this DbElement element, DbAttribute attribute, T defaultValue)
{
T result = default(T);
if (typeof(T) == typeof(DbAttribute))
{
if (element.GetValidAttribute(attribute, ref result)) return result;
}
else if (typeof(T) == typeof(bool))
{
if (element.GetValidBool(attribute, ref result)) return result;
}
return defaultValue;
}
This will not compile because result does not match the type in the specific GetValidXXX signature (return values is success/fail).
bool GetValidAttribute(DbAttribute attribute, ref DbAttribute result)
bool GetValidBool(DbAttribute attribute, ref bool result)
etc
How can I write this to achieve what I am aiming for i.e. to be able to write code that looks like this:
string description = element.GetAttributeValue(DbAttributeInstance.DESC, "unset");
bool isWritable = !element.GetAttributeValue(DbAttributeInstance.READONLY, true);
Upvotes: 0
Views: 151
Reputation: 9002
Convert.ChangeType()
might be useful in your case.
Possible usage:
public static T ConvertTypeOrGetDefault<T>(this object value, T defaultValue)
{
try
{
return (T)Convert.ChangeType(value, typeof(T));
}
catch (Exception ex)
{
return default(T);
}
}
It depends on how "hacky" you're willing to be. You also could consider re-factoring so that you don't have to hide the legacy methods.
Upvotes: 1
Reputation: 141588
You can't use T
for your ref parameters because the compiler cannot always guarantee it will be of those types. You would have to do something like this:
public static T GetAttributeValue<T>(this DbElement element, DbAttribute attribute, T defaultValue)
{
if (typeof(T) == typeof(DbAttribute))
{
var dbAttribute = default(DbAttribute);
if (element.GetValidAttribute(attribute, ref dbAttribute)) return (T)(object)dbAttribute;
}
else if (typeof(T) == typeof(bool))
{
var boolResult = default(bool);
if (element.GetValidBool(attribute, ref boolResult)) return (T)(object)boolResult;
}
return defaultValue;
}
Upvotes: 3