How to invoke a property's method by property's name [duplicate] - c#

This question already has answers here:
Get property value from string using reflection
(24 answers)
Closed 8 years ago.
I'd like to call a property's method of an object through reflection. For instance,
var query = DataContext().SomeTable.Where(u => u.UserID.contains("P");
I've tried the following but no luck:
var query = DataContext().SomeTable.Where(u => u.GetType().GetProperty("UserID").Name.contains("P");
Which returns null. Please help.

You want GetValue, not Name
((string)u.GetType().GetProperty("UserID").GetValue(u) ?? "").Contains("P")
The use of the ?? operator here is just a safeguard to make sure that Contains doesn't throw an exception if UserID is null.

You have to get the value of u, then use ToString on it:
u.GetType().GetProperty("UserID").GetValue(u, null).ToString().Contains("P");
Of course it have be a little bit improved: check if GetValue do not return null etc.
Note: Remember that you can somewhere cache PropertyInfo obtained from u.GetType().GetProperty("UserID") so you won't have to call it every time.

Related

Alternative of "??" for non nullable types (e.g. when looking up dictionary keys) [duplicate]

This question already has answers here:
Is there an IDictionary implementation that, on missing key, returns the default value instead of throwing?
(17 answers)
Closed 2 years ago.
It's very convenient using inline sugar like that: obj?.func(); and obj ?? anotherObj
But I'm trying to find an alternative to the same approach in case I want to pull data from a dictionary without knowing whether the dictionary has the key I'm looking for or not.
Specifically I'd like to do something equivalent to:
someDictionary[someKey] ?? anotherValue such that, if key exists it would use the corresponding value in the dictionary and if not, it will use anotherValue. Obviously it's not possible to use as I wrote it here since it makes no sense, but the idea behind it is sound.
Is there a way to simplify it to be used inline, without making a separate check with if?
You can replace if checking with ternary operator
var value = someDictionary.TryGetValue(someKey, out var val) ? val : anotherValue;

Object field value when have property name as string [duplicate]

This question already has answers here:
Get property value from string using reflection
(24 answers)
Closed 3 years ago.
I have an object of a model class.
I have to return the field of the object whose name is provided as a string parameter.
Is there a better way than writing the multiple if conditions.
Thanks in advance.
You can use reflection to retrieve the property value by its name.
First, obtain the Type instace that represents your class. For example, use the typeof operator if the type is known at compile-time (including if it is a generic type parameter), or the GetType() method.
Then, you can use GetProperty to retrieve a property with a given name. (Note that there are several overloads of that method that you may need in more complex cases, such as explicit interface implementations.)
The GetProperty method will return a PropertyInfo instance, by means of which you can retrieve the value.
For example:
object propertyValue = myObject.GetType().GetProperty("SomeProperty").GetValue(myObject);

Null behaviour as in t-sql [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C# if-null-then-null expression
What I miss in C# is the treatment of null references like in sql server:
var a = SomeObject.Property1.Property2.Property3.Property4
If any of properties is null then I get NullReferenceException. Sometimes it would be more convenient if a would be set to null with no error and I could simply check for this.
Similarly,
var a = SomeList.FirstOrDefault(...).Select(...)
this would also throw exception if sequence would contain no elements rather then setting a to null.
So my question: is there short and nice way (using extensions maybe?) to implement sql-like behaviour in these scenarios?
This would only work with static properties, since an uninstantiated object is null. There would be no way doing this with extension methods either, as they take as their first parameter an instance of the object they are extending.
An ugly way of doing this ...
var a;
try {
a = SomeObject.Property1.Property2.Property3.Property4;
} catch (NullReferenceException) { }

How to get parameter value from StackTrace [duplicate]

This question already has answers here:
Is it possible to get parameters' values for each frame in call stack in .NET
(2 answers)
Closed 10 years ago.
From within a method call I need to "jump" three layers up the stack and retrieve the type and value of the parameters passed to that method.
Getting the parameter type is easy but I couldn't find a way to get the value passed to a certain method on the stack.
var st = new StackTrace();
var frames = st.GetFrames();
var methodParameters = frame[2].GetMethod().GetParameters;
// get each parameter value
Note: using StackTraceis not mandatory.
Is there a wayto find a value of a parameter passed to a method during runtime?
I do not think there is a method unless you develop your own system for storing the values.
The reflection namespace represents static data about an assembly, and you would need to retrieve values at runtime.
I found PostSharp mentioned in MSDN forums, but I have never tried it.

Getting the name of the parameter passed into a method [duplicate]

This question already has answers here:
How can I get the name of a variable passed into a function?
(23 answers)
Closed 9 years ago.
Duplicate:
Determine the name of the variable used as a parameter to a method
Is there any way to retrieve the name of a parameter that was passed into a method e.g.
int someParameter = 1;
Method(someParameter);
public void Method(int parameter)
{
// I want the name of 'parameter' which will be 'someParameter'.
}
No. It's only the value which is passed in as the argument. All the method gets is the integer. The fact that the expression happened to be just evaluating a variable is unknown as far as your method is concerned.
No, there is no way.
This will be followed by a bunch of people showing weird lambda expression ways to change the call site and kinda get the name, but the short answer is no.
The only way perhaps will be with annotations with run-time retention. But then, it will be the name of the annotation, not of the parameter itself. A parameter name is just a syntactic artifact of the language. It does not get carried over to the compiled result.

Categories

Resources