Adding new items to a variable of type var - Having Constructor and Method declarations in one variable

Viewed 139

I have the following code:

var allclasses = tree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>();
foreach (var memcls in allclasses)
{
    if (memcls != null)
    {
        var methodDeclarations = memcls.DescendantNodes().OfType<MethodDeclarationSyntax>();
        foreach (var memmeth in methodDeclarations)
        {
            var paramDeclaratons = memmeth.ParameterList.Parameters;

Right after the line where methodDeclarations is defined, I also want to add a line like the following pseudo code:

methodDeclarations.AddRange(
    memcls.DescendantNodes().OfType<ConstructorDeclarationSyntax>())

In order to have the ConstructorDeclarationSyntax items that are returned added to the same methodDeclarations variable as well; i.e., having both ConstructorDeclarationSyntax and MethodDeclarationSyntax items in the same variable. How can I do that?

I tried some type casting and using List instead of var for methodDeclarations variable, but then it gives errors on the next lines where I want to access ParameterList, Identifier and other properties on memmeth.

As another trick, I tried using the following code

var methodDeclarations = tree.GetRoot().DescendantNodes()
    .Where(c => c is MethodDeclarationSyntax || c is ConstructorDeclarationSyntax);

But then again it gives error on accessing ParameterList and Identifier properties later in the code.

2 Answers
Related