Skip to content

Instantly share code, notes, and snippets.

using System;
using System.Linq;
namespace CSharp_Attributes_Walkthrough.My_Custom_Attributes
{
[Alias("Filipino_Customers", ConsoleColor.Yellow)]
public class Customer
{
[Alias("Fname", ConsoleColor.White, AlternativeName = "Customer_FirstName")]
public string Firstname { get; set; }
using CSharp_Attributes_Walkthrough.My_Custom_Attributes;
using System;
namespace Implementing_Csharp_Attributes_101
{
class Program
{
static void Main(string[] args)
{
var customer = new Customer { Firstname = "Jin Vincent" , LastName = "Necesario" };
[Fact]
public void Test_GetAll_AttributeTargets()
{
var targets = Enum.GetNames(typeof(AttributeTargets));
foreach (var target in targets)
{
this._output.WriteLine($"AttributeTargets.{target}");
}
using CSharp_Attributes_Walkthrough.My_Custom_Attributes;
using System;
namespace CSharp_Attributes_Walkthrough.My_Custom_Attributes
{
public class AliasAttribute : Attribute
{
//....
//Added an optional-parameter
using System;
namespace CSharp_Attributes_Walkthrough.My_Custom_Attributes
{
public class AliasAttribute : Attribute
{
/// <summary>
/// These parameters will become mandatory once have you decided to use this attribute.
/// </summary>
/// <param name="alias"></param>
using System;
namespace CSharp_Attributes_Walkthrough.My_Custom_Attributes
{
public class AliasAttribute : Attribute
{
//This is how to define a custom attributes.
}
}
using System;
namespace CSharp_Attributes_Walkthrough.My_Custom_Attributes
{
/// <summary>
/// This class is a custom attribute class.
/// Moreover, it is using the AttributeUsage attribute to annotate
/// that this attribute is applicable only to class, struct and property.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property)]
[Fact]
public void Test_Read_Attributes()
{
//get the Product-class
var type = typeof(Product);
//Get the attributes of the Product-class and we are expecting the [Serializable]
var attribute = (SerializableAttribute)type.
GetCustomAttributes(typeof(SerializableAttribute), false).FirstOrDefault();
using System;
using System.Diagnostics;
namespace CSharp_Attributes_Walkthrough.My_Custom_Attributes
{
[Serializable]
public class Product
{
public string Name { get; set; }
public string Code { get; set; }
[Fact]
public void Test_GetAll_BuiltIn_Attributes()
{
var assembly = Assembly.Load(assemblyFullName);
var attributes = assembly
.DefinedTypes
.Where(type =>
type
.IsSubclassOf(typeof(Attribute)));