Lennie
Lennie

Reputation: 2447

Generic method cast T to object type

I have a method that accepts a generic type of BaseViewModel. I want to get the actual object in the method.

What I tried:

public static void LogScreen<T>() where T : BaseViewModel
 {
    var viewModel = T as BaseViewModel;
 }

Upvotes: 1

Views: 3527

Answers (1)

Tatranskymedved
Tatranskymedved

Reputation: 4371

You are not passing any object into the method, only the parameter type.

To apply value correctly, You should use the syntax like:

public static void LogScreen<T>(T TArg)
    where T : BaseViewModel
{
    var viewModel = TArg; //not necessary: as BaseViewModel;
}

In this kind of code You do not really need to use generic and You might go with simplier version as:

public static void LogScreen(BaseViewModel viewModel)
{
     //already got viewModel as correct type and checked during compile for types
}

Note: The big advantage of using generic approach is putting there some type and then work with the type whole time (great example IEnumerable<int>). If You would do that without generic type, You would need to use object everywhere and You would need to cast the object all the time

  • Generic is advantage there as You can put anything inside.

On the other hand if You have a method, where You have only one type the only one, it is easier to go with strict parameter type (2nd approach).


Comment of ZoharPeled - the code should be written as:

public static void LogScreen<T>(T TArg)
    where T : BaseViewModel
{
    var viewModel = TArg as BaseViewModel;
    var viewModel2 = TArg;
}

From the compiler's point of view, the type of the reference named viewModel is exactly the same as the type of the reference named viewModel2 - both are BaseViewModel, and both instances may or may not be of any type derived from BaseViewModel. Long story short, the as operator is redundant in this code. Even if you pass an instance of some class derived from BaseModelView you can only reference it as a BaseModelView in this method.

Upvotes: 7

Related Questions