Dauris Little

  • About
  • Dauris’s Portfolio
  • Blogging Lyf
  • Contact

Did Someone Say Reflection C#

Did Someone Say Reflection C#

by Dauris / Friday, 13 March 2020 / Published in .NET & .NET Core, blog, C#, Programming Languages
.NET C#

Maybe you are new to the .Net lifestyle or maybe you are a veteran, either way, you ended up here to get a better understanding of what reflection is all about. To begin reflection is the process of describing various metadata of types, methods, and fields in code, that is literal Microsoft definition but no worries I will explain it. So before we dive into anything else you should already have an understanding of namespaces are and why we use them.

With reflection in C#, you can dynamically create an instance of a type and bing that type to an existing object. Moreover, you can get the type from an existing object and access its properties. When you use attributes in your code, reflection gives you access as it provides objects of the type that describe modules, assemblies, and types.

So in this article, I’ll discuss C# Reflection with various examples. Here we’ll learn the way of getting type information using different ways and use of properties and methods of C# Reflection type class.

Here’s a simple example of reflection using the static method GetType – inherited by all types from the Object base class – to obtain the type of a variable,

//using GetType to obtain type information
int a = 42;
System.Type type = a.GetType();
System.Console.WriteLine(type);
//the output will display as the following
//System.Int32

Defining Reflection in C#

To understand reflection, there are a few basics you should understand about modules, types, and members:

  • Assemblies contain modules
  • Modules contain types
  • Types contain members

You need to use Reflection when you want to inspect the contents of an assembly. For example, you can get all members of the object by typing “.” before an object when viewing your Visual Studio editor IntelliSense.

A program reflects on itself when it extracts metadata from its assemblies, then uses it to modify its behavior or inform the user. When you write a C# program that uses reflection, you can use either the TypeOf operator or the GetType() method to get the object’s type.

Examples of Reflection in C#

Implementing reflection in C# requires a two-step process. You first get the “type” object, then use the type to browse members such as “methods” and “properties”. This is how you would create instances of DateTime class from the system assembly:

//create instance of class DateTime
DateTime dt = (DateTime) Activator.CreateInstance(typeof(DateTime);
Namespace Test 
{
   public class YuGiOh
   {
      public YuGiOh() {...}
      public string name
      public static double Attack {get{...} set{...}}
      public static double Defense {get{...} set{...}}
      public static string Attribute() {...}
      public static string MonsterEffect() {...}
      public static int Stars () {get{...} set{...}}
      public static string CardType() {...}
   }
}

//dynamically load assembly file 
Assembly yugioh = Assembly.LoadFile(@"c:'Test.dll")

//get type of class YuGiOh from just loaded assembly
Type card = yugioh.GetType("Test.YuGiOh");

//create instance of class YuGiOh
object cardInstance = Activator.CreateInstance(card);

And access its members (the following examples illustrate getting values for the public double Number property):

//get info about property: public double Attack
PropertyInfo cardPropertyInfo = card.GetProperty("Attack"); 

//get the value of property: public double Attack
double value = (double)cardPropertyInfo.GetValue(cardInstance, null);

//set value of property: public double Attack
cardPropertyInfo.SetValue(cardInstance, 10.0, null);

Then, you

Understanding How Reflection Works

The main class for reflection is the System.Type class, which is an abstract class representing a type in the Common Type System. When you use this class, you can find the types used in a module and namespace and also determine if a given type is a reference or value type. You can parse the corresponding metadata tables to look through these items:

  • Fields
  • properties
  • Methods
  • Events 

Understanding How Reflection in C# Works

There are several uses including:

  1. Use Module to get all global and non-global methods defined in the module.
  2. Use MethodInfo to look at information such as parameters, name, return type, access modifiers, and implementation details.
  3. Use EventInfo to find out the event-handler data type, the name, declaring type and custom attributes.
  4. Use ConstructorInfo to get data on the parameters, access modifiers, and implementation details of a constructor.
  5. Use Assembly to load modules listed in the assembly manifest.
  6. Use PropertyInfo to get the declaring type, reflected type, data type, name and writable status of a property or to get and set property values.
  7. Use CustomAttributeData to find out information on custom attributes or to review attributes without having to create more instances.

Other uses for Reflection include constructing symbol tables, to determine which fields to persist and through serialization.

Tagged under: .NET, c-sharp, c#, reflection, Reflection in .NET

About Dauris

What you can read next

Shimmering in Android
javascript
The ($) and (_) within JavaScript
Did someone say Navigation to the rescue: Android Jetpack

Leave a Reply Cancel reply

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

Categories

Recent Posts

  • Did someone say Navigation to the rescue: Android Jetpack

    If you been around the block a few times with A...
  • Using Enum w/Swift

    understand enum is nothing fancy and all langua...
  • Shimmering in Android

    You may or may not  have been aware of certain ...
  • Android, SQLite & Kotlin

    The name of the database in Android is SQLite. ...
  • When over Switch in Kotlin

    Good afternoon Programming Community, I am glad...

© 2017. All rights reserved. Designed by Dauris Little

TOP
This site uses tracking cookies to personalize content and ads. AcceptLearn More