SlideShare a Scribd company logo
Mohammad Shaker 
mohammadshaker.com 
@ZGTRShaker 
2011, 2012, 2013, 2014 
C# Advanced 
L05-Attributes, Conditional Methods and Reflection
Attributes
AttributesMuch of the C# language enables the programmer to specify declarative information about the entities defined in the program. For example, the accessibility of a method in a class is specified by decorating it with the method-modifiers public, protected, internal, and private. C# enables programmers to invent new kinds of declarative information, called attributes. Programmers can then attach attributes to various program entities, and retrieve attribute information in a run-time environment. For instance, a framework might define a HelpAttributeattribute that can be placed on certain program elements (such as classes and methods) to provide a mapping from those program elements to their documentation. (from MSDN)
"DLL Hell“ problem
"DLL Hell“ problem 
•can be caused by one application overwritinga sharedlibrary of another application, usually with a different version. 
•Imagine you write an application with a shared library and then years later create a new application with an updated library. 
•In order not to break old programs, what do you do with the new library? You give it a different name, store it in a different location, or overwrite the old ones?
"DLL Hell“ problem 
•can be caused by one application overwritinga sharedlibrary of another application, usually with a different version. 
•Imagine you write an application with a shared library and then years later create a new application with an updated library. 
•In order not to break old programs, what do you do with the new library? You give it a different name, store it in a different location, or overwrite the old ones?
Assemblies
Assemblies 
•What’s an assembly? 
–An assembly is a file that is automatically generated by the compiler upon successful compilation of every.NET application. It can be either a Dynamic Link Library or an executable file. It is generated only once for an application and upon each subsequent compilation the assembly gets updated. 
–contains the intermediate code, resources, and the metadata for itself. 
–We can have a look inside the assembly using the ildasm(Intermediate Language Disassembler) tool that comes as part of Visual Studio. 
–To access it you need to open the Visual Studio Command Prompt and type ildasm.exe. This will launch a Windows application that you can use to explore any.Netapplication.
Attributes and Reflection 
•Attributes 
–Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties, and so forth). 
–Once associated with a program entity, the attribute can be queried at run time and used in any number of ways.
Attributes and Reflection 
•Example usage of attributes includes: 
–Associating help documentation with program entities (through aHelpattribute). 
–Associating value editors to a specific type in a GUI framework (through aValueEditorattribute).
Example at the start!
Example at the start! If you understand this, it’s over
Example at the start 
enumCarColour 
{ 
[Description("Ice Cream White")] 
White, 
[Description("Carbon Black")] 
Black, 
[Description("Sterling Silver")] 
Silver, 
Red 
}
Example at the start 
enumCarColour 
{ 
[Description("Ice Cream White")] 
White, 
[Description("Carbon Black")] 
Black, 
[Description("Sterling Silver")] 
Silver, 
Red 
} 
Attributes
Example at the start 
public static class EnumExtensions 
{ 
public static string Description(this EnumenumValue) 
{ 
varenumType= enumValue.GetType(); 
varfield = enumType.GetField(enumValue.ToString()); 
varattributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); 
return ((DescriptionAttribute)attributes[0]).Description; 
} 
} 
enumCarColour 
{ 
[Description("Ice Cream White")] 
White, 
[Description("Carbon Black")] 
Black, 
[Description("Sterling Silver")] 
Silver, 
Red 
}
Example at the start 
public static class EnumExtensions 
{ 
public static string Description(this EnumenumValue) 
{ 
varenumType= enumValue.GetType(); 
varfield = enumType.GetField(enumValue.ToString()); 
varattributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); 
return ((DescriptionAttribute)attributes[0]).Description; 
} 
} 
enumCarColour 
{ 
[Description("Ice Cream White")] 
White, 
[Description("Carbon Black")] 
Black, 
[Description("Sterling Silver")] 
Silver, 
Red 
} 
Extension Method
Example at the start 
public static class EnumExtensions 
{ 
public static string Description(this EnumenumValue) 
{ 
varenumType= enumValue.GetType(); 
varfield = enumType.GetField(enumValue.ToString()); 
varattributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); 
return ((DescriptionAttribute)attributes[0]).Description; 
} 
} 
enumCarColour 
{ 
[Description("Ice Cream White")] 
White, 
[Description("Carbon Black")] 
Black, 
[Description("Sterling Silver")] 
Silver, 
Red 
} 
Reflection
Example at the start 
public static class EnumExtensions 
{ 
public static string Description(this EnumenumValue) 
{ 
varenumType= enumValue.GetType(); 
varfield = enumType.GetField(enumValue.ToString()); 
varattributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); 
return ((DescriptionAttribute)attributes[0]).Description; 
} 
} 
enumCarColour 
{ 
[Description("Ice Cream White")] 
White, 
[Description("Carbon Black")] 
Black, 
[Description("Sterling Silver")] 
Silver, 
Red 
}
Example at the start 
public static class EnumExtensions 
{ 
public static string Description(this EnumenumValue) 
{ 
varenumType= enumValue.GetType(); 
varfield = enumType.GetField(enumValue.ToString()); 
varattributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); 
return ((DescriptionAttribute)attributes[0]).Description; 
} 
} 
enumCarColour 
{ 
[Description("Ice Cream White")] 
White, 
[Description("Carbon Black")] 
Black, 
[Description("Sterling Silver")] 
Silver, 
Red 
}
Example at the start 
public static class EnumExtensions 
{ 
public static string Description(this EnumenumValue) 
{ 
varenumType= enumValue.GetType(); 
varfield = enumType.GetField(enumValue.ToString()); 
varattributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); 
return ((DescriptionAttribute)attributes[0]).Description; 
} 
} 
for (CarColourcc = CarColour.White; cc <= CarColour.Red; cc++) 
{ 
Console.WriteLine(cc.Description()); 
} 
enumCarColour 
{ 
[Description("Ice Cream White")] 
White, 
[Description("Carbon Black")] 
Black, 
[Description("Sterling Silver")] 
Silver, 
Red 
}
Example at the start 
public static class EnumExtensions 
{ 
public static string Description(this EnumenumValue) 
{ 
varenumType= enumValue.GetType(); 
varfield = enumType.GetField(enumValue.ToString()); 
varattributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); 
return ((DescriptionAttribute)attributes[0]).Description; 
} 
} 
for (CarColourcc = CarColour.White; cc <= CarColour.Red; cc++) 
{ 
Console.WriteLine(cc.Description()); 
} 
enumCarColour 
{ 
[Description("Ice Cream White")] 
White, 
[Description("Carbon Black")] 
Black, 
[Description("Sterling Silver")] 
Silver, 
Red 
} 
Ice Cream White 
Carbon Black 
Sterling Silver 
Red
Concept of Attributes
Attributes Basics 
•Attributes are generally applied physically in front of type and type member declarations. They're declared with square brackets, "[" and "]", surrounding the attribute such as the followingObsoleteAttributeattribute: 
•[ObsoleteAttribute] 
AttributeUsage 
Describes how a custom attribute class can be used. 
Conditional 
Marks a conditional method, a method whose execution depends on a specified preprocessing identifier. 
Obsolete 
Marks a program entity that should not be used.
Attribute, Obsolete
Pre-Defined Attributes 
usingSystem; classBasicAttributeDemo{ [Obsolete] publicvoidMyFirstdeprecatedMethod() { Console.WriteLine("Called MyFirstdeprecatedMethod()."); } [ObsoleteAttribute] publicvoidMySecondDeprecatedMethod() { Console.WriteLine("Called MySecondDeprecatedMethod()."); } [Obsolete("You shouldn't use this method anymore.")] publicvoidMyThirdDeprecatedMethod() { Console.WriteLine("Called MyThirdDeprecatedMethod()."); }
Pre-Defined Attributes 
usingSystem; classBasicAttributeDemo{ [Obsolete] publicvoidMyFirstdeprecatedMethod() { Console.WriteLine("Called MyFirstdeprecatedMethod()."); } [ObsoleteAttribute] publicvoidMySecondDeprecatedMethod() { Console.WriteLine("Called MySecondDeprecatedMethod()."); } [Obsolete("You shouldn't use this method anymore.")] publicvoidMyThirdDeprecatedMethod() { Console.WriteLine("Called MyThirdDeprecatedMethod()."); }
Pre-Defined Attributes 
usingSystem; classBasicAttributeDemo{ [Obsolete] publicvoidMyFirstdeprecatedMethod() { Console.WriteLine("Called MyFirstdeprecatedMethod()."); } [ObsoleteAttribute] publicvoidMySecondDeprecatedMethod() { Console.WriteLine("Called MySecondDeprecatedMethod()."); } [Obsolete("You shouldn't use this method anymore.")] publicvoidMyThirdDeprecatedMethod() { Console.WriteLine("Called MyThirdDeprecatedMethod()."); }
Pre-Defined Attributes 
usingSystem; classBasicAttributeDemo{ [Obsolete] publicvoidMyFirstdeprecatedMethod() { Console.WriteLine("Called MyFirstdeprecatedMethod()."); } [ObsoleteAttribute] publicvoidMySecondDeprecatedMethod() { Console.WriteLine("Called MySecondDeprecatedMethod()."); } [Obsolete("You shouldn't use this method anymore.")] publicvoidMyThirdDeprecatedMethod() { Console.WriteLine("Called MyThirdDeprecatedMethod()."); }
Pre-Defined Attributes 
// make the program thread safe for COM[STAThread] staticvoidMain(string[] args) { BasicAttributeDemoattrDemo=newBasicAttributeDemo(); attrDemo.MyFirstdeprecatedMethod(); attrDemo.MySecondDeprecatedMethod(); attrDemo.MyThirdDeprecatedMethod(); } }
Pre-Defined Attributes 
// make the program thread safe for COM[STAThread] staticvoidMain(string[] args) { BasicAttributeDemoattrDemo=newBasicAttributeDemo(); attrDemo.MyFirstdeprecatedMethod(); attrDemo.MySecondDeprecatedMethod(); attrDemo.MyThirdDeprecatedMethod(); } }
Attribute, AttributeUsage
AttributeUsageDescribes how a custom attribute class can be used. 
[AttributeUsage( 
validon, 
AllowMultiple=allowmultiple, 
Inherited=inherited 
)]
User-Defined Attributes 
[Author("H. Ackerman", version = 1.1)] 
classSampleClass
User-Defined Attributes 
[Author("H. Ackerman", version = 1.1)] 
classSampleClass 
Author anonymousAuthorObject= newAuthor("H. Ackerman"); 
anonymousAuthorObject.version= 1.1;
User-Defined Attributes 
[Author("H. Ackerman", version = 1.1)] 
classSampleClass 
Author anonymousAuthorObject= newAuthor("H. Ackerman"); 
anonymousAuthorObject.version= 1.1; 
conceptually 
equivalent
Attribute, Conditional
Conditional Methodsallow developers to create methods whose calls can be placed in the code and then either included or omitted during compilation based on a preprocessing symbol.
Conditional Methods 
•TheConditional attribute takes one parameter —the preprocessing identifier that controls whether the method call is included when clients are compiled. If the preprocessing identifier is defined, the method is called; otherwise, the call is never inserted in the client's code. 
using System; 
using System.Diagnostics; 
namespace TraceFunctions 
{ 
public class Trace 
{ 
[Conditional("DEBUG")] 
public static void Message(string traceMessage) 
{ 
Console.WriteLine("[TRACE] -" + traceMessage); 
} 
} 
}
[Serializable]
[Serializable] Says that the object is Serializable
[Serializable] Says that the object is SerializableSo you can Stream it and save the object into, like, a file!
Reflection
ReflectionAsk the object itself about itself
Types
Types and Reflection 
•Reflection 
–Provides objects (of typeType) that encapsulate assemblies, modules and types. 
–You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. 
–If you are using attributes in your code, Reflection enables you to access them.
Types and Reflection 
•Reflection is useful in the following situations: 
–When you need to access attributes in your program's metadata. 
•“Accessing Attributes With Reflection” 
–For examining and instantiating types in an assembly. 
–For building new types at runtime. Use classes inSystem.Reflection.Emit 
–For performing late binding, accessing methods on types created at run time.
Types and Reflection 
•Reflection is useful in the following situations: 
–When you need to access attributes in your program's metadata. 
•“Accessing Attributes With Reflection” 
–For examining and instantiating types in an assembly. 
–For building new types at runtime. Use classes inSystem.Reflection.Emit 
–For performing late binding, accessing methods on types created at run time.
System.Type class
System.Typeclass 
•TheSystem.Typeclass is central to reflection. 
•The common language runtime creates theTypefor a loaded type when reflection requests it. You can use aTypeobject's methods, fields, properties, and nested classes to find out everything about that type.
System.Typeclass 
•Simple example of Reflection using the static methodGetType-inherited by all types from theObjectbase class -to obtain the type of a variable: 
// Using GetTypeto obtain type information: 
inti=42; 
System.Typetype=i.GetType(); 
System.Console.WriteLine(type);
System.Typeclass 
•Simple example of Reflection using the static methodGetType-inherited by all types from theObjectbase class -to obtain the type of a variable: 
// Using GetTypeto obtain type information: 
inti=42; 
System.Typetype=i.GetType(); 
System.Console.WriteLine(type); 
System.Int32
Types and Reflection 
•Identifying all Types that Implement an Interface (http://www.blackwasp.co.uk/) 
public interface IParent{ } 
public class Parent { } 
public class Child1 : Parent { } 
public class Child2 : Parent { } 
public class Grandchild11 : Child1 { } 
public class Grandchild12 : Child1 { } 
public class Grandchild21 : Child2 { } 
public class Grandchild22 : Child2 { } 
public class NotAChild{ } 
public class NotAGrandchild: NotAChild{ } 
Type parentType= typeof(IParent); 
Assembly assembly= Assembly.GetExecutingAssembly(); 
Type[] types = assembly.GetTypes();
Types and Reflection 
•Identifying all Types that Implement an Interface 
public interface IParent{ } 
public class Parent { } 
public class Child1 : Parent { } 
public class Child2 : Parent { } 
public class Grandchild11 : Child1 { } 
public class Grandchild12 : Child1 { } 
public class Grandchild21 : Child2 { } 
public class Grandchild22 : Child2 { } 
public class NotAChild{ } 
public class NotAGrandchild: NotAChild{ } 
IEnumerable<Type> imp = types.Where(t => t.GetInterfaces().Contains(interfaceType)); 
foreach(Type typein imp) 
{ 
Console.WriteLine(type.Name); 
} 
/* OUTPUT 
Parent 
Child1 
Child2 
Grandchild11 
Grandchild12 
Grandchild21 
Grandchild22 
*/ 
Type parentType= typeof(IParent); 
Assembly assembly= Assembly.GetExecutingAssembly(); 
Type[] types = assembly.GetTypes();
Types and Reflection 
•Identifying all Subclasses of a Class (http://www.blackwasp.co.uk/) 
public interface IParent{ } 
public class Parent { } 
public class Child1 : Parent { } 
public class Child2 : Parent { } 
public class Grandchild11 : Child1 { } 
public class Grandchild12 : Child1 { } 
public class Grandchild21 : Child2 { } 
public class Grandchild22 : Child2 { } 
public class NotAChild{ } 
public class NotAGrandchild: NotAChild{ } 
Type parentType= typeof(IParent); 
Assembly assembly= Assembly.GetExecutingAssembly(); 
Type[] types = assembly.GetTypes();
Types and Reflection 
•Identifying all Subclasses of a Class 
public interface IParent{ } 
public class Parent { } 
public class Child1 : Parent { } 
public class Child2 : Parent { } 
public class Grandchild11 : Child1 { } 
public class Grandchild12 : Child1 { } 
public class Grandchild21 : Child2 { } 
public class Grandchild22 : Child2 { } 
public class NotAChild{ } 
public class NotAGrandchild: NotAChild{ } 
IEnumerable<Type> subclasses = types.Where(t => t.IsSubclassOf(parentType)); 
foreach(Type typein subclasses) 
{ 
Console.WriteLine(type.Name); 
} 
/* OUTPUT 
Child1 
Child2 
Grandchild11 
Grandchild12 
Grandchild21 
Grandchild22 
*/ 
Type parentType= typeof(IParent); 
Assembly assembly= Assembly.GetExecutingAssembly(); 
Type[] types = assembly.GetTypes();
Test CaseGetting Constructors of StringClass
Types and Reflection 
// This program lists all the public constructors 
// of the System.Stringclass. 
usingSystem; 
usingSystem.Reflection; 
classListMembers 
{ 
publicstaticvoidMain(String[] args) 
{ 
Typet=typeof(System.String); 
Console.WriteLine("Listing all the public constructors of the {0} type", t); 
// Constructors. 
ConstructorInfo[] ci=t.GetConstructors(BindingFlags.Public|BindingFlags.Instance); 
Console.WriteLine("//Constructors"); 
PrintMembers(ci); 
} 
publicstaticvoidPrintMembers(MemberInfo[] ms) 
{ 
foreach(MemberInfominms) 
{ 
Console.WriteLine("{0}{1}", " ", m); 
} 
Console.WriteLine(); 
} 
}
Types and Reflection 
// This program lists all the public constructors 
// of the System.Stringclass. 
usingSystem; 
usingSystem.Reflection; 
classListMembers 
{ 
publicstaticvoidMain(String[] args) 
{ 
Typet=typeof(System.String); 
Console.WriteLine("Listing all the public constructors of the {0} type", t); 
// Constructors. 
ConstructorInfo[] ci=t.GetConstructors(BindingFlags.Public|BindingFlags.Instance); 
Console.WriteLine("//Constructors"); 
PrintMembers(ci); 
} 
publicstaticvoidPrintMembers(MemberInfo[] ms) 
{ 
foreach(MemberInfominms) 
{ 
Console.WriteLine("{0}{1}", " ", m); 
} 
Console.WriteLine(); 
} 
} 
Listing all the public constructors of the System.Stringtype 
//Constructors 
Void.ctor(Char*) 
Void.ctor(Char*, Int32, Int32) 
Void.ctor(SByte*) 
Void.ctor(SByte*, Int32, Int32) 
Void.ctor(SByte*, Int32, Int32, System.Text.Encoding) 
Void.ctor(Char[], Int32, Int32) 
Void.ctor(Char[]) 
Void.ctor(Char, Int32) 
Press any key to continue...
Invoking Overloaded Methods Using Reflectionhttp://www.blackwasp.co.uk/
Invoking Overloaded Methods Using Reflection 
public class Test 
{ 
public void ShowMessage() 
{ 
Console.WriteLine("Hello, world"); 
} 
public void ShowMessage(string msg, inttimesToShow) 
{ 
for (inti= 0; i< timesToShow; i++) 
{ 
Console.WriteLine(msg); 
} 
} 
}
Invoking Overloaded Methods Using Reflection 
public class Test 
{ 
public void ShowMessage() 
{ 
Console.WriteLine("Hello, world"); 
} 
public void ShowMessage(string msg, inttimesToShow) 
{ 
for (inti= 0; i< timesToShow; i++) 
{ 
Console.WriteLine(msg); 
} 
} 
} 
Test test= new Test(); 
Type type= test.GetType(); 
MethodInfomethod = type.GetMethod("ShowMessage", new Type[] { typeof(string), typeof(int) }); 
method.Invoke(test, new object[] { "Exterminate!", 3 });
Invoking Overloaded Methods Using Reflection 
public class Test 
{ 
public void ShowMessage() 
{ 
Console.WriteLine("Hello, world"); 
} 
public void ShowMessage(string msg, inttimesToShow) 
{ 
for (inti= 0; i< timesToShow; i++) 
{ 
Console.WriteLine(msg); 
} 
} 
} 
Test test= new Test(); 
Type type= test.GetType(); 
MethodInfomethod = type.GetMethod("ShowMessage", new Type[] { typeof(string), typeof(int) }); 
method.Invoke(test, new object[] { "Exterminate!", 3 });
Invoking Overloaded Methods Using Reflection 
public class Test 
{ 
public void ShowMessage() 
{ 
Console.WriteLine("Hello, world"); 
} 
public void ShowMessage(string msg, inttimesToShow) 
{ 
for (inti= 0; i< timesToShow; i++) 
{ 
Console.WriteLine(msg); 
} 
} 
} 
Test test= new Test(); 
Type type= test.GetType(); 
MethodInfomethod = type.GetMethod("ShowMessage", new Type[] { typeof(string), typeof(int) }); 
method.Invoke(test, new object[] { "Exterminate!", 3 }); 
Exterminate! 
Exterminate! 
Exterminate!
Accessing Attributes Through Reflection
Accessing Attributes Through ReflectionYou don’t have to read..
Accessing Attributes Through Reflection 
class MainClass 
{ 
public static void Main() 
{ 
System.Reflection.MemberInfoinfo = typeof(MyClass); 
object[] attributes = info.GetCustomAttributes(true); 
for (inti = 0; i < attributes.Length; i++) 
{ 
System.Console.WriteLine(attributes[i]); 
} 
} 
}
Accessing Attributes Through Reflection 
classMainClass 
{ 
publicstaticvoidMain() 
{ 
System.Reflection.MemberInfoinfo=typeof(MyClass); 
object[] attributes=info.GetCustomAttributes(true); 
for(inti=0; i<attributes.Length; i++) 
{ 
System.Console.WriteLine(attributes[i]); 
} 
} 
}
Accessing Attributes Through Reflection 
•Let’s have the following giantexample! 
publicclassIsTestedAttribute: Attribute 
{ 
publicoverridestringToString() 
{ 
return"Is Tested"; 
} 
}
Concept of Attributes 
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct)] 
publicclassAuthorAttribute: Attribute 
{ 
publicAuthorAttribute(stringname) 
{ 
this.name=name; 
this.version=0; 
} 
publicstringName 
{ get 
{ 
returnname; 
} 
} 
publicintVersion 
{ 
get 
{ 
returnversion; 
} 
set 
{ 
version=value; 
} 
} 
publicoverridestringToString() 
{ 
stringvalue="Author : "+Name; 
if(version!=0) 
{ 
value+=" Version : "+Version.ToString(); 
} 
returnvalue; 
} 
privatestringname; 
privateintversion; 
}
Concept of Attributes 
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct)] 
publicclassAuthorAttribute: Attribute 
{ 
publicAuthorAttribute(stringname) 
{ 
this.name=name; 
this.version=0; 
} 
publicstringName 
{ get 
{ 
returnname; 
} 
} 
publicintVersion 
{ 
get 
{ 
returnversion; 
} 
set 
{ 
version=value; 
} 
} 
publicoverridestringToString() 
{ 
stringvalue="Author : "+Name; 
if(version!=0) 
{ 
value+=" Version : "+Version.ToString(); 
} 
returnvalue; 
} 
privatestringname; 
privateintversion; 
}
Concept of Attributes 
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct)] 
publicclassAuthorAttribute: Attribute 
{ 
publicAuthorAttribute(stringname) 
{ 
this.name=name; 
this.version=0; 
} 
publicstringName 
{ get 
{ 
returnname; 
} 
} 
publicintVersion 
{ 
get 
{ 
returnversion; 
} 
set 
{ 
version=value; 
} 
} 
publicoverridestringToString() 
{ 
stringvalue="Author : "+Name; 
if(version!=0) 
{ 
value+=" Version : "+Version.ToString(); 
} 
returnvalue; 
} 
privatestringname; 
privateintversion; 
}
Concept of Attributes 
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct)] 
publicclassAuthorAttribute: Attribute 
{ 
publicAuthorAttribute(stringname) 
{ 
this.name=name; 
this.version=0; 
} 
publicstringName 
{ get 
{ 
returnname; 
} 
} 
publicintVersion 
{ 
get 
{ 
returnversion; 
} 
set 
{ 
version=value; 
} 
} 
publicoverridestringToString() 
{ 
stringvalue="Author : "+Name; 
if(version!=0) 
{ 
value+=" Version : "+Version.ToString(); 
} 
returnvalue; 
} 
privatestringname; 
privateintversion; 
}
Accessing Attributes Through Reflection 
[Author("Joe Programmer")] 
classAccount 
{ 
// Attach the IsTestedAttributecustom attribute to this method. 
[IsTested] 
publicvoidAddOrder(OrderorderToAdd) 
{ 
orders.Add(orderToAdd); 
} 
privateArrayListorders=newArrayList(); 
} 
[Author("Jane Programmer", Version=2), IsTested()] 
classOrder 
{ 
// add stuff here... 
}
Accessing Attributes Through Reflection 
[Author("Joe Programmer")] 
classAccount 
{ 
// Attach the IsTestedAttributecustom attribute to this method. 
[IsTested] 
publicvoidAddOrder(OrderorderToAdd) 
{ 
orders.Add(orderToAdd); 
} 
privateArrayListorders=newArrayList(); 
} 
[Author("Jane Programmer", Version=2), IsTested()] 
classOrder 
{ 
// add stuff here... 
}
Accessing Attributes Through Reflection 
[Author("Joe Programmer")] 
classAccount 
{ 
// Attach the IsTestedAttributecustom attribute to this method. 
[IsTested] 
publicvoidAddOrder(OrderorderToAdd) 
{ 
orders.Add(orderToAdd); 
} 
privateArrayListorders=newArrayList(); 
} 
[Author("Jane Programmer", Version=2), IsTested()] 
classOrder 
{ 
// add stuff here... 
}
Accessing Attributes Through Reflection 
classMainClass 
{ 
privatestaticboolIsMemberTested(MemberInfomember) 
{ 
foreach(objectattributeinmember.GetCustomAttributes(true)) 
{ 
if(attributeisIsTestedAttribute) 
{ 
returntrue; 
} 
} 
returnfalse; 
} 
privatestaticvoidDumpAttributes(MemberInfomember) 
{ 
Console.WriteLine("Attributes for : "+member.Name); 
foreach(objectattributeinmember.GetCustomAttributes(true)) 
{ 
Console.WriteLine(attribute); 
} 
}
Concept of Attributes 
publicstaticvoidmain() 
{ DumpAttributes(typeof(Account)); 
foreach(MethodInfomethodin(typeof(Account)).GetMethods()) 
{ 
if(IsMemberTested(method)) 
{ 
Console.WriteLine("Member {0} is tested!", method.Name); 
} 
else 
{ 
Console.WriteLine("Member {0} is NOT tested!", method.Name); 
} 
} 
Console.WriteLine(); 
// display attributes for Order class 
DumpAttributes(typeof(Order)); 
// display attributes for methods on the Order class 
foreach(MethodInfomethodin(typeof(Order)).GetMethods()) 
{ 
if(IsMemberTested(method)) 
{ 
Console.WriteLine("Member {0} is tested!", method.Name); 
} 
else 
{ 
Console.WriteLine("Member {0} is NOT tested!", method.Name); 
} 
} 
Console.WriteLine(); } }
Concept of Attributes 
publicstaticvoidmain() 
{ DumpAttributes(typeof(Account)); 
foreach(MethodInfomethodin(typeof(Account)).GetMethods()) 
{ 
if(IsMemberTested(method)) 
{ 
Console.WriteLine("Member {0} is tested!", method.Name); 
} 
else 
{ 
Console.WriteLine("Member {0} is NOT tested!", method.Name); 
} 
} 
Console.WriteLine(); 
// display attributes for Order class 
DumpAttributes(typeof(Order)); 
// display attributes for methods on the Order class 
foreach(MethodInfomethodin(typeof(Order)).GetMethods()) 
{ 
if(IsMemberTested(method)) 
{ 
Console.WriteLine("Member {0} is tested!", method.Name); 
} 
else 
{ 
Console.WriteLine("Member {0} is NOT tested!", method.Name); 
} 
} 
Console.WriteLine(); } }
Concept of Attributes 
publicstaticvoidmain() 
{ DumpAttributes(typeof(Account)); 
foreach(MethodInfomethod in (typeof(Account)).GetMethods()) 
{ 
if (IsMemberTested(method)) 
{ 
Console.WriteLine("Member {0} is tested!", method.Name); 
} 
else 
{ 
Console.WriteLine("Member {0} is NOT tested!", method.Name); 
} 
} 
Console.WriteLine(); 
// display attributes for Order class 
DumpAttributes(typeof(Order)); 
// display attributes for methods on the Order class 
foreach(MethodInfomethod in (typeof(Order)).GetMethods()) 
{ 
if (IsMemberTested(method)) 
{ 
Console.WriteLine("Member {0} is tested!", method.Name); 
} 
else 
{ 
Console.WriteLine("Member {0} is NOT tested!", method.Name); 
} 
} 
Console.WriteLine(); } }
Accessing Attributes Through Reflection 
Attributes for : Account 
Author : Joe Programmer 
Member AddOrderis tested! 
Member ToStringis NOT tested! 
Member Equals is NOT tested! 
Member GetHashCodeis NOT tested! 
Member GetTypeis NOT tested! 
Attributes for : Order 
Author : Jane Programmer Version : 2 
Is Tested 
Member ToStringis NOT tested! 
Member Equals is NOT tested! 
Member GetHashCodeis NOT tested! 
Member GetTypeis NOT tested! 
Press any key to continue...
http://www.mohammadshaker.com 
mohammadshakergtr@gmail.com 
https://twitter.com/ZGTRShaker@ZGTRShakerhttps://de.linkedin.com/pub/mohammad-shaker/30/122/128/ 
http://www.slideshare.net/ZGTRZGTR 
https://www.goodreads.com/user/show/11193121-mohammad-shaker 
https://plus.google.com/u/0/+MohammadShaker/ 
https://www.youtube.com/channel/UCvJUfadMoEaZNWdagdMyCRA 
http://mohammadshakergtr.wordpress.com/

More Related Content

What's hot

Hibernate inheritance and relational mappings with examples
Hibernate inheritance and relational mappings with examplesHibernate inheritance and relational mappings with examples
Hibernate inheritance and relational mappings with examples
Er. Gaurav Kumar
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
Manav Gupta
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
hr1383
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
Javascript functions
Javascript functionsJavascript functions
Javascript functions
Alaref Abushaala
 
S313937 cdi dochez
S313937 cdi dochezS313937 cdi dochez
S313937 cdi dochez
Jerome Dochez
 
Hibernate
Hibernate Hibernate
Hibernate
Sunil OS
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
jeresig
 
KAAccessControl
KAAccessControlKAAccessControl
KAAccessControl
WO Community
 
Java script
Java scriptJava script
Java script
Abhishek Kesharwani
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
Priya Goyal
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To Hibernate
Amit Himani
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Jussi Pohjolainen
 
Placement and variable 03 (js)
Placement and variable 03 (js)Placement and variable 03 (js)
Placement and variable 03 (js)
AbhishekMondal42
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
Paras Mendiratta
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
Scala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgrammingScala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgramming
Meir Maor
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
Boulder Java User's Group
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
Doug Jones
 

What's hot (20)

Hibernate inheritance and relational mappings with examples
Hibernate inheritance and relational mappings with examplesHibernate inheritance and relational mappings with examples
Hibernate inheritance and relational mappings with examples
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScript
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
S313937 cdi dochez
S313937 cdi dochezS313937 cdi dochez
S313937 cdi dochez
 
Hibernate
Hibernate Hibernate
Hibernate
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
KAAccessControl
KAAccessControlKAAccessControl
KAAccessControl
 
Java script
Java scriptJava script
Java script
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To Hibernate
 
JavaScript - Chapter 7 - Advanced Functions
 JavaScript - Chapter 7 - Advanced Functions JavaScript - Chapter 7 - Advanced Functions
JavaScript - Chapter 7 - Advanced Functions
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Placement and variable 03 (js)
Placement and variable 03 (js)Placement and variable 03 (js)
Placement and variable 03 (js)
 
Angular JS2 Training Session #1
Angular JS2 Training Session #1Angular JS2 Training Session #1
Angular JS2 Training Session #1
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
Scala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgrammingScala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgramming
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 

Viewers also liked

Advanced c#
Advanced c#Advanced c#
Advanced c#
AkashThakrar
 
13 iec t1_s1_oo_ps_session_19
13 iec t1_s1_oo_ps_session_1913 iec t1_s1_oo_ps_session_19
13 iec t1_s1_oo_ps_session_19
Niit Care
 
Smoke and Mirrors - Reflection in C#
Smoke and Mirrors - Reflection in C#Smoke and Mirrors - Reflection in C#
Smoke and Mirrors - Reflection in C#
Wekoslav Stefanovski
 
Building & Designing Windows 10 Universal Windows Apps using XAML and C#
Building & Designing Windows 10 Universal Windows Apps using XAML and C#Building & Designing Windows 10 Universal Windows Apps using XAML and C#
Building & Designing Windows 10 Universal Windows Apps using XAML and C#
Fons Sonnemans
 
.NET Attributes and Reflection - What a Developer Needs to Know...
.NET Attributes and Reflection - What a Developer Needs to Know....NET Attributes and Reflection - What a Developer Needs to Know...
.NET Attributes and Reflection - What a Developer Needs to Know...
Dan Douglas
 
Reflection in C#
Reflection in C#Reflection in C#
Reflection in C#
Rohit Vipin Mathews
 
Day02 01 Advance Feature in C# DH TDT
Day02 01 Advance Feature in C# DH TDTDay02 01 Advance Feature in C# DH TDT
Day02 01 Advance Feature in C# DH TDT
Nguyen Patrick
 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
BlackRabbitCoder
 

Viewers also liked (9)

Advanced c#
Advanced c#Advanced c#
Advanced c#
 
Study research in April
Study research in AprilStudy research in April
Study research in April
 
13 iec t1_s1_oo_ps_session_19
13 iec t1_s1_oo_ps_session_1913 iec t1_s1_oo_ps_session_19
13 iec t1_s1_oo_ps_session_19
 
Smoke and Mirrors - Reflection in C#
Smoke and Mirrors - Reflection in C#Smoke and Mirrors - Reflection in C#
Smoke and Mirrors - Reflection in C#
 
Building & Designing Windows 10 Universal Windows Apps using XAML and C#
Building & Designing Windows 10 Universal Windows Apps using XAML and C#Building & Designing Windows 10 Universal Windows Apps using XAML and C#
Building & Designing Windows 10 Universal Windows Apps using XAML and C#
 
.NET Attributes and Reflection - What a Developer Needs to Know...
.NET Attributes and Reflection - What a Developer Needs to Know....NET Attributes and Reflection - What a Developer Needs to Know...
.NET Attributes and Reflection - What a Developer Needs to Know...
 
Reflection in C#
Reflection in C#Reflection in C#
Reflection in C#
 
Day02 01 Advance Feature in C# DH TDT
Day02 01 Advance Feature in C# DH TDTDay02 01 Advance Feature in C# DH TDT
Day02 01 Advance Feature in C# DH TDT
 
C#/.NET Little Wonders
C#/.NET Little WondersC#/.NET Little Wonders
C#/.NET Little Wonders
 

Similar to CSharp Advanced L05-Attributes+Reflection

C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
akreyi
 
Intro to iOS Development • Made by Many
Intro to iOS Development • Made by ManyIntro to iOS Development • Made by Many
Intro to iOS Development • Made by Many
kenatmxm
 
csharp.docx
csharp.docxcsharp.docx
csharp.docx
LenchoMamudeBaro
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
Ananthu Mahesh
 
Generics
GenericsGenerics
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
Yakov Fain
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
YoungSu Son
 
Csharp generics
Csharp genericsCsharp generics
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
David McCarter
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Iván Fernández Perea
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
Zafor Iqbal
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
Nico Ludwig
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
Rafael Coutinho
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
Synapseindiappsdevelopment
 
ProgrammingPrimerAndOOPS
ProgrammingPrimerAndOOPSProgrammingPrimerAndOOPS
ProgrammingPrimerAndOOPS
sunmitraeducation
 
Generic
GenericGeneric
Generic
abhay singh
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
Muhammad Hammad Waseem
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
Yakov Fain
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
lennartkats
 

Similar to CSharp Advanced L05-Attributes+Reflection (20)

C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Intro to iOS Development • Made by Many
Intro to iOS Development • Made by ManyIntro to iOS Development • Made by Many
Intro to iOS Development • Made by Many
 
csharp.docx
csharp.docxcsharp.docx
csharp.docx
 
Csharp_mahesh
Csharp_maheshCsharp_mahesh
Csharp_mahesh
 
Generics
GenericsGenerics
Generics
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Framework engineering JCO 2011
Framework engineering JCO 2011Framework engineering JCO 2011
Framework engineering JCO 2011
 
Csharp generics
Csharp genericsCsharp generics
Csharp generics
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01C Sharp: Basic to Intermediate Part 01
C Sharp: Basic to Intermediate Part 01
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
ProgrammingPrimerAndOOPS
ProgrammingPrimerAndOOPSProgrammingPrimerAndOOPS
ProgrammingPrimerAndOOPS
 
Generic
GenericGeneric
Generic
 
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types[OOP - Lec 13,14,15] Constructors / Destructor and its Types
[OOP - Lec 13,14,15] Constructors / Destructor and its Types
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
 
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
Domain-Specific Languages for Composable Editor Plugins (LDTA 2009)
 

More from Mohammad Shaker

12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian Graduate12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian Graduate
Mohammad Shaker
 
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Mohammad Shaker
 
Interaction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with PsychologyInteraction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with Psychology
Mohammad Shaker
 
Short, Matters, Love - Passioneers Event 2015
Short, Matters, Love -  Passioneers Event 2015Short, Matters, Love -  Passioneers Event 2015
Short, Matters, Love - Passioneers Event 2015
Mohammad Shaker
 
Unity L01 - Game Development
Unity L01 - Game DevelopmentUnity L01 - Game Development
Unity L01 - Game Development
Mohammad Shaker
 
Android L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and WearablesAndroid L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and Wearables
Mohammad Shaker
 
Interaction Design L03 - Color
Interaction Design L03 - ColorInteraction Design L03 - Color
Interaction Design L03 - Color
Mohammad Shaker
 
Interaction Design L05 - Typography
Interaction Design L05 - TypographyInteraction Design L05 - Typography
Interaction Design L05 - Typography
Mohammad Shaker
 
Interaction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and CouplingInteraction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and Coupling
Mohammad Shaker
 
Android L05 - Storage
Android L05 - StorageAndroid L05 - Storage
Android L05 - Storage
Mohammad Shaker
 
Android L04 - Notifications and Threading
Android L04 - Notifications and ThreadingAndroid L04 - Notifications and Threading
Android L04 - Notifications and Threading
Mohammad Shaker
 
Android L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOSAndroid L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOS
Mohammad Shaker
 
Interaction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile ConstraintsInteraction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile Constraints
Mohammad Shaker
 
Interaction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and GridsInteraction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and Grids
Mohammad Shaker
 
Android L10 - Stores and Gaming
Android L10 - Stores and GamingAndroid L10 - Stores and Gaming
Android L10 - Stores and Gaming
Mohammad Shaker
 
Android L06 - Cloud / Parse
Android L06 - Cloud / ParseAndroid L06 - Cloud / Parse
Android L06 - Cloud / Parse
Mohammad Shaker
 
Android L08 - Google Maps and Utilities
Android L08 - Google Maps and UtilitiesAndroid L08 - Google Maps and Utilities
Android L08 - Google Maps and Utilities
Mohammad Shaker
 
Android L03 - Styles and Themes
Android L03 - Styles and Themes Android L03 - Styles and Themes
Android L03 - Styles and Themes
Mohammad Shaker
 
Android L02 - Activities and Adapters
Android L02 - Activities and AdaptersAndroid L02 - Activities and Adapters
Android L02 - Activities and Adapters
Mohammad Shaker
 
Android L01 - Warm Up
Android L01 - Warm UpAndroid L01 - Warm Up
Android L01 - Warm Up
Mohammad Shaker
 

More from Mohammad Shaker (20)

12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian Graduate12 Rules You Should to Know as a Syrian Graduate
12 Rules You Should to Know as a Syrian Graduate
 
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]
 
Interaction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with PsychologyInteraction Design L06 - Tricks with Psychology
Interaction Design L06 - Tricks with Psychology
 
Short, Matters, Love - Passioneers Event 2015
Short, Matters, Love -  Passioneers Event 2015Short, Matters, Love -  Passioneers Event 2015
Short, Matters, Love - Passioneers Event 2015
 
Unity L01 - Game Development
Unity L01 - Game DevelopmentUnity L01 - Game Development
Unity L01 - Game Development
 
Android L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and WearablesAndroid L07 - Touch, Screen and Wearables
Android L07 - Touch, Screen and Wearables
 
Interaction Design L03 - Color
Interaction Design L03 - ColorInteraction Design L03 - Color
Interaction Design L03 - Color
 
Interaction Design L05 - Typography
Interaction Design L05 - TypographyInteraction Design L05 - Typography
Interaction Design L05 - Typography
 
Interaction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and CouplingInteraction Design L04 - Materialise and Coupling
Interaction Design L04 - Materialise and Coupling
 
Android L05 - Storage
Android L05 - StorageAndroid L05 - Storage
Android L05 - Storage
 
Android L04 - Notifications and Threading
Android L04 - Notifications and ThreadingAndroid L04 - Notifications and Threading
Android L04 - Notifications and Threading
 
Android L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOSAndroid L09 - Windows Phone and iOS
Android L09 - Windows Phone and iOS
 
Interaction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile ConstraintsInteraction Design L01 - Mobile Constraints
Interaction Design L01 - Mobile Constraints
 
Interaction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and GridsInteraction Design L02 - Pragnanz and Grids
Interaction Design L02 - Pragnanz and Grids
 
Android L10 - Stores and Gaming
Android L10 - Stores and GamingAndroid L10 - Stores and Gaming
Android L10 - Stores and Gaming
 
Android L06 - Cloud / Parse
Android L06 - Cloud / ParseAndroid L06 - Cloud / Parse
Android L06 - Cloud / Parse
 
Android L08 - Google Maps and Utilities
Android L08 - Google Maps and UtilitiesAndroid L08 - Google Maps and Utilities
Android L08 - Google Maps and Utilities
 
Android L03 - Styles and Themes
Android L03 - Styles and Themes Android L03 - Styles and Themes
Android L03 - Styles and Themes
 
Android L02 - Activities and Adapters
Android L02 - Activities and AdaptersAndroid L02 - Activities and Adapters
Android L02 - Activities and Adapters
 
Android L01 - Warm Up
Android L01 - Warm UpAndroid L01 - Warm Up
Android L01 - Warm Up
 

Recently uploaded

Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
ICS
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
Neo4j
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
Gerardo Pardo-Castellote
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
Peter Muessig
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Undress Baby
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
Remote DBA Services
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
kalichargn70th171
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Envertis Software Solutions
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
pavan998932
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 

Recently uploaded (20)

Webinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for EmbeddedWebinar On-Demand: Using Flutter for Embedded
Webinar On-Demand: Using Flutter for Embedded
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
GraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph TechnologyGraphSummit Paris - The art of the possible with Graph Technology
GraphSummit Paris - The art of the possible with Graph Technology
 
DDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systemsDDS-Security 1.2 - What's New? Stronger security for long-running systems
DDS-Security 1.2 - What's New? Stronger security for long-running systems
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsUI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
UI5con 2024 - Boost Your Development Experience with UI5 Tooling Extensions
 
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdfRevolutionizing Visual Effects Mastering AI Face Swaps.pdf
Revolutionizing Visual Effects Mastering AI Face Swaps.pdf
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Oracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptxOracle Database 19c New Features for DBAs and Developers.pptx
Oracle Database 19c New Features for DBAs and Developers.pptx
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise EditionWhy Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
Why Choose Odoo 17 Community & How it differs from Odoo 17 Enterprise Edition
 
What is Augmented Reality Image Tracking
What is Augmented Reality Image TrackingWhat is Augmented Reality Image Tracking
What is Augmented Reality Image Tracking
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 

CSharp Advanced L05-Attributes+Reflection

  • 1. Mohammad Shaker mohammadshaker.com @ZGTRShaker 2011, 2012, 2013, 2014 C# Advanced L05-Attributes, Conditional Methods and Reflection
  • 3. AttributesMuch of the C# language enables the programmer to specify declarative information about the entities defined in the program. For example, the accessibility of a method in a class is specified by decorating it with the method-modifiers public, protected, internal, and private. C# enables programmers to invent new kinds of declarative information, called attributes. Programmers can then attach attributes to various program entities, and retrieve attribute information in a run-time environment. For instance, a framework might define a HelpAttributeattribute that can be placed on certain program elements (such as classes and methods) to provide a mapping from those program elements to their documentation. (from MSDN)
  • 5. "DLL Hell“ problem •can be caused by one application overwritinga sharedlibrary of another application, usually with a different version. •Imagine you write an application with a shared library and then years later create a new application with an updated library. •In order not to break old programs, what do you do with the new library? You give it a different name, store it in a different location, or overwrite the old ones?
  • 6. "DLL Hell“ problem •can be caused by one application overwritinga sharedlibrary of another application, usually with a different version. •Imagine you write an application with a shared library and then years later create a new application with an updated library. •In order not to break old programs, what do you do with the new library? You give it a different name, store it in a different location, or overwrite the old ones?
  • 8. Assemblies •What’s an assembly? –An assembly is a file that is automatically generated by the compiler upon successful compilation of every.NET application. It can be either a Dynamic Link Library or an executable file. It is generated only once for an application and upon each subsequent compilation the assembly gets updated. –contains the intermediate code, resources, and the metadata for itself. –We can have a look inside the assembly using the ildasm(Intermediate Language Disassembler) tool that comes as part of Visual Studio. –To access it you need to open the Visual Studio Command Prompt and type ildasm.exe. This will launch a Windows application that you can use to explore any.Netapplication.
  • 9. Attributes and Reflection •Attributes –Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties, and so forth). –Once associated with a program entity, the attribute can be queried at run time and used in any number of ways.
  • 10. Attributes and Reflection •Example usage of attributes includes: –Associating help documentation with program entities (through aHelpattribute). –Associating value editors to a specific type in a GUI framework (through aValueEditorattribute).
  • 11. Example at the start!
  • 12. Example at the start! If you understand this, it’s over
  • 13. Example at the start enumCarColour { [Description("Ice Cream White")] White, [Description("Carbon Black")] Black, [Description("Sterling Silver")] Silver, Red }
  • 14. Example at the start enumCarColour { [Description("Ice Cream White")] White, [Description("Carbon Black")] Black, [Description("Sterling Silver")] Silver, Red } Attributes
  • 15. Example at the start public static class EnumExtensions { public static string Description(this EnumenumValue) { varenumType= enumValue.GetType(); varfield = enumType.GetField(enumValue.ToString()); varattributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); return ((DescriptionAttribute)attributes[0]).Description; } } enumCarColour { [Description("Ice Cream White")] White, [Description("Carbon Black")] Black, [Description("Sterling Silver")] Silver, Red }
  • 16. Example at the start public static class EnumExtensions { public static string Description(this EnumenumValue) { varenumType= enumValue.GetType(); varfield = enumType.GetField(enumValue.ToString()); varattributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); return ((DescriptionAttribute)attributes[0]).Description; } } enumCarColour { [Description("Ice Cream White")] White, [Description("Carbon Black")] Black, [Description("Sterling Silver")] Silver, Red } Extension Method
  • 17. Example at the start public static class EnumExtensions { public static string Description(this EnumenumValue) { varenumType= enumValue.GetType(); varfield = enumType.GetField(enumValue.ToString()); varattributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); return ((DescriptionAttribute)attributes[0]).Description; } } enumCarColour { [Description("Ice Cream White")] White, [Description("Carbon Black")] Black, [Description("Sterling Silver")] Silver, Red } Reflection
  • 18. Example at the start public static class EnumExtensions { public static string Description(this EnumenumValue) { varenumType= enumValue.GetType(); varfield = enumType.GetField(enumValue.ToString()); varattributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); return ((DescriptionAttribute)attributes[0]).Description; } } enumCarColour { [Description("Ice Cream White")] White, [Description("Carbon Black")] Black, [Description("Sterling Silver")] Silver, Red }
  • 19. Example at the start public static class EnumExtensions { public static string Description(this EnumenumValue) { varenumType= enumValue.GetType(); varfield = enumType.GetField(enumValue.ToString()); varattributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); return ((DescriptionAttribute)attributes[0]).Description; } } enumCarColour { [Description("Ice Cream White")] White, [Description("Carbon Black")] Black, [Description("Sterling Silver")] Silver, Red }
  • 20. Example at the start public static class EnumExtensions { public static string Description(this EnumenumValue) { varenumType= enumValue.GetType(); varfield = enumType.GetField(enumValue.ToString()); varattributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); return ((DescriptionAttribute)attributes[0]).Description; } } for (CarColourcc = CarColour.White; cc <= CarColour.Red; cc++) { Console.WriteLine(cc.Description()); } enumCarColour { [Description("Ice Cream White")] White, [Description("Carbon Black")] Black, [Description("Sterling Silver")] Silver, Red }
  • 21. Example at the start public static class EnumExtensions { public static string Description(this EnumenumValue) { varenumType= enumValue.GetType(); varfield = enumType.GetField(enumValue.ToString()); varattributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); return ((DescriptionAttribute)attributes[0]).Description; } } for (CarColourcc = CarColour.White; cc <= CarColour.Red; cc++) { Console.WriteLine(cc.Description()); } enumCarColour { [Description("Ice Cream White")] White, [Description("Carbon Black")] Black, [Description("Sterling Silver")] Silver, Red } Ice Cream White Carbon Black Sterling Silver Red
  • 23. Attributes Basics •Attributes are generally applied physically in front of type and type member declarations. They're declared with square brackets, "[" and "]", surrounding the attribute such as the followingObsoleteAttributeattribute: •[ObsoleteAttribute] AttributeUsage Describes how a custom attribute class can be used. Conditional Marks a conditional method, a method whose execution depends on a specified preprocessing identifier. Obsolete Marks a program entity that should not be used.
  • 25. Pre-Defined Attributes usingSystem; classBasicAttributeDemo{ [Obsolete] publicvoidMyFirstdeprecatedMethod() { Console.WriteLine("Called MyFirstdeprecatedMethod()."); } [ObsoleteAttribute] publicvoidMySecondDeprecatedMethod() { Console.WriteLine("Called MySecondDeprecatedMethod()."); } [Obsolete("You shouldn't use this method anymore.")] publicvoidMyThirdDeprecatedMethod() { Console.WriteLine("Called MyThirdDeprecatedMethod()."); }
  • 26. Pre-Defined Attributes usingSystem; classBasicAttributeDemo{ [Obsolete] publicvoidMyFirstdeprecatedMethod() { Console.WriteLine("Called MyFirstdeprecatedMethod()."); } [ObsoleteAttribute] publicvoidMySecondDeprecatedMethod() { Console.WriteLine("Called MySecondDeprecatedMethod()."); } [Obsolete("You shouldn't use this method anymore.")] publicvoidMyThirdDeprecatedMethod() { Console.WriteLine("Called MyThirdDeprecatedMethod()."); }
  • 27. Pre-Defined Attributes usingSystem; classBasicAttributeDemo{ [Obsolete] publicvoidMyFirstdeprecatedMethod() { Console.WriteLine("Called MyFirstdeprecatedMethod()."); } [ObsoleteAttribute] publicvoidMySecondDeprecatedMethod() { Console.WriteLine("Called MySecondDeprecatedMethod()."); } [Obsolete("You shouldn't use this method anymore.")] publicvoidMyThirdDeprecatedMethod() { Console.WriteLine("Called MyThirdDeprecatedMethod()."); }
  • 28. Pre-Defined Attributes usingSystem; classBasicAttributeDemo{ [Obsolete] publicvoidMyFirstdeprecatedMethod() { Console.WriteLine("Called MyFirstdeprecatedMethod()."); } [ObsoleteAttribute] publicvoidMySecondDeprecatedMethod() { Console.WriteLine("Called MySecondDeprecatedMethod()."); } [Obsolete("You shouldn't use this method anymore.")] publicvoidMyThirdDeprecatedMethod() { Console.WriteLine("Called MyThirdDeprecatedMethod()."); }
  • 29. Pre-Defined Attributes // make the program thread safe for COM[STAThread] staticvoidMain(string[] args) { BasicAttributeDemoattrDemo=newBasicAttributeDemo(); attrDemo.MyFirstdeprecatedMethod(); attrDemo.MySecondDeprecatedMethod(); attrDemo.MyThirdDeprecatedMethod(); } }
  • 30. Pre-Defined Attributes // make the program thread safe for COM[STAThread] staticvoidMain(string[] args) { BasicAttributeDemoattrDemo=newBasicAttributeDemo(); attrDemo.MyFirstdeprecatedMethod(); attrDemo.MySecondDeprecatedMethod(); attrDemo.MyThirdDeprecatedMethod(); } }
  • 32. AttributeUsageDescribes how a custom attribute class can be used. [AttributeUsage( validon, AllowMultiple=allowmultiple, Inherited=inherited )]
  • 33. User-Defined Attributes [Author("H. Ackerman", version = 1.1)] classSampleClass
  • 34. User-Defined Attributes [Author("H. Ackerman", version = 1.1)] classSampleClass Author anonymousAuthorObject= newAuthor("H. Ackerman"); anonymousAuthorObject.version= 1.1;
  • 35. User-Defined Attributes [Author("H. Ackerman", version = 1.1)] classSampleClass Author anonymousAuthorObject= newAuthor("H. Ackerman"); anonymousAuthorObject.version= 1.1; conceptually equivalent
  • 37. Conditional Methodsallow developers to create methods whose calls can be placed in the code and then either included or omitted during compilation based on a preprocessing symbol.
  • 38. Conditional Methods •TheConditional attribute takes one parameter —the preprocessing identifier that controls whether the method call is included when clients are compiled. If the preprocessing identifier is defined, the method is called; otherwise, the call is never inserted in the client's code. using System; using System.Diagnostics; namespace TraceFunctions { public class Trace { [Conditional("DEBUG")] public static void Message(string traceMessage) { Console.WriteLine("[TRACE] -" + traceMessage); } } }
  • 40. [Serializable] Says that the object is Serializable
  • 41. [Serializable] Says that the object is SerializableSo you can Stream it and save the object into, like, a file!
  • 43. ReflectionAsk the object itself about itself
  • 44. Types
  • 45. Types and Reflection •Reflection –Provides objects (of typeType) that encapsulate assemblies, modules and types. –You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. –If you are using attributes in your code, Reflection enables you to access them.
  • 46. Types and Reflection •Reflection is useful in the following situations: –When you need to access attributes in your program's metadata. •“Accessing Attributes With Reflection” –For examining and instantiating types in an assembly. –For building new types at runtime. Use classes inSystem.Reflection.Emit –For performing late binding, accessing methods on types created at run time.
  • 47. Types and Reflection •Reflection is useful in the following situations: –When you need to access attributes in your program's metadata. •“Accessing Attributes With Reflection” –For examining and instantiating types in an assembly. –For building new types at runtime. Use classes inSystem.Reflection.Emit –For performing late binding, accessing methods on types created at run time.
  • 49. System.Typeclass •TheSystem.Typeclass is central to reflection. •The common language runtime creates theTypefor a loaded type when reflection requests it. You can use aTypeobject's methods, fields, properties, and nested classes to find out everything about that type.
  • 50. System.Typeclass •Simple example of Reflection using the static methodGetType-inherited by all types from theObjectbase class -to obtain the type of a variable: // Using GetTypeto obtain type information: inti=42; System.Typetype=i.GetType(); System.Console.WriteLine(type);
  • 51. System.Typeclass •Simple example of Reflection using the static methodGetType-inherited by all types from theObjectbase class -to obtain the type of a variable: // Using GetTypeto obtain type information: inti=42; System.Typetype=i.GetType(); System.Console.WriteLine(type); System.Int32
  • 52. Types and Reflection •Identifying all Types that Implement an Interface (http://www.blackwasp.co.uk/) public interface IParent{ } public class Parent { } public class Child1 : Parent { } public class Child2 : Parent { } public class Grandchild11 : Child1 { } public class Grandchild12 : Child1 { } public class Grandchild21 : Child2 { } public class Grandchild22 : Child2 { } public class NotAChild{ } public class NotAGrandchild: NotAChild{ } Type parentType= typeof(IParent); Assembly assembly= Assembly.GetExecutingAssembly(); Type[] types = assembly.GetTypes();
  • 53. Types and Reflection •Identifying all Types that Implement an Interface public interface IParent{ } public class Parent { } public class Child1 : Parent { } public class Child2 : Parent { } public class Grandchild11 : Child1 { } public class Grandchild12 : Child1 { } public class Grandchild21 : Child2 { } public class Grandchild22 : Child2 { } public class NotAChild{ } public class NotAGrandchild: NotAChild{ } IEnumerable<Type> imp = types.Where(t => t.GetInterfaces().Contains(interfaceType)); foreach(Type typein imp) { Console.WriteLine(type.Name); } /* OUTPUT Parent Child1 Child2 Grandchild11 Grandchild12 Grandchild21 Grandchild22 */ Type parentType= typeof(IParent); Assembly assembly= Assembly.GetExecutingAssembly(); Type[] types = assembly.GetTypes();
  • 54. Types and Reflection •Identifying all Subclasses of a Class (http://www.blackwasp.co.uk/) public interface IParent{ } public class Parent { } public class Child1 : Parent { } public class Child2 : Parent { } public class Grandchild11 : Child1 { } public class Grandchild12 : Child1 { } public class Grandchild21 : Child2 { } public class Grandchild22 : Child2 { } public class NotAChild{ } public class NotAGrandchild: NotAChild{ } Type parentType= typeof(IParent); Assembly assembly= Assembly.GetExecutingAssembly(); Type[] types = assembly.GetTypes();
  • 55. Types and Reflection •Identifying all Subclasses of a Class public interface IParent{ } public class Parent { } public class Child1 : Parent { } public class Child2 : Parent { } public class Grandchild11 : Child1 { } public class Grandchild12 : Child1 { } public class Grandchild21 : Child2 { } public class Grandchild22 : Child2 { } public class NotAChild{ } public class NotAGrandchild: NotAChild{ } IEnumerable<Type> subclasses = types.Where(t => t.IsSubclassOf(parentType)); foreach(Type typein subclasses) { Console.WriteLine(type.Name); } /* OUTPUT Child1 Child2 Grandchild11 Grandchild12 Grandchild21 Grandchild22 */ Type parentType= typeof(IParent); Assembly assembly= Assembly.GetExecutingAssembly(); Type[] types = assembly.GetTypes();
  • 57. Types and Reflection // This program lists all the public constructors // of the System.Stringclass. usingSystem; usingSystem.Reflection; classListMembers { publicstaticvoidMain(String[] args) { Typet=typeof(System.String); Console.WriteLine("Listing all the public constructors of the {0} type", t); // Constructors. ConstructorInfo[] ci=t.GetConstructors(BindingFlags.Public|BindingFlags.Instance); Console.WriteLine("//Constructors"); PrintMembers(ci); } publicstaticvoidPrintMembers(MemberInfo[] ms) { foreach(MemberInfominms) { Console.WriteLine("{0}{1}", " ", m); } Console.WriteLine(); } }
  • 58. Types and Reflection // This program lists all the public constructors // of the System.Stringclass. usingSystem; usingSystem.Reflection; classListMembers { publicstaticvoidMain(String[] args) { Typet=typeof(System.String); Console.WriteLine("Listing all the public constructors of the {0} type", t); // Constructors. ConstructorInfo[] ci=t.GetConstructors(BindingFlags.Public|BindingFlags.Instance); Console.WriteLine("//Constructors"); PrintMembers(ci); } publicstaticvoidPrintMembers(MemberInfo[] ms) { foreach(MemberInfominms) { Console.WriteLine("{0}{1}", " ", m); } Console.WriteLine(); } } Listing all the public constructors of the System.Stringtype //Constructors Void.ctor(Char*) Void.ctor(Char*, Int32, Int32) Void.ctor(SByte*) Void.ctor(SByte*, Int32, Int32) Void.ctor(SByte*, Int32, Int32, System.Text.Encoding) Void.ctor(Char[], Int32, Int32) Void.ctor(Char[]) Void.ctor(Char, Int32) Press any key to continue...
  • 59. Invoking Overloaded Methods Using Reflectionhttp://www.blackwasp.co.uk/
  • 60. Invoking Overloaded Methods Using Reflection public class Test { public void ShowMessage() { Console.WriteLine("Hello, world"); } public void ShowMessage(string msg, inttimesToShow) { for (inti= 0; i< timesToShow; i++) { Console.WriteLine(msg); } } }
  • 61. Invoking Overloaded Methods Using Reflection public class Test { public void ShowMessage() { Console.WriteLine("Hello, world"); } public void ShowMessage(string msg, inttimesToShow) { for (inti= 0; i< timesToShow; i++) { Console.WriteLine(msg); } } } Test test= new Test(); Type type= test.GetType(); MethodInfomethod = type.GetMethod("ShowMessage", new Type[] { typeof(string), typeof(int) }); method.Invoke(test, new object[] { "Exterminate!", 3 });
  • 62. Invoking Overloaded Methods Using Reflection public class Test { public void ShowMessage() { Console.WriteLine("Hello, world"); } public void ShowMessage(string msg, inttimesToShow) { for (inti= 0; i< timesToShow; i++) { Console.WriteLine(msg); } } } Test test= new Test(); Type type= test.GetType(); MethodInfomethod = type.GetMethod("ShowMessage", new Type[] { typeof(string), typeof(int) }); method.Invoke(test, new object[] { "Exterminate!", 3 });
  • 63. Invoking Overloaded Methods Using Reflection public class Test { public void ShowMessage() { Console.WriteLine("Hello, world"); } public void ShowMessage(string msg, inttimesToShow) { for (inti= 0; i< timesToShow; i++) { Console.WriteLine(msg); } } } Test test= new Test(); Type type= test.GetType(); MethodInfomethod = type.GetMethod("ShowMessage", new Type[] { typeof(string), typeof(int) }); method.Invoke(test, new object[] { "Exterminate!", 3 }); Exterminate! Exterminate! Exterminate!
  • 65. Accessing Attributes Through ReflectionYou don’t have to read..
  • 66. Accessing Attributes Through Reflection class MainClass { public static void Main() { System.Reflection.MemberInfoinfo = typeof(MyClass); object[] attributes = info.GetCustomAttributes(true); for (inti = 0; i < attributes.Length; i++) { System.Console.WriteLine(attributes[i]); } } }
  • 67. Accessing Attributes Through Reflection classMainClass { publicstaticvoidMain() { System.Reflection.MemberInfoinfo=typeof(MyClass); object[] attributes=info.GetCustomAttributes(true); for(inti=0; i<attributes.Length; i++) { System.Console.WriteLine(attributes[i]); } } }
  • 68. Accessing Attributes Through Reflection •Let’s have the following giantexample! publicclassIsTestedAttribute: Attribute { publicoverridestringToString() { return"Is Tested"; } }
  • 69. Concept of Attributes [AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct)] publicclassAuthorAttribute: Attribute { publicAuthorAttribute(stringname) { this.name=name; this.version=0; } publicstringName { get { returnname; } } publicintVersion { get { returnversion; } set { version=value; } } publicoverridestringToString() { stringvalue="Author : "+Name; if(version!=0) { value+=" Version : "+Version.ToString(); } returnvalue; } privatestringname; privateintversion; }
  • 70. Concept of Attributes [AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct)] publicclassAuthorAttribute: Attribute { publicAuthorAttribute(stringname) { this.name=name; this.version=0; } publicstringName { get { returnname; } } publicintVersion { get { returnversion; } set { version=value; } } publicoverridestringToString() { stringvalue="Author : "+Name; if(version!=0) { value+=" Version : "+Version.ToString(); } returnvalue; } privatestringname; privateintversion; }
  • 71. Concept of Attributes [AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct)] publicclassAuthorAttribute: Attribute { publicAuthorAttribute(stringname) { this.name=name; this.version=0; } publicstringName { get { returnname; } } publicintVersion { get { returnversion; } set { version=value; } } publicoverridestringToString() { stringvalue="Author : "+Name; if(version!=0) { value+=" Version : "+Version.ToString(); } returnvalue; } privatestringname; privateintversion; }
  • 72. Concept of Attributes [AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct)] publicclassAuthorAttribute: Attribute { publicAuthorAttribute(stringname) { this.name=name; this.version=0; } publicstringName { get { returnname; } } publicintVersion { get { returnversion; } set { version=value; } } publicoverridestringToString() { stringvalue="Author : "+Name; if(version!=0) { value+=" Version : "+Version.ToString(); } returnvalue; } privatestringname; privateintversion; }
  • 73. Accessing Attributes Through Reflection [Author("Joe Programmer")] classAccount { // Attach the IsTestedAttributecustom attribute to this method. [IsTested] publicvoidAddOrder(OrderorderToAdd) { orders.Add(orderToAdd); } privateArrayListorders=newArrayList(); } [Author("Jane Programmer", Version=2), IsTested()] classOrder { // add stuff here... }
  • 74. Accessing Attributes Through Reflection [Author("Joe Programmer")] classAccount { // Attach the IsTestedAttributecustom attribute to this method. [IsTested] publicvoidAddOrder(OrderorderToAdd) { orders.Add(orderToAdd); } privateArrayListorders=newArrayList(); } [Author("Jane Programmer", Version=2), IsTested()] classOrder { // add stuff here... }
  • 75. Accessing Attributes Through Reflection [Author("Joe Programmer")] classAccount { // Attach the IsTestedAttributecustom attribute to this method. [IsTested] publicvoidAddOrder(OrderorderToAdd) { orders.Add(orderToAdd); } privateArrayListorders=newArrayList(); } [Author("Jane Programmer", Version=2), IsTested()] classOrder { // add stuff here... }
  • 76. Accessing Attributes Through Reflection classMainClass { privatestaticboolIsMemberTested(MemberInfomember) { foreach(objectattributeinmember.GetCustomAttributes(true)) { if(attributeisIsTestedAttribute) { returntrue; } } returnfalse; } privatestaticvoidDumpAttributes(MemberInfomember) { Console.WriteLine("Attributes for : "+member.Name); foreach(objectattributeinmember.GetCustomAttributes(true)) { Console.WriteLine(attribute); } }
  • 77. Concept of Attributes publicstaticvoidmain() { DumpAttributes(typeof(Account)); foreach(MethodInfomethodin(typeof(Account)).GetMethods()) { if(IsMemberTested(method)) { Console.WriteLine("Member {0} is tested!", method.Name); } else { Console.WriteLine("Member {0} is NOT tested!", method.Name); } } Console.WriteLine(); // display attributes for Order class DumpAttributes(typeof(Order)); // display attributes for methods on the Order class foreach(MethodInfomethodin(typeof(Order)).GetMethods()) { if(IsMemberTested(method)) { Console.WriteLine("Member {0} is tested!", method.Name); } else { Console.WriteLine("Member {0} is NOT tested!", method.Name); } } Console.WriteLine(); } }
  • 78. Concept of Attributes publicstaticvoidmain() { DumpAttributes(typeof(Account)); foreach(MethodInfomethodin(typeof(Account)).GetMethods()) { if(IsMemberTested(method)) { Console.WriteLine("Member {0} is tested!", method.Name); } else { Console.WriteLine("Member {0} is NOT tested!", method.Name); } } Console.WriteLine(); // display attributes for Order class DumpAttributes(typeof(Order)); // display attributes for methods on the Order class foreach(MethodInfomethodin(typeof(Order)).GetMethods()) { if(IsMemberTested(method)) { Console.WriteLine("Member {0} is tested!", method.Name); } else { Console.WriteLine("Member {0} is NOT tested!", method.Name); } } Console.WriteLine(); } }
  • 79. Concept of Attributes publicstaticvoidmain() { DumpAttributes(typeof(Account)); foreach(MethodInfomethod in (typeof(Account)).GetMethods()) { if (IsMemberTested(method)) { Console.WriteLine("Member {0} is tested!", method.Name); } else { Console.WriteLine("Member {0} is NOT tested!", method.Name); } } Console.WriteLine(); // display attributes for Order class DumpAttributes(typeof(Order)); // display attributes for methods on the Order class foreach(MethodInfomethod in (typeof(Order)).GetMethods()) { if (IsMemberTested(method)) { Console.WriteLine("Member {0} is tested!", method.Name); } else { Console.WriteLine("Member {0} is NOT tested!", method.Name); } } Console.WriteLine(); } }
  • 80. Accessing Attributes Through Reflection Attributes for : Account Author : Joe Programmer Member AddOrderis tested! Member ToStringis NOT tested! Member Equals is NOT tested! Member GetHashCodeis NOT tested! Member GetTypeis NOT tested! Attributes for : Order Author : Jane Programmer Version : 2 Is Tested Member ToStringis NOT tested! Member Equals is NOT tested! Member GetHashCodeis NOT tested! Member GetTypeis NOT tested! Press any key to continue...
  • 81. http://www.mohammadshaker.com mohammadshakergtr@gmail.com https://twitter.com/ZGTRShaker@ZGTRShakerhttps://de.linkedin.com/pub/mohammad-shaker/30/122/128/ http://www.slideshare.net/ZGTRZGTR https://www.goodreads.com/user/show/11193121-mohammad-shaker https://plus.google.com/u/0/+MohammadShaker/ https://www.youtube.com/channel/UCvJUfadMoEaZNWdagdMyCRA http://mohammadshakergtr.wordpress.com/