score:2

Accepted answer

First will throw. Use FirstOrDefault that will return the default<T> and also null-conditional operator (?.):

Label lbl = grid.Children.OfType<Label>().FirstOrDefault(k => k.Name=="label");
string result = lbl?.Name.ToString();
Console.WriteLine(result);

However, Since this is a WPF project, I suggest use a MessageBox or something similar to show the result, instead of Console.WriteLine, like this:

Add this to your using directives first:

using System.Windows; 

And then:

MessageBox.Show(result);

Related Articles