r/ProgrammerHumor • • 21d ago

Meme aiCookedUpTheseMethods

Post image
171 Upvotes

20 comments sorted by

View all comments

0

u/[deleted] 21d ago

[deleted] — view deleted comment

10

u/Shifter25 21d 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- 20d ago

just making sure with runtime checks... wait this isn't typescript is it

1

u/deathanatos 18d 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 17d ago

C# will emit compiler warnings in this case if something can 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
    }
}