-1

i have this code:

Task NavigateToAsync<TViewModel>() where TViewModel : ViewModelInteres;

i dont understand the goal of where, what is the goal?, can someone explain to me what it is for, Is it mandatory to use the reserved word WHERE?

Jason
  • 86,222
  • 15
  • 131
  • 146
  • 1
    https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters – JamesFaix Mar 08 '20 at 21:58
  • 4
    Does this answer your question? [Why use generic constraints in C#](https://stackoverflow.com/questions/4073852/why-use-generic-constraints-in-c-sharp) – Zer0 Mar 08 '20 at 22:12

2 Answers2

1

It is not mandatory at all. You would use where when you want to apply a constraint on the types of your generics.

Some examples:

class MyGeneric<T> where T : class  {...}

T here can only be a class (no structs, like int, byte etc.), this makes it possible to handle better nullable types, for example.

class MyGeneric<T> where T : notnull {...} 

T can be struct or class, but will never be null.

class MyGeneric<T> where T : new() {...} 

T is a class that can be instantiated with an empty constructor. Useful if you want to have generic fabrics.

interface Animal { public int nrPaws {get;} }
class MyGeneric<T> where T : Animal {...} 

T must implement the interface Animal. In this way you can control the methods you can call from MyGeneric.


where is generally very handy when you want these kind of checks to be done at compile-time rather that throwing error during run-time.

Alvin Sartor
  • 2,249
  • 4
  • 20
  • 36
-1

it constrains what types can be used for TViewModel

Jason
  • 86,222
  • 15
  • 131
  • 146
  • can i help with https://stackoverflow.com/questions/60621436/how-use-the-styles-merged please –  Mar 11 '20 at 02:06