Cannot assign void to an implicitly-typed local variable with var and foreach
Asked Answered
M

3

18

I'm trying to list all buttons name from my form to list with code

var v = new List<Form1>() { this }.ForEach(x => { x.GetType().Name.Contains(typeof(Button).Name); });

and always get error

Cannot assign void to an implicitly-typed local variable

How to bypass that?

Merla answered 2/4, 2014 at 14:16 Comment(1)
You cannot do this. call foreach on v, not on the constructed object, as ForEach returns void and you are then trying to assign void to the variableGeoponic
A
27

Foreach returns void that is why you are getting the error. Your statement on the right hand side of assignment is not returning anything. You can do the same in two statements like:

var v = new List<Form1>() { this };
v.ForEach(x => { x.GetType().Name.Contains(typeof(Button).Name); });

In your current code you are creating a new List<Form1> and then iterating over each item in the list, but you are not returning anything.

As Jon Skeet has pointed out in the comment, it will not have any effect on the list. I guess you are trying to get all the button from your list of forms you can do:

var allButtons = v.SelectMany(r => r.Controls.OfType<Button>()).ToList();
Ambrosane answered 2/4, 2014 at 14:18 Comment(4)
@tonni: No. You could order assignment before a member usage using parentheses, but not initialization.Cranial
@habib your update don't work but i understand what you tying to sayMerla
@tonni, umm what doesn't work, it should return a List<Button> for all the items in your List<Form1>, Are you getting any error /exception ?Ambrosane
@Ambrosane --- didn't include linq, now work perfect :), thnx for helpMerla
C
8

I suspect you're really looking for Where - just calling Contains in a ForEach call isn't going to do anything for you. Likewise I don't think you're really looking for a list of forms if you're interested in buttons. I suspect you may be looking for:

var buttons = this.Controls.OfType<Button>().ToList();

Note that this won't go into nested controls - if you need to do that, you'll need something recursive. (You may well be able to find other questions asking for that... it doesn't help that we don't know whether this is WinForms, WebForms, something else...)

Cysticercus answered 2/4, 2014 at 14:21 Comment(0)
D
0

This is the correct form of code of the above error that I was facing.

public asyncTask<IDataResult<IEnumerable<PatientSpecialInstructionDto>>> Handle(GetPatientSpecialInstructionListQuery request, CancellationToken cancellationToken)
{
var dataList = await _patientSpecialInstructionRepository.GetPatientSpecialInstructionListQuery(request.ProviderId);
                
 return new PagedDataResult<IEnumerable<PatientSpecialInstructionDto>>(dataList, dataList.Count(), request.PageNumber);
            }
Daguerreotype answered 3/4, 2023 at 4:35 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.