Reflection Made Easy (In C#)

visual-studio-asp-net

Hi there! In this post, I will teach you the correct usage of the reflection with the newest ASP Core library, .NET 5. I have found many resources but I couldn’t find any web-site which takes you from 0 to 1.

Loading Assembly In Correct Way

I experienced too many issues when calling an assembly directly with a file path. Rather than this, I chose to use Byte notations.

string fileToLoad = AppContext.BaseDirectory + dllName + ".dll";
byte[] data = System.IO.File.ReadAllBytes(fileToLoad);
Assembly assembly = Assembly.Load((data));

Say, there is a variable named dllName. You can now dynamically reach a dll and its content. Not sure why direct path didn’t work but I was well satisfied with the result now.

Type typ in assembly.GetTypes()

You can iterate in each type of the respective dll now. In what aspect, does it work? Now, you can compare your types with other types. Sometimes, only one type you will need.

(typ, typeof(IMyLibrary))

Think there is a function on the left side that compares the types, for now, it is not the content. When your typ is equal to IMyLibrary, it enters into the condition. I mean the if condition. Let’s implement this code:

private bool TypeComparer(Type objectType, Type moduleInterface)
{
	Type multi = objectType.GetInterface("IMultiplier");
	if (multi == null)
		return false;
	if (multi.Name == moduleInterface.Name)
		return true;
	else
		return TypeComparer(objectType.BaseType, moduleInterface);
}

The parameter objectType is your base type so the ultimate code is:

if (TypeComparer(myType, typeof(IMultiplier)))

How to Get Properties and Their Names?

The code which is depicted below is the right solution towards your necessity.

PropertyInfo[] propInfos  = typeof(MyLibClass).GetProperties();

You see you can loop inside propInfos. Call the “Name” function afterward to reach out the name of the respective property. To get the value I use a beneficial resource from the internet. It was answered on Stackoverflow.

How to Get Properties and Their Values?

string abc= (string) GetPropertyValue(GetPropertyValue(model, assemblyInstance.Name), "ValueString");

ValueString is the property name, this way you can get its value. See, there is a nested class there.

This way you can get value of the property, I will introduce GetPropertyValue below.

public static object GetPropertyValue(object src, string propertyName)
{
         PropertyInfo property = src.GetType().GetProperty(propertyName);
         return property.GetValue(src, null);
}

Stay tuned.