Monday, August 8, 2016

Attributes and Reflection

Attributes
Declarative information,help documentation with your program to makes developers life easier . (types, methods, properties, and so forth). 

Associating value editors to a specific type in a GUI framework (through a ValueEditorattribute).

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property )]
public class SampleEAttribute : Attribute
{
    public string Name { get; set; }
    public int Version { get; set; }
}

[SampleE(Name = "OBY", Version = 1)]
public class Test
{
   [SampleE]
   public int MyTestProperty { get; set; }
}

[Obsolete("Don't use OldMethod, use NewMethod instead", false)] // true will get error  public static void OldMethod()
{
      Console.WriteLine("It is the old method");

}
Reflection
use Type system. (GetMethod, GetValue,
Enable you to obtain information about loaded assemblies and the types defined within them.


  1. Check the type of an object at runtime (simple calls to typeof() for example)
  2. Inspect the Attributes of an object at runtime to change the behavior of a method (the various serialization methods in .NET)
var assembly = Assembly.GetExecutingAssembly();
Console.WriteLine(assembly.FullName);
var types = assembly.GetTypes().Where(x => x.GetCustomAttributes<SampleEAttribute>().Count() > 0);


Sample Merge new object to Old Object and return old object without (List)

public static T MergeObject<T>(T oldObject, T newObject)
{
    //Not For List
    var propertyNames = newObject.GetType().GetProperties()
          .Where(x => !x.PropertyType.IsConstructedGenericType
          || (x.PropertyType.IsConstructedGenericType
               && x.PropertyType.GetGenericTypeDefinition() != typeof(List<>)))
          .Select(y => y.Name).ToList();

    foreach (var propertyName in propertyNames)
    {
        var value = newObject.GetType().GetProperty(propertyName).GetValue(newObject, null);

        if (value != null)
            oldObject.GetType().GetProperty(propertyName).SetValue(oldObject, value, null);
    }

    return oldObject;

}

No comments:

Post a Comment