I am trying to find a good solution to finding out whether a dependency on another class in C# is in composition or agreggation.
Is there a better way to do it than like this?
private static DependencyType GetDependencyAssociation(this INamedTypeSymbol? symbol)
{
if (symbol.IsReferenceType && !symbol.IsValueType)
{
return DependencyType.Aggregation;
}
if (symbol.IsReferenceType && symbol.IsValueType)
{
return DependencyType.Composition;
}
return DependencyType.Association;
}
From the code snippet, it is not clear how you get the dependency and why you are sure that the dependency is an a kind of association.
First of all, there are many dependencies that do not necesarily imply an association:
Console. WriteLine(object)
does not at all imp'y that the console and the object will be associated!If you are sure that the dependcy is related to an association, for example if type X has a property of type Y, of a property that is a container of type Z, then your code snippet make sense.
I'm not a Roselyn expert, but from the documentation of INamedTypeSymbol
we can see that IsReferenceType
and IsValueType
are mutually exclusive: at most one of the two is true:
It is never the case that
IsReferenceType
andIsValueType
both return true. However, for an unconstrained type parameter,IsReferenceType
andIsValueType
will both return false.
The first if
can therefore be simplified into if (symbol.IsReferenceType)
. The second if
will newer be fired as its condition will always be wrong.
Assuming you capture well candidate associations, for example that for a type A you have a property of type B:
symbol
B is a reference type, there is an association.symbol
B is a value type (e.g. a struct
embedded in a class, according to C# semantics) then there is a composition since the B object is created with the A object and will be destroyed with the A object.But what's with aggregation? You don't need it! because the UML specifications do not define any semantics for it. The specs leave the possibility for a group of modelers to define their own semantics. Moreover even if there were some semantics agreed, how could you objectively verify a very conceptual criteria in your code?