C
C#2y ago
scac

✅ Get property from generic type?

I have a method with a generic type. Two objects of different classes may be passed to it. How do I access a property in these objects (it has the same name in both objs)? Been trying with reflection but I'm getting a Object reference not set to an instance of an object. C# GetProperty()
12 Replies
Angius
Angius2y ago
Do those objects share an interface? If not, then that's how it should be solved
scac
scacOP2y ago
I can't touch these objects. They do share an interface but that interface does not implement the property I'm interested in.
Angius
Angius2y ago
I guess you could use pattern matching You want to get the value of that property, right?
scac
scacOP2y ago
yes it's a bool
Angius
Angius2y ago
var val = obj switch {
SomeClass sc => sc.Prop,
SomeOtherClass soc => soc.Prop,
_ => false
};
var val = obj switch {
SomeClass sc => sc.Prop,
SomeOtherClass soc => soc.Prop,
_ => false
};
scac
scacOP2y ago
let's see also, why does this not work for me? typeof(T).GetProperty(parameter).GetValue(currentItem); I've tried similar stuff.
Angius
Angius2y ago
¯\_(ツ)_/¯
scac
scacOP2y ago
Stack Overflow
Get property of generic class
I have a generic class, and an object value where obj.GetType().GetGenericTypeDefinition() == typeof(Foo<>). class Foo<T> { public List<T> Items { get; set; } } How do I get...
scac
scacOP2y ago
thank you, this is useful
Anton
Anton2y ago
you need BindingFlags
scac
scacOP2y ago
I will look into that
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server