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

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);

Related

Generic method return dynamic for unknown reason [duplicate]

This question already has answers here:
Passing dynamic object to C# method changes return type
(2 answers)
Closed 4 years ago.
I have the following generic method signature
public static T? TryConvertToEnum<T>(object obj, T? defaultValue = null) where T : struct, IConvertible
which is working fine! The problem I have is there seems to be a unexpected behaviour from VS in this call:
dynamic dynamicValue = "1";
var value= ConversionHelper.TryConvertToEnum<MyEnum>(dynamicValue);
the problem is that the Type of "value" is "dynamic" and I don't know why I'd expect it to be "MyEnum?"
Did anyone expected this behavior or know why this is happening?
Almost everything you do with a value of type dynamic results in a value of dynamic. Sure, you know the return type of the TryConvertToEnum method you intend to call - but you're passing in a dynamic argument, which means it's not bound until execution time. At execution time, there could be a whole other method with a string parameter and a different return type.
There are a very few cases of expressions which include dynamic values but still don't have a result type of dynamic. Off the top of my head, they are:
Constructor calls (always the type being constructed)
The is operator (always bool)
The as operator (always the type named as the second operand)
In your case, just use object instead of dynamic and the call will be statically bound instead, and value will be of type MyEnum?.

Can you return an 'anonymous struct'? [duplicate]

This question already has answers here:
Getting value from anonymous type? [duplicate]
(3 answers)
Closed 6 years ago.
This answer describes constructing 'an anonymous struct' in C#: Is there an equivalent C# syntax for C's inline anonymous struct definition?
var x = new { SomeField = 1, SomeOtherField = "Two" };
Is it valid to return this from a method to avoid having to define a struct explicitly? A comment on that answer says no, but that was 2011...
That's not a struct, it's an Anonymous Type in C# (which is actually implemented as a class by the compiler). An anonymous type is declared in local scope, and you cannot pass it as a strong typed class in C# because it is a compiler generated class. Your options are either to use object or dynamic as return types, but you still lose the underlying type.
To sum up your question, the answer is a simple "not the way you want it to work".
MSDN says:
Anonymous types are class types that derive directly from object, and that cannot be cast to any type except object. The compiler provides a name for each anonymous type, although your application cannot access it. From the perspective of the common language runtime, an anonymous type is no different from any other reference type.
So you can return it as an object but afterwards you cannot do too much with them unless you use reflection or dynamics.
If your real intention is to return multiple values use the Tuple<...> type instead:
return Tuple.Create<int, string>(1, "Two");

Getting the type of Dynamic variable [duplicate]

This question already has answers here:
get the Type for a object declared dynamic
(2 answers)
Closed 8 years ago.
I am accessing a COM object and a method returns a dynamic variable. I do not have the implementation of the method that returns the dynamic variable and I need to cast it to the appropriate type so that I can use it in my class.
So I would like to know if there is a way to find the underlying type of a dynamic variable during runtime.
The dynamic variable is the value returning from a COM function so the UnWrap doesnt work and GetType() returns COMObject type.
thanks
If the object being returned can be one of many Types then you're best to keep using it as a dynamic and only trying to access methods and properties you know will exist (I'd expect the COM method to have some indication of how to use the dynamic it returns).
var canBeLiterallyAnything = ComMethod();
canbeLiterallyAnything.MethodDocsSayExists();
var propVal = canBeLiterallyAnything.SomeProperty;
Of course, if all of the possible Types all implement the same interface, you could cast to that interface.
var typeSafeReference = (ISharedInterface)canBeLiterallyAnything;
If you know that the COM method returns a specific Type but just don't know what that Type is then for the purpose of investigation you can call GetType() and either write it to console or set a breakpoint and inspect it. This will let you then update your code to include a cast to that Type (which would minimise the impact of the use of dynamic, but also introduce the risk of a bad cast if other Types can be returned).
var type = canBeLiterallyAnything.GetType();
// e.g. If the above returns a Type of 'SpecificType', then you can update code to
var typeSafeReference = (SpecificType)canBeLiterallyAnything;
It should be noted that the COM method might not return a concrete Type, it might be returning an anonymous object, in which case there is no casting you can do so you'll have to just keep using it as a dynamic and only access properties/methods you know exist.

Creating a generic object based on a Type variable [duplicate]

This question already has answers here:
Pass An Instantiated System.Type as a Type Parameter for a Generic Class
(6 answers)
Closed 8 years ago.
I need to create a generic object based on a type that is stored in a database. How can I acheive this? The code below (which won't compile) explains what I mean:
string typeString = GetTypeFromDatabase(key);
Type objectType = Type.GetType(typeString);
//This won't work, but you get the idea!
MyObject<objectType> myobject = new MyObject<objectType>();
Is it possible to do this kind of thing?
Thanks
Type type = typeof(MyObject<>).MakeGenericType(objectType);
object myObject = Activator.CreateInstance(type);
Also - watch out; Type.GetType(string) only checks the executing assembly and a few system assemblies; it doesn't scan everything. If you use an assembly-qualified-name you should be fine - otherwise you may need to get the Assembly first, and use someAssembly.GetType(string).

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