why "type inference " cann't work

N

Nie longhai

I have a generic method in a class as follow:

T Get<T>(string key)
{
.....
return Convert.ChangeType(v, typeof(T))
}

when I use it in my code:

string ret = MyObject.Get("key");

compile failed , type inference cann't work, why?

thanks for any advice!



--

_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
Nie Longhai, Coder ^_*

Shanghai Xomi Instruments Co.,Ltd.

Phone: 086-021-57513966(807)
Fax: 086-021-57513966
Cell: 13162055440
Email: (e-mail address removed), (e-mail address removed)
Web: www.xomi.cn
Zip: 201411

Shanghai C&U Industrial Park
Feng Cheng Town, Feng Xian District
 
J

Jon Skeet [C# MVP]

Nie longhai said:
I have a generic method in a class as follow:

T Get<T>(string key)
{
....
return Convert.ChangeType(v, typeof(T))
}

when I use it in my code:

string ret = MyObject.Get("key");

compile failed , type inference cann't work, why?

Type inference is only performed based on parameters, not return
values.
 
N

Nie longhai

Hi, Jon

thank you for your help.
but

Why C# cann't infer type base on return type and cann't overload base on
return type ?
 
J

Jon Skeet [C# MVP]

Nie said:
thank you for your help.
but

Why C# cann't infer type base on return type and cann't overload base on
return type ?

It was a choice made by the language designers to make things less
context-sensitive, so you can always tell from a method call which
overload will be taken etc without the compiler having to take into
account where the result will be used.

It can be a pain at times, but I think overall it adds to readability
of code and simplicity of the language specification.

Jon
 
C

cok119

Hi, Jon

thank you very much.

Jon Skeet said:
It was a choice made by the language designers to make things less
context-sensitive, so you can always tell from a method call which
overload will be taken etc without the compiler having to take into
account where the result will be used.

It can be a pain at times, but I think overall it adds to readability
of code and simplicity of the language specification.

Jon
 

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