Existing answers already speak the difference. But C # 7 gave a new function to is
.
When do you need to check the type of the object? When you do not know the exact type you are getting.
What do you do to use this object with the type you checked? It probably makes a cast for the type and then has access to the available members of that type. If you do not need to access these members you do not have to cast , and then you do not have to check what type it is.
As in most cases cast is what you want, C # 7 allows this to be done automatically.
using static System.Console;
using System;
public class Program {
public static void Main() {
Teste(DateTime.Now);
WriteLine();
Teste("ok");
}
public static void Teste(object qualquerVariavel) {
if(qualquerVariavel is DateTime x) {
WriteLine($"A variável é DateTime e seu valor é {x.DayOfWeek}");
}
if(qualquerVariavel is DateTime) {
WriteLine($"A variável é DateTime e seu valor é {((DateTime)qualquerVariavel).DayOfWeek}");
}
if(qualquerVariavel is DateTime) {
// WriteLine($"A variável é DateTime e seu valor é {qualquerVariavel.DayOfWeek}"); //isto não compila
}
if(qualquerVariavel is "ok") {
WriteLine($"A variável é string e vale ok");
}
switch (qualquerVariavel) {
case null:
WriteLine("nulo");
break;
case int i:
WriteLine(i);
break;
case string s:
WriteLine(s);
break;
case DateTime d:
WriteLine(d.DayOfWeek);
break;
}
}
}
See working on .NET Fiddle . Also put it on GitHub for future reference .
Note that the variable is declared inside if
or case
but has method scope, so it can not use the same name in each. This is because it is not within the if
block, the condition itself does not create a new scope.
Using switch
may not appear to be using is
, but just as ==
is implied in it, is
is also there even if you do not see it.