C# Dynamic Coding – Attributes in Depth

The .NET common language offers the implementation of dynamic coding practice at runtime by introducing the Attributes that enable to associate custom metadata which are generated compile-time and embedded in the .NET assembly with program elements. Furthermore, these metadata can easily be examined by employing the .NET mechanism called Reflection. So, this article bestows a brief understanding of the usage of the .NET attributes in the dynamic programming perspective.

Attributes

Attributes derived from the System.Attribute class. Attributes can be positioned on most any revelation, however, a particular characteristic may limit the kinds of presentations on which it is substantial. In .NET code, we can determine the attributes by putting the name of the attributes encased in square sections ([]) over the declaration of the element to which it applies. Besides, we can incorporate extra metadata into a get together utilizing qualities. More so, attributes resemble descriptive words, utilized for metadata explanation like COM components that can be applied to a given kind, get together, modules, techniques and many more. Here is the syntax of an attribute in .NET programming as following;

[type: attributeName(parameter1, parameter2, ………n)]

The .NET constructs specify two types of properties for the usage of attributes either as Predefined Attributes or Custom Attributes. Attributes typically can have wither zero or more parameters. The following C# code is, therefore, poses the execution of Attributes where a method is being declared as deprecated using obsolete as;

filter_none

edit
close

play_arrow

link
brightness_4
code

using System;
  
namespace attributes {
class Program {
    static void Main(string[] args)
    {
        Console.WriteLine("C# Dynamic code sample");
        // Deprecated method call
        TestMethod();
        Console.ReadKey();
    }
    // "declaring the TestMethod() as Obsolete by attrribute"
    [Obsolete("Deprecated function", false)] public static void TestMethod()
    {
        Console.WriteLine("geeksForGeeks");
    }
}
}

chevron_right


The ILDASM utility of the .NET framework could be harness to verify the entry of the Obsolete attribute in the generated MSIL code of the corresponding aforesaid code through as following;

C# Dynamic Coding - Attributes in Depth



The ILDASM utility generates the code behind IL code to a .NET assembly, hence, double-click on the obsolete method myFun() entry, and it reflects the entry of the Obsolete attribute as following;

C# Dynamic Coding - Attributes in Depth

Attributes serve the purpose of information definition, reflection, web services, serialization, set-up the class blueprint, and specify the third party library at run-time. Overall, it is conducive to make an entry to the metadata table for a documentation point of view. Moreover, the compile automatically discovers the presence of the attribute entry during debugging. The .NET framework stipulates Custome and Predefined attributes in the source code. The forthcoming section depicts the implementation of some predefined attributes in the code.

Serialization

Let’s have a look to the following class code having with the serialization attribute connotation with a non-serialized field as following;

filter_none

edit
close

play_arrow

link
brightness_4
code

// Serialization class declaration with attribute
[Serializable] public class xyz {
    public xyz() {}
  
    string custName;
    string Address;
    // Non- serialized method attribute
    [NonSerialized] int MobPhone;
}

chevron_right


We can again duly check both of the entry of serializing and non-serialize attributes entry into the IL code as following;

DllImport

The following code sample illustrates the functioning of [DllIport] attribute which calls an unmanaged dll user32.dll to populate a message box as following;

filter_none

edit
close

play_arrow

link
brightness_4
code

public class xyz {
    // Dll Import API call for MessageBox display
    [DllImport("user32.dll", EntryPoint = "MessageBox")]
        // MessageBox property configuration
        public static extern int
        ShowMessageBox(int hWnd, string text, string caption, uint type);
}
class Program {
    static void Main(string[] args)
    {
        // Property value initialized
        string caption = "geeksForGeeks";
        string text = "[DLLImport] Attribute";
        // Calling static method of xyz class
        xyz.ShowMessageBox(0, text, caption, 0);
        Console.ReadKey();
    }
}

chevron_right


Up till now, we have experienced the pre-defined attributes, in this series, we can further develop our own custom attributes too, and leverage it in other code. For this, the class must be prefixed with attributes and derived to System. Attribute class as following;

filter_none

edit
close

play_arrow

link
brightness_4
code

class Program {
    static void Main(string[] args)
    {
        xyz obj = new xyz("GeeksforGeeks", "Hyderabad");
        Console.WriteLine(obj.FullDetails());
        Console.ReadKey();
    }
}
public class xyz {
    public xyz(string name, string country)
    {
        this.Name = name;
        this.City = country;
    }
    public string FullDetails()
    {
        string str = Name + "-" + City;
        return str;
    }
  
    private string Name;
    private string City;
}
// Custom Attribute Class
[AttributeUsage(AttributeTargets.Class)] public class custAttribute : Attribute {
    // Constructor
    public custAttribute(string s)
    {
        this.CompanyName = s;
    }
    public string CompanyName
    {
        get;
        set;
    }
}

chevron_right


After compiling this aforesaid code, we can observe the custom attribute annotation happen in the metadata level by using ildasm.exe as follows;




My Personal Notes arrow_drop_up

Recommended Posts:


    Check out this Author's contributed articles.

    If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

    Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.