473,395 Members | 1,681 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 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 16591
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.