-
July 20th, 2010, 06:24 PM
#1
CS0119 when compiling generic function, why?
When I compile this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace App1
{
class Program
{
static T foo<T>(string s)
{
try
{
return T.Parse(s);
}
catch (FormatException ex)
{
return default(T);
}
}
static void Main(string[] args)
{
int x = foo<int>("0");
int? y = foo<int?>("");
}
}
}
I get this:
error CS0119: 'T' is a 'type parameter', which is not valid in the given context
(on the line with the T.Parse() )
Why?
-
July 20th, 2010, 06:29 PM
#2
Re: CS0119 when compiling generic function, why?
You have no constraints on your generic parameter, i.e., it could be anything. How do you know that what is passed in has a "Parse" method? For example, I could use your code like this:
Code:
string s = foo<string>("1");
Uh oh, there is no Parse method for the string class. How is the compiler supposed to deal with that? It can't, hence the error.
Also, what you are trying to do is not even possible for int, float, double, etc. They all inherit from System.ValueType, i.e., they share no common interface. Think about that for a bit and ask yourself how you would expect your code to work.
You can do what you want, but it will involve classes/interfaces like IConvertible, it is not as simple as it seems at first.
-
July 20th, 2010, 10:23 PM
#3
Re: CS0119 when compiling generic function, why?
Originally Posted by BigEd781
You have no constraints on your generic parameter, i.e., it could be anything. How do you know that what is passed in has a "Parse" method? For example, I could use your code like this:
Code:
string s = foo<string>("1");
Uh oh, there is no Parse method for the string class. How is the compiler supposed to deal with that? It can't, hence the error.
Also, what you are trying to do is not even possible for int, float, double, etc. They all inherit from System.ValueType, i.e., they share no common interface. Think about that for a bit and ask yourself how you would expect your code to work.
You can do what you want, but it will involve classes/interfaces like IConvertible, it is not as simple as it seems at first.
<whine>
But the types for which I instantiate it do in fact have a Parse() method... can't the compiler wait and see what I am using it for? A c++ compiler would.
</whine>
I have a workaround.
Thank you ...
-
July 21st, 2010, 02:48 AM
#4
Re: CS0119 when compiling generic function, why?
"A C++ compiler would"
Yeah, because it's much more desirable for coding errors that can be caught at compile time to crash your program at runtime. Templates in C++ or compile time copy and paste mechanisms. C# gives you type safety. Perhaps you should spend some more time learning how the language works.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|