472,950 Members | 2,353 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,950 software developers and data experts.

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

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

Jul 5 '07 #1
7 16364
On Thu, 05 Jul 2007 14:57:08 -0700, <gr****@lfsh.comwrote:
[...]
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
Jul 5 '07 #2
On Jul 5, 4:10 pm, "Peter Duniho" <NpOeStPe...@nnowslpianmk.com>
wrote:
On Thu, 05 Jul 2007 14:57:08 -0700, <gro...@lfsh.comwrote:
[...]
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
Jul 6 '07 #3
<gr****@lfsh.comwrote:

<snip>
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Jul 6 '07 #4
<snip>
>
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.

--
Jon Skeet - <s...@pobox.com>http://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
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

Jul 6 '07 #5
On Jul 6, 3:15 pm, gro...@lfsh.com wrote:
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

Jul 6 '07 #6
<gr****@lfsh.comschrieb im Newsbeitrag
news:11*********************@n2g2000hse.googlegrou ps.com...
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
Jul 6 '07 #7
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<objectgenTime = 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();
}
}

<gr****@lfsh.comwrote in message
news:11*********************@n2g2000hse.googlegrou ps.com...
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
Jul 6 '07 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Sorisio, Chris | last post by:
Ladies and gentlemen, I've imported some data from a MySQL database into a Python dictionary. I'm attempting to tidy up the date fields, but I'm receiving a 'mx.DateTime.Error: cannot convert...
14
by: Jon Davis | last post by:
I have put my users through so much crap with this bug it is an absolute shame. I have a product that reads/writes RSS 2.0 documents, among other things. The RSS 2.0 spec mandates an en-US style...
17
by: Andreas Huber | last post by:
What follows is a discussion of my experience with .NET generics & the ..NET framework (as implemented in the Visual Studio 2005 Beta 1), which leads to questions as to why certain things are the...
1
by: Anonieko Ramos | last post by:
The logical thing to do is to try it yourself. > > > > See this example: -----------------------------------------------------------
4
by: KC | last post by:
Could some one explain to me the casting rules for sending generic lists, ex. List<Person>, to a function that accepts List<object>? I cannot get the following easy-cheesy app to work. I get the...
23
by: Luc Vaillant | last post by:
I need to initialise a typed parameter depending of its type in a generic class. I have tried to use the C++ template form as follow, but it doesn't work. It seems to be a limitation of generics...
1
by: uttara | last post by:
I have a generic collection which I am using in classes to store a collection of embedded objects. Class Employee: IEntity { Private string mName; Private int mEmployeeID; . Private...
1
by: John | last post by:
I have a drop down that is showing dates, I need to pass the selected date to my proc, so I pass it like this; ...
1
by: Kevin S. Goff | last post by:
Hi, all, Hopefully this will make sense: I have 2 classes that implement the same generic interface. public interface IAgingReport<T> { T GetAgingReport(DateTime dAsOfDate); }
0
by: Mushico | last post by:
How to calculate date of retirement from date of birth
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
3
by: nia12 | last post by:
Hi there, I am very new to Access so apologies if any of this is obvious/not clear. I am creating a data collection tool for health care employees to complete. It consists of a number of...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.