Reputation: 1043
can you please help me to find out the namespace from VariableDeclarationSyntax, StatementSyntax and IdentifierNameSyntax ?
I am just using the below code, but it always replies the "Microsoft.CodeAnalysis.CSharp.Syntax" namespace only.
string namespaceName = identifierSyntax.GetType().BaseType.Namespace;
Please consider the below example:
Package X;
Class A {};
Class B
{
A a;
}
Here both classes are available in the package X; So i don't want to refer the namespace of class A in B, if i'm using the A's instance in B class. But i want the namespace name of Class A using Roslyn. is there any way to get it?
Upvotes: 1
Views: 1300
Reputation: 3
you can use semanticModel.GetSymbolInfo(identifierNameSyntax) which returns a SymbolInfo. SymbolInfo.Symbol is an ISymbol, so you can use ISymbol.ContainingNamespace to get the namespace an identifier belongs to.
var namespace = $"{semanticModel.GetSymbolInfo(identifierNameSyntax).Symbol.ContainingNamespace}";
Upvotes: 0
Reputation: 2329
From an IdentifierNameSyntax, if you want to determine what namespace that identifier is declared within then you may do the following (and so you'll be able to do the same from other node types) -
var ns = context.Node.Ancestors().OfType<NamespaceDeclarationSyntax>().FirstOrDefault();
Note that this will sometimes be null. For example, if you are analysing the following content
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ConsoleApplication1
{
class TypeName
{
}
}
Then "System", "Collections", "Generic", etc.. will result in instances of IdentifierNameSyntax but they are not within a namespace.
Alternaitvely, if you have a VariableDeclarationSyntax and you want to know what namespace contains the type that the variable is of, then you can do this:
var variableDeclaration = (VariableDeclarationSyntax)context.Node;
var type = context.SemanticModel.GetTypeInfo(variableDeclaration.Type).Type;
if ((type != null) && !(type is IErrorTypeSymbol)) // This will happen if the type lookup fails
{
var ns = type.ContainingNamespace;
}
If you were analysing the line
var x = new SqlCommand();
then "type" would be "System.Data.SqlClient.SqlCommand" and so "ns" would be the namespace "System.Data.SqlClient";
Upvotes: 1