As you may know, Microsoft is getting into the open source community with the ASP.NET and DNX with the mono project.
The .NET Execution Environment (DNX) is a software development kit which allows you to run .NET applications on Windows, Mac, and Linux using different frameworks such as .NET framework, .NET Core, and Mono. However, everything are not roses. There are many incomplete libraries, incompatibilities, lack of documentation, and most of the examples such as doing SQL or SOAP do not work depending on which the library targets you are planning to code for. Therefore, I decided to test the basics on all the library targets. I am starting with DNX451.

Reflection seems to be working fine in DNX451 with C#. Below is a code example for those who wish to play with it.

ReflectionExample.cs

using System;
using System.Linq;
using System.Reflection;

namespace ConsoleApp1 {

	public class ReflectionExample {

		public ReflectionExample() {
			
			Console.WriteLine("ReflectionExample()");
			
			// Option 1
			Assembly assm = typeof(ReflectionExample).Assembly;
			Console.WriteLine("Assembly: {0}", assm);
			Console.WriteLine("Assembly Full Name: {0}", assm.FullName);
					
			// Option 2
			var asm = Assembly.GetExecutingAssembly();
			Console.WriteLine("Assembly Full Name: {0}", asm.FullName);
			
			// Getting info
			var asmTypes = asm.GetTypes();
			foreach (var type in asmTypes){
				Console.WriteLine("\tType: " + type.Name);
				
				var properties = type.GetProperties();
				foreach (var prop in properties){
					Console.WriteLine("\t\tProperty: " + prop.Name + " [Type: " + prop.PropertyType + "]");
				}
				
				var fields = type.GetFields();
				foreach (var f in fields){
					Console.WriteLine("\t\tField: " + f.Name);
				}
				
				var methods = type.GetMethods();
				foreach (var m in methods){
					Console.WriteLine("\t\tMethod: "+ m.Name);
				}
				
			}
			
			// Accessing to properties and methods
			var rs = new ReflectionSample() { Name = "Alejandro", Age = 35 };
			var rsType = typeof(ReflectionSample);

			var nameProperty = rsType.GetProperty("Name");
			Console.WriteLine("Property: " + nameProperty.GetValue(rs));

			var ms = rsType.GetMethod("MethodSample");
			ms.Invoke(rs, null);
					
			Console.WriteLine("Methods:");
			MethodInfo[] methodInfos = rsType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
			Console.WriteLine("-> Number of methods: {0}", methodInfos.Length);
			foreach (MethodInfo mi in methodInfos){
				Console.WriteLine("\t-> Name: {0}", mi.Name);
				Console.WriteLine("\t - Number of parameters: {0}", mi.GetParameters().Length);
				if (mi.GetParameters().Length < 1){
					mi.Invoke(rs, null);
				}
				
			}	
			
			// Accessing attributes
			var types = asm.GetTypes().Where(t => t.GetCustomAttributes<ThisClassAttribute>().Count() > 0);
			foreach(var type in types){
				Console.WriteLine("\nClass with ThisClassAttribute: {0}", type.Name);
				
				var methods = type.GetMethods().Where(m => m.GetCustomAttributes<ThisMethodAttribute>().Count() > 0);
				foreach(var method in methods){
					Console.WriteLine("\t Method with ThisMethodAttribute: {0}", method.Name);
				}
			}		
		
		}
		
		[ThisClass]
		public class ReflectionSample{
			
			public string Name { get; set; }
			
			public int Age;
			
			[ThisMethod]
			public void MethodSample(){
				Console.WriteLine("MethodSample()\n\tRun...");
			}
			
			public void MethodSample2(){
				Console.WriteLine("MethodSample2()\n\tRun...");
			}
		}
		
		[AttributeUsage(AttributeTargets.Class)]
		public class ThisClassAttribute : Attribute { }
		
		[AttributeUsage(AttributeTargets.Method)]
		public class ThisMethodAttribute : Attribute { }
		
	}	
		
}

Since the output may varied depending on all the classes you may have in your project, I decided to not include to not include it]

 

Cite this article as: Alejandro G. Carlstein Ramos Mejia, "DNX: C#: Reflection," in Alejandro G. Carlstein Ramos Mejia Blog, August 31, 2015, http://blog.acarlstein.com/?p=3155.

© 2015, Alejandro G. Carlstein Ramos Mejia. All rights reserved.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

*

Click to Insert Smiley

SmileBig SmileGrinLaughFrownBig FrownCryNeutralWinkKissRazzChicCoolAngryReally AngryConfusedQuestionThinkingPainShockYesNoLOLSillyBeautyLashesCuteShyBlushKissedIn LoveDroolGiggleSnickerHeh!SmirkWiltWeepIDKStruggleSide FrownDazedHypnotizedSweatEek!Roll EyesSarcasmDisdainSmugMoney MouthFoot in MouthShut MouthQuietShameBeat UpMeanEvil GrinGrit TeethShoutPissed OffReally PissedMad RazzDrunken RazzSickYawnSleepyDanceClapJumpHandshakeHigh FiveHug LeftHug RightKiss BlowKissingByeGo AwayCall MeOn the PhoneSecretMeetingWavingStopTime OutTalk to the HandLoserLyingDOH!Fingers CrossedWaitingSuspenseTremblePrayWorshipStarvingEatVictoryCurseAlienAngelClownCowboyCyclopsDevilDoctorFemale FighterMale FighterMohawkMusicNerdPartyPirateSkywalkerSnowmanSoldierVampireZombie KillerGhostSkeletonBunnyCatCat 2ChickChickenChicken 2CowCow 2DogDog 2DuckGoatHippoKoalaLionMonkeyMonkey 2MousePandaPigPig 2SheepSheep 2ReindeerSnailTigerTurtleBeerDrinkLiquorCoffeeCakePizzaWatermelonBowlPlateCanFemaleMaleHeartBroken HeartRoseDead RosePeaceYin YangUS FlagMoonStarSunCloudyRainThunderUmbrellaRainbowMusic NoteAirplaneCarIslandAnnouncebrbMailCellPhoneCameraFilmTVClockLampSearchCoinsComputerConsolePresentSoccerCloverPumpkinBombHammerKnifeHandcuffsPillPoopCigarette