❔ Use Variable as Type
Hiya 🙂
I'm needing some help with a WinForms Project. I want to take an object from a list and convert that object's properties to an array. The object type, however, can vary. I have a form that asks for what type the user wants, and I want to pass that decision into my code as a variable so that the correct object type is loaded. I've been using dynamic, but it mistakes one class for another, and dynamic is ugly anyway. Attached the code for that bit with dynamic in. Thanks!
26 Replies
objList is the list of generic objects. objArray is an array of those objects. singleArr is just one of those objects and objProp is that object's properties.
Well, the problem is, C# isn't really built to support "an array of whatever"
object
, dynamic
, etc are just workarounds at best
Signs of bad design, usuallyoh bugger
So if your list can hold whatever in it, I have to question why
I have 2 classes
customer and engineer
there is a data entry form and it will add it to a list
and csv
Seems like they could both inherit from a
Person
classindeed they do
Or even they could just be a
Person
class
With a property that tells you whether they're a customer or an engineerthere as about 3 properties different
ooh
and then I could just leave the customer specific properties balnk?
blank?**
Sure
Or you can have a list of
Person
And use pattern matching to see if they're the customer or engineercould I just google microsoft documentation about pattern matching? I haven't used that before but sounds usefull
i ask that and it took 2 secs to actually do it
Sure can google it lol
Basically, what it lets you do, is
so if i got this right
if variable person is of client type/ has client characteristics
You can do property matching, yes
what does the 'c' do after Client? is that just creating a new variable going forward?
What I described is about the type
Yep, creates a new variable of the matched type
great!
will this thread stay open if I need to come back?
It should, yea
thanks so much by the way haven't even seen this in the textbook i got lmfao
really appreciate it!
Pattern matching is a fairly new feature
ah I see
thank god for libraries, this book is $70 and already old
Yeah, books do go out of date fairly quickly
We get a new version of .NET and C# every year, after all
yeah the preface of this book literally says "there's a new version in 7 months" like why are you writin it then
The features that are there stay the same, new ones are added on top. So you could think of that book as one that teaches a subset of C#
that's a positive way of thinking
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.