G
groups
This is my first foray into writing a generic method and maybe I've
bitten off more than I can chew.
My intent is to have a generic method that accepts a value name and
that value will be returned from the source. My first attempt was as
follows; (please ignore that error handling is not present in this
example)
public T GetValue<T> (string objName) {
T results;
switch (objName) {
case "Now":
results = DateTime.Now;
break;
// other cases omitted for brevity
}
return results;
}
This would then be called with something like:
DateTime dt = GetValue<DateTime>("Now");
Unfortunately, when I try to compile this I get the error " Cannot
implicitly convert type 'System.DateTime' to 'T' " at the line
assigning DateTime.Now to results.
I tried changing the offending line to
results = (T)DateTime.Now;
But that just changed the error to " Cannot convert type
'System.DateTime' to 'T' " which isn't a whole lot better.
I've also tried putting a struct constraint on the method definition
(where T : struct) but that had no effect.
I'd hate to have to revert to a non-generic signature of public object
GetValue(string objName) but after searching the web and groups for an
hour I couldn't find anything that answered my question.
Is there something I'm missing here? Any help is appreciated.
Thanks!
-GM
bitten off more than I can chew.
My intent is to have a generic method that accepts a value name and
that value will be returned from the source. My first attempt was as
follows; (please ignore that error handling is not present in this
example)
public T GetValue<T> (string objName) {
T results;
switch (objName) {
case "Now":
results = DateTime.Now;
break;
// other cases omitted for brevity
}
return results;
}
This would then be called with something like:
DateTime dt = GetValue<DateTime>("Now");
Unfortunately, when I try to compile this I get the error " Cannot
implicitly convert type 'System.DateTime' to 'T' " at the line
assigning DateTime.Now to results.
I tried changing the offending line to
results = (T)DateTime.Now;
But that just changed the error to " Cannot convert type
'System.DateTime' to 'T' " which isn't a whole lot better.
I've also tried putting a struct constraint on the method definition
(where T : struct) but that had no effect.
I'd hate to have to revert to a non-generic signature of public object
GetValue(string objName) but after searching the web and groups for an
hour I couldn't find anything that answered my question.
Is there something I'm missing here? Any help is appreciated.
Thanks!
-GM