C
C#2mo ago
stigzler

Casting types inline

I'm still not clear on all the routes to this, and which one is best for readability. I'm trying to get .Count from a child object of object sender. The Type hierarchy is:
DirectDragTreeViewItem.GistViewModel.GistModel.IList<GistFileModel>
DirectDragTreeViewItem.GistViewModel.GistModel.IList<GistFileModel>
Here are a couple of ways I've tried:
int directCastListCount = (GistViewModel)((DirectDragTreeViewItem)sender).DataContext) // wtf!? gave up here
int paternMatchedListCount = ((((sender as DirectDragTreeViewItem).DataContext as GistViewModel).Gist as GistModel).Files as IList<GistFileModel>).Count();
int directCastListCount = (GistViewModel)((DirectDragTreeViewItem)sender).DataContext) // wtf!? gave up here
int paternMatchedListCount = ((((sender as DirectDragTreeViewItem).DataContext as GistViewModel).Gist as GistModel).Files as IList<GistFileModel>).Count();
Of course things could be nested deeper. Which is the best way (realise 'best' is ambiguous)
7 Replies
Joreyk ( IXLLEGACYIXL )
send proper event args
Stefanidze
Stefanidze2mo ago
What are you trying to achieve here? What's the purpose of this code? If you want to pass data with event you don't need the sender object but EventArgs Also casting here looks strange to me...
stigzler
stigzler2mo ago
I was really asking more conceptually
Joreyk ( IXLLEGACYIXL )
in C# you have always ( atleast in Gui its standard ) for an event of some kind SomeEvent(object sender, ImportantEventArgs args) you define the ImportantEventArgs yourself, and there you put your types accurately how you need them into that you shouldnt cast the sender
Stefanidze
Stefanidze2mo ago
Well, if you want this code working, this looks fine to me:
IList<GistFileModel> result = (sender as DirectDragTreeViewItem).GistViewModel.GistModel.IList<GistFileModel>;
IList<GistFileModel> result = (sender as DirectDragTreeViewItem).GistViewModel.GistModel.IList<GistFileModel>;
But you really shouldn't do this to pass data with events...
stigzler
stigzler2mo ago
Yeah - I'm jjst tinkering with someone else's code + i hear what you are saying about design, but my question was really about syntax/concepts
Joreyk ( IXLLEGACYIXL )
the concept is to not do what has be done