The existing answers already tell the difference. But C# 7 gave a new function for the is
.
When do you need to check the type of the object? When you don’t know the exact type you are getting.
What do you do to use this object with the type you checked? It probably does a cast for the type and then have access to the members available in this type. If you do not need to access these members you do not have to do the cast, and then you don’t have to check what kind it is.
As in most cases the cast is the desired 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;
}
}
}
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
Note that the variable is declared inside the if
or case
but it has scope of method, so it cannot use the same name on each one. This is because it is not inside the block of the if
, the condition itself does not create new scope.
The use of switch
may appear not to be using the is
, but as the ==
is implicit in it, the is
is also there even if you don’t see.
Related: What is the difference between typeof(T) vs. Object.Gettype()
– Jéf Bueno