ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Advanced Programming
    CSI-415
    Progress0 / 55 topics
    Topics
    1. Visual Programming Basics2. Introduction to Events3. Fundamentals of Event-Driven Programming4. Message Handling5. User Interfaces6. Graphics Device Interface7. Painting and Drawing8. Windows Management9. Input Devices10. Resources11. String and Menu Resource12. Dialogs and Windows Controls13. Common Controls14. Dynamic Link Libraries (DLLs)15. Threads and Synchronization16. Network Programming17. Building Class Libraries at the Command Line18. Class Libraries19. Using References20. Assemblies21. Private Assembly Deployment22. Shared Assembly Deployment23. Configuration Overview24. Configuration Files25. Programmatic Access to Configuration26. Using SDK Tools for Signing and Deployment27. Metadata28. Reflection29. Late Binding30. Directories and Files31. Serialization32. Attributes33. Memory Management and Garbage Collection34. Threading and Synchronization35. Asynchronous Delegates36. Application Domains37. Marshal by Value38. Marshal by Reference39. Authentication and Authorization40. Configuring Security41. Code Access Security42. Code Groups43. Evidence44. Permissions45. Role-Based Security46. Principals and Identities47. Using Data Readers48. Using Data Sets49. Interacting with XML Data50. Tracing Event Logs51. Using the Boolean Switch and Trace Switch Classes52. Print Debugging Information with the Debug Class53. Instrumenting Release Builds with the Trace Class54. Using Listeners55. Implementing Custom Listeners
    CSI-415›Metadata
    Advanced ProgrammingTopic 27 of 55

    Metadata

    7 minread
    1,243words
    Intermediatelevel

    Metadata in .NET

    Metadata in .NET refers to the data about the types, members, and other components in an assembly. It provides important information that allows the .NET runtime and tools to understand the structure and behavior of your code. This includes information such as types, methods, properties, attributes, and other aspects that describe your application's components. Metadata is essential for reflection, debugging, and certain tasks like serialization or working with libraries and frameworks.

    Key Aspects of Metadata in .NET:

    1. What is Metadata?

      • Metadata is data that describes the types, methods, and other structures in an assembly.
      • It is embedded into the Assembly when the .NET compiler compiles the source code.
      • It’s separate from the code itself, and is mainly used for runtime operations, reflection, and dynamic loading of types and assemblies.
    2. Where is Metadata Stored?

      • Metadata is embedded in the PE (Portable Executable) files (i.e., DLL or EXE) produced during compilation. These files contain both IL (Intermediate Language) code and metadata.
      • The metadata is contained in the CLI header and metadata tables within the assembly file.
    3. Metadata Components:

      • Types: Information about the classes, interfaces, and enums defined in the assembly.
      • Methods: Metadata about the methods, including method names, parameters, return types, etc.
      • Fields: Information about the fields or properties in a class, including types and attributes.
      • Attributes: Metadata that provides additional information about types, methods, and fields. For example, the [Obsolete] attribute or [Serializable] attribute.
      • References: Information about references to other assemblies that the current assembly depends on.
      • Custom Metadata: You can define custom metadata using attributes.

    1. Assembly Metadata

    Each assembly in .NET has its own set of metadata that describes the assembly itself, including:

    • Assembly Name: The name of the assembly.
    • Version: The version number of the assembly (major, minor, build, revision).
    • Culture: Defines the culture or localization of the assembly (e.g., en-US).
    • Public Key Token: A hash of the public key used in strong-naming the assembly.

    This assembly metadata is often specified in the Assembly Information file (AssemblyInfo.cs) in .NET Framework projects or as part of the project file (.csproj) in .NET Core/.NET 5+ projects.

    Example (in .csproj for .NET Core / .NET 5+):

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <AssemblyName>MyApp</AssemblyName>
        <Version>1.0.0</Version>
        <Description>My first application</Description>
        <Company>MyCompany</Company>
        <Authors>Author Name</Authors>
      </PropertyGroup>
    
    </Project>
    

    In this example, the Version, AssemblyName, Description, Company, and other properties will be embedded in the assembly metadata.


    2. Reflection and Metadata

    Reflection is a powerful feature in .NET that allows you to examine the metadata of assemblies at runtime. This is useful for tasks like dynamically loading types, accessing properties, or invoking methods.

    • System.Reflection namespace provides classes to inspect metadata in assemblies.
    • Reflection allows you to inspect types, methods, properties, attributes, and more.

    Example of Using Reflection to Get Metadata:

    using System;
    using System.Reflection;
    
    class Program
    {
        static void Main()
        {
            // Load an assembly
            Assembly assembly = Assembly.LoadFrom("MyApp.dll");
    
            // Get all types in the assembly
            Type[] types = assembly.GetTypes();
    
            foreach (Type type in types)
            {
                Console.WriteLine($"Type: {type.FullName}");
    
                // Get methods of the type
                MethodInfo[] methods = type.GetMethods();
                foreach (MethodInfo method in methods)
                {
                    Console.WriteLine($"  Method: {method.Name}");
                }
    
                // Get properties of the type
                PropertyInfo[] properties = type.GetProperties();
                foreach (PropertyInfo property in properties)
                {
                    Console.WriteLine($"  Property: {property.Name}");
                }
            }
        }
    }
    

    This code dynamically loads an assembly (MyApp.dll), and then reflects on its types, methods, and properties, printing them to the console.


    3. Custom Attributes in Metadata

    In .NET, you can create custom attributes to add metadata to your types, methods, properties, etc. Custom attributes can be used to provide additional information about code elements, which can then be accessed at runtime via reflection.

    Example of a Custom Attribute:

    using System;
    
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class DocumentationAttribute : Attribute
    {
        public string Author { get; }
        public string Description { get; }
    
        public DocumentationAttribute(string author, string description)
        {
            Author = author;
            Description = description;
        }
    }
    
    [Documentation("John Doe", "This class does important work.")]
    public class MyClass
    {
        [Documentation("Jane Smith", "This method calculates the result.")]
        public int Calculate(int a, int b) => a + b;
    }
    
    class Program
    {
        static void Main()
        {
            Type type = typeof(MyClass);
            var attributes = type.GetCustomAttributes(typeof(DocumentationAttribute), false);
            foreach (DocumentationAttribute attr in attributes)
            {
                Console.WriteLine($"Class Author: {attr.Author}, Description: {attr.Description}");
            }
    
            MethodInfo methodInfo = type.GetMethod("Calculate");
            var methodAttributes = methodInfo.GetCustomAttributes(typeof(DocumentationAttribute), false);
            foreach (DocumentationAttribute attr in methodAttributes)
            {
                Console.WriteLine($"Method Author: {attr.Author}, Description: {attr.Description}");
            }
        }
    }
    

    In this example, the DocumentationAttribute is a custom attribute used to provide metadata about classes and methods. This metadata can be accessed via reflection at runtime.


    4. Common Metadata Use Cases

    • Versioning: Metadata is often used for version control of assemblies. The assembly version in metadata allows the runtime to ensure compatibility between different versions of an assembly.
    • Reflection: Reflection is commonly used in frameworks and libraries (such as ORMs or Dependency Injection frameworks) to discover types, properties, and methods dynamically.
    • Serialization: Metadata often provides the necessary information for serialization and deserialization frameworks to correctly convert objects to and from various formats (e.g., JSON, XML).
    • Custom Attributes: Used for adding business-specific metadata to code elements (e.g., marking methods as deprecated or making classes serializable).

    5. Viewing Metadata

    You can view the metadata embedded in an assembly using several tools:

    • ILSpy: A popular .NET decompiler that allows you to view metadata, IL code, and more.
    • dotPeek: A JetBrains tool that decompiles .NET assemblies and lets you inspect metadata.
    • Reflector: Another decompiler that helps in inspecting assemblies and metadata.
    • PE Explorer: Allows you to view the PE headers and metadata of executable files.

    Using ILDasm (Intermediate Language Disassembler)

    ILDasm is a tool provided by the .NET SDK that can display the metadata of assemblies. You can open an assembly and inspect its metadata.

    ildasm MyApp.dll
    

    This will open the IL Disassembler window, allowing you to browse through the assembly's metadata, types, methods, and more.


    6. Modifying Metadata

    While metadata is typically read-only, it can be modified using certain tools, such as:

    • Mono.Cecil: A library for reading and writing .NET assemblies, including modifying metadata.
    • System.Reflection.Emit: Allows you to dynamically create or modify types and methods in metadata during runtime.

    7. Summary

    • Metadata in .NET is crucial for describing the structure of assemblies, types, methods, and other components.
    • It is stored in the assembly file and used at runtime for operations like reflection and dynamic loading.
    • Reflection allows you to access and inspect metadata programmatically.
    • You can add custom metadata via attributes, which can be inspected at runtime.
    • Tools like ILSpy, dotPeek, and ILDasm help you view and analyze assembly metadata.
    • Metadata is often used for versioning, serialization, and reflection.

    By leveraging metadata, .NET developers can create flexible, dynamic, and maintainable code that adapts to changing requirements, while also ensuring that additional information can be easily accessed at runtime.

    Previous topic 26
    Using SDK Tools for Signing and Deployment
    Next topic 28
    Reflection

    Past Papers

    Open this section to load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time7 min
      Word count1,243
      Code examples0
      DifficultyIntermediate