473,890 Members | 2,014 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Generic type inferrence and anonymous methods

I am running into a situation where the compiler complains that it
cannot infer the type parameters of a generic method when one of the
function arguments is an anonymous method.

Here is a complete code example:

//-----------------------------
using System;
using System.Collecti ons.Generic;

interface ForwardIterator <T> {}
class IterImpl<T> : ForwardIterator <T> {}

static class Algorithm
{
// method that takes a delegate as its last argument
public static void ReplaceIf<T>(Fo rwardIterator<T > begin,
ForwardIterator <T> end,
Predicate<T> func)
{}

// another method that takes a delegate
public static I RemoveIf<I,T>(I begin, I end, Predicate<T> func)
where I: class, ForwardIterator <T>
{
return null;
}
}

class Program
{
static void Main(string[] args)
{
IterImpl<int> begin = new IterImpl<int>() ;
IterImpl<int> end = new IterImpl<int>() ;

// This compiles fine
Algorithm.Repla ceIf(begin, end, delegate(int x){return true;});

// This also compiles
Predicate<int> pred = delegate(int x){return true;};
Algorithm.Remov eIf(begin, end, pred);

// This errors out
Algorithm.Remov eIf(begin, end, delegate(int x){return true;});
}
}
//-----------------------------

The error is
main.cs(38,9): error CS0411: The type arguments for method
'Algorithm.Remo veIf<I,T>(I, I, System.Predicat e<T>)' cannot be
inferred from the usage. Try specifying the type arguments explicitly.

I can get it to compile by passing template arguments, but that is
hideous. Why can't the compiler infer the second usage when it can infer
the first? Am I missing something simple?

H^2
May 16 '06 #1
4 4952
"Harold Howe" <hh***********@ mchsi.com> wrote in message
news:uf******** ******@TK2MSFTN GP02.phx.gbl...
I am running into a situation where the compiler complains that it cannot
infer the type parameters of a generic method when one of the function
arguments is an anonymous method.


look like a compiler bug to me seeing as the example that asigns the anon
delegate works. I can;t see any ambiguity there.

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk
May 16 '06 #2
Harold Howe <hh***********@ mchsi.com> wrote:
I am running into a situation where the compiler complains that it
cannot infer the type parameters of a generic method when one of the
function arguments is an anonymous method.


Type inference for C# is not nearly as comprehensive as C++. You should
read section 25.6.4 of the C# standard ECMA-334 (3rd ed) before deciding
if it's a bug.

Part of the algorithm for type inference, described in 25.6.4:

---8<---
Nothing is inferred from the argument (but type inference succeeds) if
any of the following are true:
o P does not involve any method type parameters.
o The argument has the null type (§11.2.7).
o The argument is an anonymous method.
o The argument is a method group.
--->8---

In your case, the argument is an anonymous method, so nothing is
inferred from the argument. Since there aren't any more arguments to
infer the type parameter from, and one or more type parameters didn't
have a type argument inferred for it, inference overall fails. So as far
as I can make out, the behaviour you're seeing matches the standard.

Not actually exactly related to your problem, but you may find it
useful: beware the fact that anonymous delegates and method groups need
to go through an implicit conversion to a delegate type before they can
be considered for type inference. This implicit conversion requires that
the target delegate type be known before the anonymous delegate or
method group can be converted. For example:

---8<---
using System;

class App
{
static void F<T>(Action<T> a)
{
}

static void TakesT<T>(T x)
{
}

static void Main()
{
F<int>(TakesT) ; // Succeeds - can infer delegate type
// and thus T for argument to TakesT<>.

F(TakesT<int>); // Fails - can't infer delegate type for
// conversion so can't infer T for F<>.
}
}
--->8---

HTH,

-- Barry
May 17 '06 #3
Thanks for the suggestions.

I have ran into a similar inferrence problem without involving
delegates. This is a simpler case to consider, and would have made a
better post than my original. I may repost a separate question. Here is
the code:

//---------------------------------
using System;
using System.Collecti ons.Generic;

interface ForwardIterator <T> {}
class IterImpl<T> : ForwardIterator <T> {}

static class Algorithm
{
public static I MinElement<I,T> (I begin, I end)
where I: ForwardIterator <T>
where T: IComparable<T>
{
// real code snipped
return default(I);
}
}

class Program
{
static void Main(string[] args)
{
IterImpl<int> begin = new IterImpl<int>() ;
IterImpl<int> end = new IterImpl<int>() ;

IterImpl<int> min = Algorithm.MinEl ement(begin, end);
}
}
//-------------------------------------

I get the same compiler error:

main.cs(31,25): error CS0411: The type arguments for method
'Algorithm.MinE lement<I,T>(I, I)' cannot be inferred from the usage.
Try specifying the type arguments explicitly.

Once again, passing type arguments is ugly, and I would like to avoid
it. I can work around this by not parameterizing on the iterator type.
ie if I do this:

public static ForwardIterator <T> MinElement<T>(F orwardIterator< T> begin,
ForwardIterator <T> end)
where T: IComparable<T>
....

However, this results in a small loss of type information. If I pass in
a strongly typed IterImpl<int>, I get back a weaker
ForwardIterator <int>. The original form returns the stronger type, but I
can't get the inference to work.

Am I out of luck on this? I will probably live with the loss of type
information, rather than force callers to pass type arguments.

H^2
May 17 '06 #4
Harold Howe <hh***********@ mchsi.com> wrote:
public static I MinElement<I,T> (I begin, I end)
where I: ForwardIterator <T>
where T: IComparable<T>
This is trying to infer the type argument from the type constraints -
can't be done (back to section 25.6.4 of ECMA-334 3rd ed):

---8<---
Method type parameter constraints, if any, are ignored for the purpose
of type inference.
--->8---
Am I out of luck on this? I will probably live with the loss of type
information, rather than force callers to pass type arguments.


If you are willing to limit the number of classes, you can keep some
type inference and keep a stronger return type by implementing the
method multiple times. From your example:

---8<---
using System;
using System.Collecti ons.Generic;

interface ForwardIterator <T> {}
class IterImpl<T> : ForwardIterator <T> {}

static class Algorithm
{
public static ForwardIterator <T> MinElement<T>(
ForwardIterator <T> begin, ForwardIterator <T> end)
{
return null;
}
public static IterImpl<T> MinElement<T>(I terImpl<T> begin,
IterImpl<T> end)
{
return null;
}
}

class App
{
static void Main(string[] args)
{
IterImpl<int> begin = new IterImpl<int>() ;
IterImpl<int> end = new IterImpl<int>() ;

IterImpl<int> min = Algorithm.MinEl ement(begin, end);
}
}
--->8---

-- Barry

--
http://barrkel.blogspot.com/
May 17 '06 #5

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

Similar topics

49
2920
by: Steven Bethard | last post by:
I promised I'd put together a PEP for a 'generic object' data type for Python 2.5 that allows one to replace __getitem__ style access with dotted-attribute style access (without declaring another class). Any comments would be appreciated! Thanks! Steve ----------------------------------------------------------------------
18
3060
by: Steven Bethard | last post by:
In the "empty classes as c structs?" thread, we've been talking in some detail about my proposed "generic objects" PEP. Based on a number of suggestions, I'm thinking more and more that instead of a single collections type, I should be proposing a new "namespaces" module instead. Some of my reasons: (1) Namespace is feeling less and less like a collection to me. Even though it's still intended as a data-only structure, the use cases...
8
1837
by: JAL | last post by:
Here is my first attempt at a deterministic collection using Generics, apologies for C#. I will try to convert to C++/cli. using System; using System.Collections.Generic; using System.Text; namespace DeterminedGenericCollection { // I got tired of copy and pasting IDisposable
7
3795
by: Bill Woodruff | last post by:
I've found it's no problem to insert instances of named delegates as values into a generic dictionary of the form : private Dictionary<KeyType, DelegatemyDictionary = new Dictionary<KeyType, Delegate); using the standard .Add method of the Dictionary, passing in the name of the delegate instance for the value. private void myMethodBody()
9
5860
by: Steve Richter | last post by:
in a generic class, can I code the class so that I can call a static method of the generic class T? In the ConvertFrom method of the generic TypeConvert class I want to write, I have a call to the static Parse method of the conversion class. if (InValue is string) return T.Parse((string)InValue); else return base.ConvertFrom(context, culture, InValue);
7
1647
by: Ido Samuelson | last post by:
Hello, What do you think about the following features: public class GenericDecorator<T: T { } can leverage to a few things:
26
3637
by: raylopez99 | last post by:
Here is a good example that shows generic delegate types. Read this through and you'll have an excellent understanding of how to use these types. You might say that the combination of the generic delegate type expression in just the right place and a well-named method means we can almost read the code out loud and understand it without even thinking. Note that since 'boxing' and 'unboxing' is involved (I think), you don't get what you...
8
4381
by: Advait Mohan Raut | last post by:
Hello, I am using VC# 2005 ; C# 2.0 I am working on the performance measurement tool. For that I need my code to call user defined method along with its parameters. For that should I use a generic delegate with variable length argument or something else ? if it is then how to use it ? AA advait
0
2380
by: =?Utf-8?B?TW9ydGVuIFdlbm5ldmlrIFtDIyBNVlBd?= | last post by:
"Anders Borum" wrote: Hi Anders, I'm afraid the GetMethod() does not currently support filtering on generic parameters so you will have to loop through the existing methods using GetMethods() MethodInfo methods = t.GetMethods();
0
9978
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9822
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10923
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10462
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9633
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8016
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6045
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4676
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4271
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.