C# Generics: cannot convert 'System.DateTime' to 'T'

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
 
P

Peter Duniho

[...]
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 see two questions:

1) Generally, how to convert from one type to another in a generic
method
2) How to extract a given property from an arbitrary type by name

Regarding #1:

There may be some funny business you can play using "typeof" and the
Convert class, but it seems to me that the basic issue here is that the
compiler needs to know what you are going to convert DateTime.Now to.
Constraining T to be a struct doesn't help that at all.

If you can constrain T to be a type that you know DateTime.Now can be
implicitly cast to (or explicitly, if you want to cast explicitly), then
do that. Otherwise, you may want to look at Convert.ChangeType()...you'll
want to constrain T to be something that implements IConvertible, and the
conversion may still fail, but it may get you what you want.

Regarding #2:

In your example, you appear to be simply retrieving the property by string
name. This is something that is supported by reflection, so if that's
really what you're trying to do, that would be a much better mechanism
that trying to coerce a generic method into doing that based on a switch
statement. The code will be shorter and much more flexible (ie you won't
have to hard-code each and every property you want to support).

Pete
 
G

groups

[...]
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 see two questions:

1) Generally, how to convert from one type to another in a generic
method
2) How to extract a given property from an arbitrary type by name

Regarding #1:

There may be some funny business you can play using "typeof" and the
Convert class, but it seems to me that the basic issue here is that the
compiler needs to know what you are going to convert DateTime.Now to.
Constraining T to be a struct doesn't help that at all.

If you can constrain T to be a type that you know DateTime.Now can be
implicitly cast to (or explicitly, if you want to cast explicitly), then
do that. Otherwise, you may want to look at Convert.ChangeType()...you'll
want to constrain T to be something that implements IConvertible, and the
conversion may still fail, but it may get you what you want.

Regarding #2:

In your example, you appear to be simply retrieving the property by string
name. This is something that is supported by reflection, so if that's
really what you're trying to do, that would be a much better mechanism
that trying to coerce a generic method into doing that based on a switch
statement. The code will be shorter and much more flexible (ie you won't
have to hard-code each and every property you want to support).

Pete

Pete,

Thanks for your response. The main reason for looking at generics is
that the method will return a variety of types so type coercion isn't
quite what I was looking for. The other piece of this which I didn't
mention before because I didn't think it was important, but now see
that it is, is that this will be called through remoting. I didn't
want to force the client to change the remote interface every time a
new property was added to the server object. So my intent was to
access various properties by using a string reference but also having
it strongly typed on the client side. This way I can add new
properties on the server, but the client doesn't have to change their
interface.

Ideally the client should be able to do any of the following and they
should all work: Note that it's a mix of value and reference types.

string stringValue = remoteObject.GetValue<string>("Value1");
int intValue = remoteObject.GetValue<int>("Value2");
DateTime dtValue = remoteObject.GetValue<DateTime>("Value3");
DataSet set = remoteObject.GetValue<DataSet>("Value4");


I thought about reflection in the implementation as that does avoid a
switch statement on the server side, and I may still go that route,
but I still have the problem of how to give the client a strongly
typed object rather than returning the object type that they'll then
have to convert. That just seems messy to me.


Thanks,
-GM
 
J

Jon Skeet [C# MVP]

Ideally the client should be able to do any of the following and they
should all work: Note that it's a mix of value and reference types.

string stringValue = remoteObject.GetValue<string>("Value1");
int intValue = remoteObject.GetValue<int>("Value2");
DateTime dtValue = remoteObject.GetValue<DateTime>("Value3");
DataSet set = remoteObject.GetValue<DataSet>("Value4");

But the problem is what you do with:

string stringValue = remoteObject.GetValue<string>("Value4");

Because the type of object returned is determined at runtime, you need
a runtime check - whereas generics is about compile-time checking.
 
G

groups

But the problem is what you do with:

string stringValue = remoteObject.GetValue<string>("Value4");

Because the type of object returned is determined at runtime, you need
a runtime check - whereas generics is about compile-time checking.

Ah, it makes sense now. So I really have no choice but to do
something like:

public object GetValue(string key) {
// based on key, return a specific object
}

string stringValue = remoteObject.GetValue("Value4") as string;
if (stringValue != null) {
// do something with the string
}

Thanks,
-GM
 
J

Jon Skeet [C# MVP]

Ah, it makes sense now. So I really have no choice but to do
something like:

public object GetValue(string key) {
// based on key, return a specific object

}

string stringValue = remoteObject.GetValue("Value4") as string;
if (stringValue != null) {
// do something with the string

}

Either that, or expose multiple methods: GetStringValue,
GetDateTimeValue etc, which would throw an exception if the value to
be returned isn't of the right type.

Jon
 
C

Christof Nordiek

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;
}

You could do someting like

results = (T)(object)DateTime.Now

This would compile, and it works for your case though it involves extra
boxing and unboxing. (Maybe the compiler optimizes this away.)

The involved conversions would be: boxing conversion (if the expression is
of a valuetype), unboxing conversion (if T is a value type) und reference
conversions. So if the value returned by the expression is not of type T or
of a type that derives from or implements T an InvalidCastException is
thrown.

Christof
 
M

Mike Flynn

Generics are used mainly for collections where they are usefull if you want
lists, arrays etc of varying types (ref and value). The code runs faster
(probably not noticeable) because you do not need to cast between types.
Hope this helps and I have not got the wrong end of the stick.

class Program
{
public class GetTime<T>
{

private T t;

//single parameter constructor, can be many of different types
public GetTime(T _t)
{
t = _t;
}
}

static void Main(string[] args)
{
object t = new object();

GetTime<object> genTime = new GetTime<object>(t);

string s = args[0];

switch (s)
{
case "Now":
t = DateTime.Now; // t of type System.DateTime
break;
case "Then":
t = 12; //t of type System.Int32
break;
}
Console.WriteLine(t);
Console.WriteLine(t.GetType());
Console.ReadKey();
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top