83
u/JMOWw7 10d ago
Pattern matching all the way. I think the second one probably won't catch inheretance
57
u/captainAwesomePants 10d ago
This is true, but of course they are also both stupid because a IsSomething(thing) function has no advantage over just typing "thing is Something" each time.
2
u/JMOWw7 10d ago
Yeah of course. The code makes no sense in general. Type of Something.Something implies that it's a class nested inside of Something which would be not allowed, and then since you're passing a Something to the method it would always be false... But this sub is for idiot kids who've taken like a semester of comp sci classes
5
u/Tyfyter2002 10d ago
I think a nested class can inherit the class it's nested in in C#, and whether or not it's valid in Java one would have a bigger problem because it's using
==.3
0
u/tasos_lydia4 1d ago
If it uses GetType() == typeof(T), yes: that checks the exact runtime type; `is T` also matches derived types.
1
u/ANixosUser 7d ago
what languae is this? new Java?
2
u/intbeam 7d ago
C#, so close
1
u/andrewowenmartin 6d ago
1996 - James Gosling invents Java. Java is a relatively verbose, garbage collected, class based, statically typed, single dispatch, object oriented language with single implementation inheritance and multiple interface inheritance. Sun loudly heralds Java's novelty.
2001 - Anders Hejlsberg invents C#. C# is a relatively verbose, garbage collected, class based, statically typed, single dispatch, object oriented language with single implementation inheritance and multiple interface inheritance. Microsoft loudly heralds C#'s novelty.
A Brief, Incomplete, and Mostly Wrong History of Programming Languages
0
10d ago
[deleted]
10
u/Shifter25 10d ago
You could use it to detect which kind of implementation of a superclass it is, maybe.
IsEagle(Bird bird) => bird is Bird.Eagle
Something like that?
1
u/-Redstoneboi- 10d ago
just making sure with runtime checks... wait this isn't typescript is it
1
u/deathanatos 7d ago
I believe this is C#.
You're passing in a Something. It shouldn't compile if it isn't a Something.
laughs in null
1
u/intbeam 7d ago
C# will emit compiler warnings in this case if
somethingcan be null. If you make the parameter nullable,(Something? something)you can also make the compiler assert the nullability of the parameter;public static bool IsSomething([NotNullWhen(true)]Something? something) => something is Something.Something;In that case, it will annotate code in that context where IsSomething may return false without the caller checking the result;
public static void DoSomething(Something? something) { var b = IsSomething(something); Console.WriteLine(something.ToString()); // compiler warning, "something may be null" if(b) { Console.WriteLine(something.ToString()); // No compiler warning } }
4
u/Patchargh 10d ago
Context: Friend asked AI how to check if a something is something in C#.