2
/// <summary>  
///  This can have any description of the class  
/// </summary>  
public class MyClass {} 

In the above code sample, is there any way I could get the summary Value.

My objective in such this, is to record objects' actions in a log and in such context, I know what class did what and when.

I can get the Name of the class from this.GetType().Name but in some situation I will need to have any description associate with it.

If there is any alternative way of having a description of the class other than the XML documentation, then I would like to hear about it.

Thank You,

hiFI
  • 1,887
  • 3
  • 28
  • 57
  • 1
    You could just parse the xml file yourself. I really doubt that the comments themselves are compiled and stored for you to access through code. – Erndob Aug 03 '18 at 06:55
  • There are some third-party solutions out there, that compile help files from those comments. But as @Erndob stated, you could just parse them yourself – 4ndy Aug 03 '18 at 06:56

2 Answers2

2

You can't get the XML documentation from reflection, since it is not generated into the assembly. It is generated to a separate XML file, which you can open and read from your application. (Distribution might be an issue, since the XML file is generated after the assembly was compiled, so you can't include it as resource in the assembly itself.)

An alternative solution might be to create a special attribute, which you can fill and read. Something like:

[Summary("This can have any description of the class.")]
public class MyClass {}

The problem with that solution is that it doesn't generate the documentation XML, so you have no IntelliSense, etc.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
2

If you don't want to use XML comments, you can store the description as metadata using the [Description] attribute, i.e:

[Description("This can have any description of the class")]
public class MyClass {} 

You can then access the value of this attribute at run-time:

public static string GetDescription(Type t) {
    return TypeDescriptor.GetAttributes(t)
        .OfType<DescriptionAttribute>()
        .Select(x => x.Description)
        .FirstOrDefault();
}

e.g. GetDescription(typeof(MyClass))

Bradley Smith
  • 13,353
  • 4
  • 44
  • 57
  • Then the XML documentation doesn't work any more. So no IntelliSense, etc. – Patrick Hofman Aug 03 '18 at 07:03
  • If you value that functionality more then (as others have said) you would be better off parsing the XML documentation at run-time. I wrote an article on this subject a few years ago: https://www.brad-smith.info/blog/archives/220 – Bradley Smith Aug 03 '18 at 07:08