I would like to imitate the F # keyword with a key (which can be used in entries) in C #.
Now, when I create a new immutable class, I just manually add some custom c methods, for example:
public class MyClass { public readonly string Name; public readonly string Description; public MyClass(string name, string description) { this.Name = name; this.Description = description; }
For my personal C # development, I tried to create a generic method for this (in an ideal world, I would use F #). The "best" I did was something like:
public static class MyExtensions { public static TSource With<TSource, TField>( this TSource obj, string fieldName, TField value) where TSource : class {
This works, but I'm not completely satisfied, because I am losing compile-time errors using a string parameter (so far I don't care about performance issues).
I would really like to write something like the code below, where I will replace the string parameter with the "projection" lambda:
var myClass1 = new MyClass("name", "desc"); var myClass2 = myClass1.With(obj => obj.Name, "newName");
My extension method would look something like this:
public static TSource With<TSource, TField>( this TSource obj, Expression<Func<TSource, TField>> projection, TField value) where TSource : class {
So here are my questions:
- Is it possible to use reflection of the projection result and get the field name from it?
- Has anyone else already made a reliable c method in C #?
immutability reflection c # lambda
Emmanuel horrent
source share