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?
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?
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.
it constrains what types can be used for TViewModel