Get non-static method name inside static method - c#

I am trying to do something rather simple but not sure if there's any way around simply creating a dummy instance of my class.
I am trying to simply get the method name of a non-static method using some simple code:
static string GetMethodName(Func<string, int> function )
{
return function.Method.Name;
}
however I am trying to call this from MyStaticMethod like so and of course it is complaining:
private static void MyStaticMethod()
{
var a = GetMethodName(MyNonStaticMethod);
}
private int MyNonStaticMethod(string param1)
{
return 0;
}
Is there any way to accomplish this without creating a dummy instance of the containing class? obviously my case is more complex and I cannot simply make my non static method static (it requires an instance and has dependency bindings). Just wondering if this is possible as all I need is the name (so really don't need an instance). I am trying to get away from magic strings and want some compile time errors when things change.
edit: I've created a static helper class
i have a generic method:
public static string GetMemberName<T>(
Expression<Func<T, object>> expression)
{
if (expression == null)
{
throw new ArgumentNullException("expression");
}
return _GetMemberName(expression.Body);
}
private static string _GetMemberName(
Expression expression)
{
if (expression is MemberExpression)
{
var memberExpression =
(MemberExpression)expression;
return memberExpression.Member.Name;
}
if (expression is MethodCallExpression)
{
var methodCallExpression = (MethodCallExpression)expression;
return methodCallExpression.Method.Name;
}
if (expression is UnaryExpression)
{
var unaryExpression = (UnaryExpression)expression;
return GetMemberName(unaryExpression);
}
throw new ArgumentException("Unrecognized expression");
}

Of course you can do this. Use Expression<Func<YourInstanceClass, TReturn>> like this:
static string GetMethodName<TReturn>(Expression<Func<YourInstanceClass, TReturn>> function)
{
var call = function.Body as MethodCallExpression;
return call != null ? call.Method.Name : "not a single call expression";
}
now you can
var name = GetMethodName(a => a.MyNonStaticMethod("1"));
Console.WriteLine (name); //prints MyNonStaticMethod
where
public class YourInstanceClass
{
public int MyNonStaticMethod(string param1)
{
return 0;
}
}
I've made MyNonStaticMethod public, so that I can call it outside, but you can left it private and call it in static method inside a class

Related

Getting the callee's name of an extension method

I've built up a simple ArgumentValidator class in order to simplify argument preconditions in any given method. Most of them are null or bounds checks and it gets pretty tedious after a couple of
if (arg == null ) throw new ArgumentNullException(nameof(arg));
So I've come up with the following set up:
public static class ArgumentValidator
{
public interface IArgument<T>
{
string ParamName { get; }
T Value { get; }
}
private class Argument<T>: IArgument<T>
{
public Argument(T argument, string paramName)
{
ParamName = paramName;
Value = argument;
}
public string ParamName { get; }
public T Value { get; }
}
public static IArgument<T> Validate<T>(this T argument, string paramName = null)
{
return new Argument<T>(argument, paramName ?? string.Empty);
}
public static IArgument<T> IsNotNull<T>(this IArgument<T> o)
{
if (ReferenceEquals(o.Value, null))
throw new ArgumentNullException(o.ParamName);
return o;
}
public static IArgument<T> IsSmallerThan<T, Q>(this IArgument<T> o, Q upperBound) where T : IComparable<Q> { ... }
//etc.
}
And I can use it in the following way:
public Bar Foo(object flob)
{
flob.Validate(nameof(flob)).IsNotNull().IsSmallerThan(flob.MaxValue);
}
Ideally I'd love to get rid of nameof(flob) in the Validate call and ultimately get rid of Validate alltogether; the only purpose of Validate is to avoid having to pass nameof(...) on every check down the chain.
Is there a way to get the name flob inside the Validate() method?
Doing that with an extension method is not that easy. It is easier with a static method that takes an LINQ expression (derived from devdigital's answer here):
public static T Validate<T>(this Expression<Func<T>> argument)
{
var lambda = (LambdaExpression)argument;
MemberExpression memberExpression;
if (lambda.Body is UnaryExpression)
{
var unaryExpression = (UnaryExpression)lambda.Body;
memberExpression = (MemberExpression)unaryExpression.Operand;
}
else
{
memberExpression = (MemberExpression)lambda.Body;
}
string name = memberExpression.Member.Name;
Delegate d = lambda.Compile();
return (T)d.DynamicInvoke();
}
The name inside is the name of the property you put in the method:
MyMethods.Validate(() => o);
Since the Validate returns T, you can use that further on. This might not be as performing as you want it to be, but this is the only viable option.
It is possible to make this an extension method too, you have to create the expression yourself by hand:
Expression<Func<object>> f = () => o; // replace 'object' with your own type
f.Validate();

How to get the name of a property sent as a parameter using a lambda

I could have a method like this:
public void MyMethod<T, TResult>( string propertyName, ... ){
var name = propertyName;
return {property with correct name from some object that is of type TResult}
}
And call it like this:
MyMethod<SomeClass>("SomePropertyName");
To get hold of the propertyname inside the method. However, I do not like sending that propertyname in as a string in case SomeClass changes in the future, and the compiler cannot verify that the propertyName matches a property of type TResult either.
I would much rather call it like this:
MyMethod<SomeClass>(c => c.SomePropertyName);
But I am unsure how my method would look like then. I have tried variants of this:
public void MyMethod<T>( Func<T,TResult> property, ... ){
var name = {do some cleverness on property here to extract the actual name of the property inside the expression};
return {property with correct name from some object that is of type TResult}
}
Are there any good clean way to do this in C#?
You can't investigate Func<> delegates with much detail. You want to interrogate an Expression.. something like this (not tested.. but should be close):
public void MyMethod<T>(Expression<Func<T,TResult>> expr, ... ){
var expression = (MemberExpression)expr.Body;
var name = expression.Member.Name;
// .. the rest here using "name"
}
Usage is the same:
MyMethod<User>(u => u.UserId); // name will be "UserId"
This is how I do this for a RaisePropertyChanged method
internal static class PropertySupport
{
public static string ExtractPropertyName<T>(Expression<Func<T>> propertyExpression)
{
if (propertyExpression == null)
{
throw new ArgumentNullException("propertyExpression");
}
var memberExpression = propertyExpression.Body as MemberExpression;
if (memberExpression == null)
{
throw new ArgumentException("propertyExpression");
}
var property = memberExpression.Member as PropertyInfo;
if (property == null)
{
throw new ArgumentException("propertyExpression");
}
var getMethod = property.GetGetMethod(true);
if (getMethod.IsStatic)
{
throw new ArgumentException("propertyExpression");
}
return memberExpression.Member.Name;
}
}
and in the method using the PropertySupport :
protected virtual void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression)
{
var propertyName = PropertySupport.ExtractPropertyName(propertyExpression);
this.RaisePropertyChanged(propertyName);
}
I can use it simply with
RaisePropertyChanded<String>(() => this.MyString);
as you can see, the lambda is very simple.
Would [callermembername] work for you? You'd use it like:
public void MyMethod<T>([CallerMemberName]string caller = null){
//leave caller blank and it will put the name of the calling member in as a string
}
http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute(v=vs.110).aspx

How to pass objects properties into a generic function

I am trying to create a function that takes in a object property and returns back object property.
How to get the property values into this specific Function, so that this function only takes takes in the object's specific property and not the entire object?
class Program
{
public T MapFrom<T,V>(T SourceObject.property, V DestinationObject.Property)
//Not able to achieve this//
{
// Code to Map Property
}
// Here I want to specifically pass only one property of Object , not the entire one
ProgramClassObject.MapFrom<Details,Person>(Details.FirstName,Person.FName)
}
}
// Class Containing Property
class Details
{
public string FirstName { get; set;}
}
// Class Containing Property
class Person
{
public string FName { get; set;}
}
You can do it manually, or use some library (see comments, someone mentetioned about it).
If still want to implement yourself:
Prepare some useful Expression extensions:
public static B GetProperty<T, B>(this Expression<Func<T, B>> propertySelector, T target) where T : class
{
if (target == null)
{
throw new ArgumentNullException("target");
}
if (propertySelector == null)
{
throw new ArgumentNullException("propertySelector");
}
var memberExpression = propertySelector.Body as MemberExpression;
if (memberExpression == null)
{
throw new NotSupportedException("Only member expression is supported.");
}
var propertyInfo = memberExpression.Member as PropertyInfo;
if (propertyInfo == null)
{
throw new NotSupportedException("You can select property only. Currently, selected member is: " +
memberExpression.Member);
}
return (B)propertyInfo.GetValue(target);
}
public static void SetProperty<T, B>(this Expression<Func<T, B>> propertySelector, T target, B value)
{
SetObjectProperty(target, propertySelector, value);
}
public static void SetObjectProperty<T, B>(T target, Expression<Func<T, B>> propertySelector, object value)
{
if (target == null)
{
throw new ArgumentNullException("target");
}
if (propertySelector == null)
{
throw new ArgumentNullException("propertySelector");
}
var memberExpression = propertySelector.Body as MemberExpression;
if (memberExpression == null)
{
throw new NotSupportedException("Cannot recognize property.");
}
var propertyInfo = memberExpression.Member as PropertyInfo;
if (propertyInfo == null)
{
throw new NotSupportedException("You can select property only. Currently, selected member is: " + memberExpression.Member);
}
propertyInfo.SetValue(target, value);
}
MapFrom implementation:
public static void MapFrom<TObject, TTarget, TProp>(TObject source, TTarget dest,
Expression<Func<TObject, TProp>> sourceSelector, Expression<Func<TTarget, TProp>> targetSelector)
where TObject : class where TTarget : class
{
var sourceValue = sourceSelector.GetProperty(source);
targetSelector.SetProperty(dest, sourceValue);
}
Usage:
programClassObject.MapFrom(details, person, det => det.FirstName, per => per.FName);
It sounds like what you're looking for is an expression. That's how some libraries like Entity Framework effectively "parse" the code that they're passed.
First, you can get the PropertyInfo from an expression through a method such as this. I'm going to explain how to use this below, so bear with me.
public static PropertyInfo GetPropertyInfo<TIn, TOut>(Expression<Func<TIn, TOut>> PropertyExpression)
{
MemberExpression memberExpr;
switch (PropertyExpression.Body.NodeType)
{
case ExpressionType.MemberAccess:
memberExpr = (MemberExpression)PropertyExpression.Body;
break;
case ExpressionType.Convert:
memberExpr = (MemberExpression)((UnaryExpression)PropertyExpression.Body).Operand;
break;
default:
throw new NotSupportedException();
}
var property = (PropertyInfo)memberExpr.Member;
return property;
}
Then, the method will become something like this. I've taken the liberty of ensuring the datatypes to be the same here, although you could change TOut to object if you'd prefer. I did this based on your name of MapFrom, which leads me to believe the properties are meant to "communicate" directly.
public T MapFrom<T, V, TOut>(Expression<Func<T, TOut>> Source, Expression<Func<V, TOut>> Destination)
{
var sourceProperty = GetPropertyInfo<T, TOut>(Source);
var destinationProperty = GetPropertyInfo<V, TOut>(Destination);
// Use those
// They're PropertyInfo instances, so it should be pretty easy to handle them however you would have expected to.
}
Once you've got all that,
var ret = MapFrom<Person, Details, string>(c => c.FName, c => c.FirstName);
The signature there could be cleaned up through the use of a generically typed master class, since you wouldn't have to specify any type arguments, and the string would be inferred. In a real-world situation, that's likely what you'd want to do, particularly since you appear to be, again, mapping values.

Add intellisense when writing lambda's for an Action<dynamic>

This question is related to this other question.
I have the following method:
public static T GetNewData<T>(params Action<dynamic>[] actions) where T : class, new()
{
dynamic dynamicData = new DeepObject();
foreach (var action in actions)
{
action(dynamicData);
}
return Converter.Convert<T>(dynamicData);
}
The users of this method will include less technical people, even non-developers and as such the easier writing calls to this method is the better. My sticking point right now is that by using Action<dynamic> as the parameter type there is no intellisense provided to the user. In the context I know that the intellisense should be acting as if the dynamic was in fact T.
So is their a way I could either: Tell Visual Studio to use type T for the intellisense or change the parameter to be Action<T> and somehow programmatically change it to be Action<dynamic> or Action<DeepObject> so that the call to it will succeed?
EDIT: To clarify, the types that I am using for T are not of type DeepObject and they do not inherit any standard interface, the use of DeepObject is to allow setting up nested types without the user needing to explicitly instantiate at each level. This was the original usage before adding the dynamic and DeepObject code:
ExampleDataFactory.GetNewData<ServicesAndFeaturesInfo>(
x => x.Property1 = ExampleDataFactory.GetNewData<Property1Type>(),
x => x.Property1.Property2 = ExampleDataFactory.GetNewData<Property2Type>(),
x => x.Property1.Property2.Property3 = ExampleDataFactory.GetNewData<Property3Type>(),
x => x.Property1.Property2.Property3.Property4 = true);
Here is what it looks like now:
ExampleDataFactory.GetNewData<ServicesAndFeaturesInfo>(
x => x.Property1.Property2.Property3.Property4 = true);
EDIT: Here is the fully implemented solution based on nmclean's answer
public static DataBuilder<T> GetNewData<T>() where T : class, new()
{
return new DataBuilder<T>();
}
The DataBuilder Class:
public class DataBuilder<T>
{
public readonly T data;
public DataBuilder()
{
data = Activator.CreateInstance<T>();
}
public DataBuilder(T data)
{
this.data = data;
}
public DataBuilder<T> SetValue<T2>(Expression<Func<T, T2>> expression, T2 value)
{
var mExpr = GetMemberExpression(expression);
var obj = Recurse(mExpr);
var p = (PropertyInfo)mExpr.Member;
p.SetValue(obj, value);
return this;
}
public T Build()
{
return data;
}
public object Recurse(MemberExpression expr)
{
if (expr.Expression.Type != typeof(T))
{
var pExpr = GetMemberExpression(expr.Expression);
var parent = Recurse(pExpr);
var pInfo = (PropertyInfo) pExpr.Member;
var obj = pInfo.GetValue(parent);
if (obj == null)
{
obj = Activator.CreateInstance(pInfo.PropertyType);
pInfo.SetValue(parent, obj);
}
return obj;
}
return data;
}
private static MemberExpression GetMemberExpression(Expression expr)
{
var member = expr as MemberExpression;
var unary = expr as UnaryExpression;
return member ?? (unary != null ? unary.Operand as MemberExpression : null);
}
private static MemberExpression GetMemberExpression<T2>(Expression<Func<T, T2>> expr)
{
return GetMemberExpression(expr.Body);
}
}
The Usage:
ExampleDataFactory.GetNewData<ServicesAndFeaturesInfo>()
.SetValue(x=> x.Property1.EnumProperty, EnumType.Own)
.SetValue(x=> x.Property2.Property3.Property4.BoolProperty, true)
.Build();
Do not use Action<dynamic>, use Action<T>with method's constraint where T:DeepObject. Users will get intellisence and ability to use strongly typed objects:
public static DeepObject GetNewData<T>(params Action<T>[] actions)
where T : DeepObject, //restrict user only inheritors of DeepObject
new() //and require constructor
{
var data = new T();
foreach (var action in actions)
{
action(data);
}
return data;
}
Does the user need to access unknown properties or add new ones? If not, using dynamic objects seems like a step backwards. If your desired syntax does compile as an Action<T>, I think you should just declare it that way and then go with your first instinct of using the LINQ Expression API to decide how to interpret the code.
Unfortunately, although statements, such as an assignment, are part of the API, C# doesn't support converting them to expression trees. This is not allowed:
public static T GetNewData<T>(params Expression<Action<T>>[] actions)
where T : class, new() {
...
}
...
ExampleDataFactory.GetNewData<ServicesAndFeaturesInfo>(
x => x.Property1.Property2.Property3.Property4 = true);
Only single-line expressions that would have a return a value are supported. So I think the best you could do is something like this:
public class Assignment<T> {
public readonly Expression Expression;
public readonly object Value;
public Assignment(Expression<Func<T, object>> expression, object value) {
Expression = expression;
Value = value;
}
}
...
public static T GetNewData<T>(params Assignment<T>[] assignments)
where T : class, new() {
var data = Activator.CreateInstance<T>();
foreach (var assignment in assignments) {
// todo:
// - pull property names from assignment.Expression
// - initialize nested properties / assign to assignment.Value
}
return data;
}
...
ExampleDataFactory.GetNewData<ServicesAndFeaturesInfo>(
new Assignment<ServicesAndFeaturesInfo>(
x => x.Property1.Property2.Property3.Property4, true));
Getting the property names from an expression tree of chained property access is not too complicated. Here is one implementation.
Of course, the new Assignment<ServicesAndFeaturesInfo>(...) is ugly and repetitive, so maybe it could be restructured to something like this:
var newData = ExampleDataFactory.NewData<ServicesAndFeaturesInfo>();
newData.Add(x => x.Property1.Property2.Property3.Property4, true);
newData.Add(...);
...
newData.Get();

Use type of this Type argument in extension method for TIn of a Func in the same method signature

I was pretty sure that this was possible, but for some reason, I can't seem to figure this out... I am trying to make an extension method off of Type, that will take in a Func to a property from that type, and extract a DefaultValue from the DefaultValueAttribute.
I can get it working, but only if I specify the type arguments for the GetDefaultValue function call. Here is my code as I have it currently:
Person entity:
public class Person
{
public string FirstName { get; set; }
[DefaultValue("1234")]
public string DOB { get; set; }
}
Calls to the method:
//Messing around in LinqPad - .Dump() is LinqPad method
//Works
//typeof(Person).GetDefaultValue<Person, string>(x=>x.DOB).Dump();
//Trying to get to work
//Can't figure out how to get it to infer that TIn is of the Type type.....
typeof(Person).GetDefaultValue(x=> x.DOB).Dump();
This is where the method calls are going to... I am just trying to figure out the means right now before I incorporate into my actual program... Error checking will come into play once I've figured out either how to do it, or to give up b/c it can't be done...
public static class Extensions
{
// Works
// public static TProperty GetDefaultValue<TModel, TProperty>(this Type type, Expression<Func<TModel, TProperty>> exp)
// {
// var property = typeof(TModel).GetProperties().ToList().Single(p => p.Name == GetFullPropertyName(exp));
// var defaultValue = (DefaultValueAttribute)property.GetCustomAttributes(typeof(DefaultValueAttribute), false).FirstOrDefault();
// return (TProperty)defaultValue.Value;
// }
//trying to get to work
//I know that I can't do the following, but it is basically what I am trying to do... I think!
public static TProperty GetDefaultValue<TProperty>(this Type type, Expression<Func<typeof(type), TProperty>> exp)
{
var property = type.GetProperties().ToList().Single(p => p.Name == GetFullPropertyName(exp));
var defaultValue = (DefaultValueAttribute)property.GetCustomAttributes(typeof(DefaultValueAttribute), false).FirstOrDefault();
return (TProperty)defaultValue.Value;
}
//GetFullPropertyName c/o: http://stackoverflow.com/users/105570/
//ref: http://stackoverflow.com/questions/2789504/
public static string GetFullPropertyName<TModel, TProperty>(Expression<Func<TModel, TProperty>> exp)
{
MemberExpression memberExp;
if (!TryFindMemberExpression(exp.Body, out memberExp))
return String.Empty;
var memberNames = new Stack<string>();
do
memberNames.Push(memberExp.Member.Name);
while (TryFindMemberExpression(memberExp.Expression, out memberExp));
return String.Join(".", memberNames.ToArray());
}
private static bool TryFindMemberExpression(Expression exp, out MemberExpression memberExp)
{
memberExp = exp as MemberExpression;
if (memberExp != null)
return true;
if (IsConversion(exp) && exp is UnaryExpression)
{
memberExp = ((UnaryExpression)exp).Operand as MemberExpression;
if (memberExp != null)
return true;
}
return false;
}
private static bool IsConversion(Expression exp)
{
return exp.NodeType == ExpressionType.Convert || exp.NodeType == ExpressionType.ConvertChecked;
}
}
Am I crazy, or is this actually possible? Thank you in advance for your help!
That's not how it works- typeof(Person) doesn't have a property called DOB, but a class whose type is Person does. What you want is to make your extension method generic:
public static TValue GetDefaultValue<TClass, TValue>(this TClass val, Expression<Func<TClass, TValue>> getter) {
var type = typeof(TClass);
var property = type.GetProperties().ToList().Single(p => p.Name == GetFullPropertyName(exp));
var defaultValue = (DefaultValueAttribute)property.GetCustomAttributes(typeof(DefaultValueAttribute), false).FirstOrDefault();
return (TProperty)defaultValue.Value;
}
and call it something like:
Person somePerson = GetMeAPerson();
somePerson.GetDefaultValue(p=>p.DOB);
Note that I have not tested the above, but I've seen similar code in the past that worked. That said, I suspect that what you were originally trying to do isn't very appealing this way because you need to make a Person instance first.
Another, possibly more appealing approach is to not make it an extension method at all:
public static TValue GetDefaultValue<TClass, TValue>(Expression<Func<TClass, TValue>> getter) {
var type = typeof(TClass);
var property = type.GetProperties().ToList().Single(p => p.Name == GetFullPropertyName(exp));
var defaultValue = (DefaultValueAttribute)property.GetCustomAttributes(typeof(DefaultValueAttribute), false).FirstOrDefault();
return (TProperty)defaultValue.Value;
}
Then you can call it without an instance, but the inference isn't as nice):
var defaultValue = GetDefaultValue<Person, DateTime>(p => p.DOB);

Categories