Link to home
Start Free TrialLog in
Avatar of Tom Knowlton
Tom KnowltonFlag for United States of America

asked on

Unfamiliar C# syntax for class instantiation / initialization - DataContext?

Not familiar with this syntax.  Is this instantiating an instance of the class?  Why is there no "new" keyword?

InspectionsByTasksViewModel vm = (DataContext as InspectionsByTasksViewModel);

Open in new window

Avatar of Chinmay Patel
Chinmay Patel
Flag of India image

Hi Tom,

If you would post the entire code snippet it would have been easier to explain. By the looks of it, this is not initialization, this is casting.
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/as

It will try to cast the DataContext as a type of InspectionsByTasksViewModel.

Biggest advantage or disadvantage of as keyword is, that the as operator is like a cast operation. But, if the conversion isn't possible, as returns null instead of raising an exception.

Regards,
Chinmay.
By the looks of it, this is not initialization,
Well, vm is being initialized...it's just being initialized based on what you described  ;)
Avatar of Tom Knowlton

ASKER

You're correct; I did not give much surrounding code or context.  Here is a screenshot of an example where this is taking place.

I should have mentioned that this was inside of a XAML application, and apparently "DataContext" belongs to the FrameworkElement, which apparently is part of XAML (I'm brand new to XAML).

I've just never seen initialization of a class instance done via casting?

User generated image
I am not sure if you have used VB.Net or some other language but VB.Net does have a similar operator

https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/trycast-operator
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you!