This project is read-only.

Behaviour of CanBeReferencedByName

Topics: APIs
Sep 20, 2014 at 8:45 PM

i'm working on a Diagnostic that may suggest to replace var by it's concrete type.
While working on it, i have encountered a case that does not work as expected.
In the following sample, it wouldn't be possible to replace var against it's conrete type since var is
NamedType System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 Length, System.String Content>>
string[] strings = { "Hello", "World" };
var anonymousSequence = strings.Select(x => new { Length = x.Length, Content = x });
To guard against these cases i used
public static TypeSyntax ReplaceIdentifier(TypeSyntax identifier, SemanticModel semanticModel)
    TypeInfo typeInfo = semanticModel.GetTypeInfo(identifier);
    if (typeInfo.ConvertedType.CanBeReferencedByName)
But suprisingly CanBeReferencedByName returned true.

Digging through the TypeArguments reveals the anonymous type and also shows CanBeReferencedByName = false, but is it correct that CanBeReferencedByName is true even if the type can't be really referenced because it's TypeArguments aren't referenceable.

I would agree that typeInfo.ConvertedType.OriginalDefinition (IEnumerable<out T>) returns true but for this instantiation it can't be really referenced by name
Nov 19, 2014 at 10:07 PM
push still wondering :-)