Calling an overload with null: casting vs default [closed]
-
02-07-2021 - |
Question
Not sure if this is a bit of a superfluous question, but consider I have these methods:
void Foo(SomeClass x)
{
//Some code
}
void Foo(AnotherClass x)
{
//Some code
}
And let's say that I want to call a specific overload (the SomeClass one) with null, here are my options:
Foo((SomeClass)null)
Foo(null as SomeClass)
Foo(default(SomeClass))
Basically, which is the best to go for? Are there any significant performance differences between the different approaches? Is a specific way generally considered more 'elegant' than the others?
Thanks
Solution
Option 4: create another overload:
void Foo()
Calling with an explicit null that you need to cast? Umm...eww...
To "officially" answer your question. Try it!
var sw = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++) {
Foo(null as string);
}
Console.WriteLine(sw.ElapsedMilliseconds);
sw = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++) {
Foo((string)null);
}
Console.WriteLine(sw.ElapsedMilliseconds);
sw = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++) {
Foo(default(string));
}
Console.WriteLine(sw.ElapsedMilliseconds);
Console.ReadLine();
I got ~4ms for all 3 approaches.
When I open up the program in reflector, I see that all of the calls have been turned into: Foo((string) null);
So, you can choose whatever you find most readable. The IL all ends up exactly the same.