Alain
Alain

Reputation: 27250

Using a type alias in a linq statement is generating an error

For some reason this statement is working fine:

vms.Where(vm => vm.MessageType == ValidationMessage.EnumValidationMessageType.Warning)

But if at the top of the class, I define an alias (to save space):

using MsgType = ValidationMessage.EnumValidationMessageType;

Then the resulting line of code:

vms.Where(vm => vm.MessageType == MsgType.Warning)

Gives me an error:

enter image description here "Delegate 'System.Func<ValidationMessage, int, bool>' does not take 1 arguments". What's odd about that is that isn't the Delegate I'm using. I'm using the 'System.Func<ValidationMessage, bool>' overload of .Where<>() - same as when I wasn't using the alias.

Note that everywhere else the alias is being used works fine, it's only inside these linq delegates that it breaks. Why is this happening?

Upvotes: 6

Views: 346

Answers (1)

Alain
Alain

Reputation: 27250

Upon trying to run my program, all those errors cleared away and a single error appeared complaining about my type alias declaration.

The problem was that the ValidationMessage.EnumValidationMessageType type existed within a namespace, which had been declared further up:

using WPF.Utilities.ObjectModel;
using MsgType = ValidationMessage.EnumValidationMessageType;

Of course, C# can't figure out where the type comes from based on prior namespace inclusions, I had to spell it out fully:

using WPF.Utilities.ObjectModel;
using MsgType = WPF.Utilities.ObjectModel.ValidationMessage.EnumValidationMessageType;

Once I did that, the other problem went away.

I guess I was just so caught up and confounded by the weird errors coming out of the linq statement, combined by the fact that VS didn't show any errors where I was using the alias in the ternary operators above, that I didn't see the obvious error there.

Thanks for the hint nemesv - I should know better than to trust the design-time compiler.

Upvotes: 2

Related Questions