Member-only story
10 Mind-Bending C# Hacks
.NET snippets and features not many know about.
Hey there, fellow coders!
I like to call these neat tricks ‘hacks’, not because they’re shortcuts or cheats, but because they’re clever, underused features in C# that offer some really creative solutions.
These ‘hacks’ showcase the versatility and depth of C# in ways you might not have explored before.
They’re all about thinking outside the box and using the language in inventive ways that go beyond the everyday code. Let’s dive in!
1. Reflection Emit for Dynamic Type Creation
Need to create a new type during runtime? Reflection Emit can do that. It’s a bit tricky, but once you get the hang of it, you’ll be able to create types dynamically whenever you need them.
var assemblyName = new AssemblyName("DynamicAssembly");
var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
var moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
var typeBuilder = moduleBuilder.DefineType("MyDynamicType", TypeAttributes.Public);
var dynamicType = typeBuilder.CreateType();
// Now you have a brand new type to play with!