c# - GetType() == typeOf(string) or var is string ...? -
c# - GetType() == typeOf(string) or var is string ...? -
so when calling console.readline , assigning variable evaluated if statement want know if next code interchangeable , if not how different point should pick 1 on other application.
//code omitted var reply = console.readline(); if (answer.gettype() == typeof(string)) { console.writeline("awesome"); } // code omitted
just wondering if using over
if (answer string) ...
is improve choice?
the code wrote nonsense, because console.readline
always returns string
(it homecoming type after all!).
to reply question, is
operator not equivalent gettype() == typeof()
statement. reason is
homecoming true if object can cast type. in particular, homecoming true derived types, fail other check. msdn:
an look evaluates true if provided look non-null, , provided object can cast provided type without causing exception thrown.
note is operator considers reference conversions, boxing conversions, , unboxing conversions. other conversions, such user-defined conversions, not considered.
if looking specific type of input (say number) need seek , parse
or tryparse
type. like:
double output; if (double.tryparse(answer, out output) { //its number! } else { //its regular string }
without seeing more impossible need write though.
c#
Comments
Post a Comment