Did Someone Say Reflection 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:
- Use Module to get all global and non-global methods defined in the module.
- Use MethodInfo to look at information such as parameters, name, return type, access modifiers, and implementation details.
- Use EventInfo to find out the event-handler data type, the name, declaring type and custom attributes.
- Use ConstructorInfo to get data on the parameters, access modifiers, and implementation details of a constructor.
- Use Assembly to load modules listed in the assembly manifest.
- 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.
- 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.
- Published in .NET & .NET Core, blog, C#, Programming Languages
Java Or Kotlin Language: Deciding Which Option to Use for Android Development
If my math is not wrong Java has been around for over 20+ years now and has no intention of going away. It holds a supreme position in the list of most popular programming languages following the C and C++ =, setting the highest usability record with millions of developers and systems.
Random Fact:
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language back in 1991. Java has been the primary language for Android app development along with a few of its companions: Scala, Groovy and stepping up is Kotlin.
Kotlin Background
Let first you will need to understand what exactly is Kotlin so it is considered as statically typed programming language that runs on JVM(Java Virtual Machine) and JavaScript. It is developed by JetBrains and open-source community. The ‘Kotlin’ name came from Kotlin Island located near Saint Petersburg. It is supported by leading IDEs and compatible with Java 6 or Java 8. Kotlin is described as a general-purpose language and introduces functional features to support Java interoperability. The Kotlin project was born out of the aspiration for heightened productivity. The goal was to improve the coding experience in a way that was both practical and effective.
A central focus of Kotlin is to enable mixed-language projects. Kotlin also introduces improved syntax, as well as concise expressions and abstractions. Using Kotlin with Java reduces excessive boilerplate code, which is a huge win for Android developers. Kotlin came when Android development needed a more modern language to add to the qualities of java and aid in mobile development. This allows developers to not only easily update old Java apps to Kotlin, but also carry on their old work in Java to Kotlin.
Here’s a brief example Kotlin language
package hello
fun main() {
println("Hello World")
}
It’s that simple! Kotlin uses developer-friendly coding structures and norms that are easy-to-understand and use. When considering this example from the develops’ perspective, you will be able to understand why Kotlin is loved by developers around the world. It is concise, effective, and faster compared to Java.
Is Java Dead?
Based on the group that I program with it appears that Java is currently in the area with us developers. Java is a reputable programming language with vast open-source tools and libraries to help developers. With that said, no language is without fault and even Java is subject to complications that can make a developer’s job tedious. If anything the objective for Kotlin is to supposedly introduce solutions to the common programming headaches and improve the Java ecosystem as a whole.
Strict Trial And Error
Kotlin has some milage under itself and has become a more stable and congruous development option especially within the Android Studio IDE. Some developers seem to believe that Kotlin will oust Java for Android development in future years. Other reviewers seem to believe Kotlin and Java should be coexisting without one outweighing the other.
This is a quality Java is not known for; however, readability should always take priority over concision. Yes, the succinct nature of Kotlin simplifies a developer’s job and mitigates the risk for error, but Kotlin doesn’t practice concision for concision’s sake. So let’s take the example below and compare the difference in the languages presents.
public class MathLife {
public static double calculate () throws Exception {
switch(op) {
case "add":
return a + b;
case "subtract":
return a - b;
case "multiply":
return a * b;
case "divide":
return a / b;
default:
throw new Exception();
}
}
}
Above is a simple calculator function written in Java. For comparison, here is the same calculator in Kotlin:
fun calculate(a: Double, op: String, b: Double): Double {
when (op) {
"add" -> return a + b
"subtract" -> return a - b
"multiply" -> return a * b
"divide" -> return a / b
else -> throw Exception()
}
}
It may not seem like much, but the Kotlin version of this calculator is written in half the lines of code it took to program the function in Java. Brevity is a crucial factor in productivity. Writing large projects becomes easier when a developer is given more power for every line of code. A key observation here is Kotlin does not overlook comprehension for the sake of brevity. The syntax is concise, readable and still substantial.
The Winner: Java or Kotlin
In all fairness, chances are that you have been taught, learn and embraced Java. Switching to Kotlin at a time can be a bit of shock, so it is important to do this transition slowly to make sure you understand. having said that, Kotlin is the new official language and owing to its modern nature, it will become widely adopted in the future, so learning it and starting development with it right now would be a good idea. Understand java will continue to be a popular language for several years to come and isn’t likely to be entirely replaced. So take your time and make the switch gently.
At the end of the day, it’s all about what you feel comfortable with. As stated previously to be a true blood Androidian, you will need to have a working knowledge of the language Java. But if you already do have that then the Kotlin language of the future, so you might as well spend some time getting accustomed to it.
- Published in Android, Java, Kotlin, Language, Programming Languages


