Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Microsoft is casting null to a type, should I?

Tags:

c#

I'm working on some customized authentication code based on Microsoft's membership stuff. While looking into the Profile functionality, I looked into the ProfileBase class found in System.Web.dll v4.0.30319. There are a few class level variables that are declared as a type but then and then initialized to a null value that is cast to that type.

For example,

private static Exception s_InitializeException = (Exception) null;
private static ProfileBase s_SingletonInstance = (ProfileBase) null;
private static Hashtable s_PropertiesForCompilation = (Hashtable) null;

I don't normally initialize variables that have a class level scope. I'm wondering if this is something I should be doing or what purpose it serves.

Thanks for any enlightenment.

like image 905
Jeff Reddy Avatar asked May 29 '12 18:05

Jeff Reddy


3 Answers

You're probably looking at the disassemblied code. This casting is probably added by the disassembler and it didn't exist in the source code.

You definitely don't have to do this kind of casting in your code.

like image 175
Jakub Konecki Avatar answered Nov 06 '22 15:11

Jakub Konecki


There is no point to this; I believe null is always null - I certainly can't think of any examples in C based languages where it isn't. It is probably generated code rather than code that has been explicitly written like that.

like image 34
Luke Avatar answered Nov 06 '22 13:11

Luke


What that code is saying: initialize an area of memory to hold a type of Exception, and assign the value NULL to that variable. Since Exception is a reference type then it can be null. There is no point to casting NULL to Exception. Maybe generated code?

like image 41
RobertMS Avatar answered Nov 06 '22 15:11

RobertMS