.net - C# Compiler - Unassigned DateTime Field and Local Variable -


out of curiosity:

this code valid , executes:

public class program {     private static datetime date;      public static void main()     {         console.writeline(date.tostring("o"));     } } 

see working on .net fiddle

but doesn´t compile (unassigned local variable):

public class program {     public static void main()     {         datetime date;         console.writeline(date.tostring("o"));     } } 

see (not) working on .net fiddle

datetime non nullable value type, doesn´t need assigned , initialized have value, has default one.

so why compiler allows datetime field version compile , doesn´t let local variable version compile? when code compiled il, prevents value type local variable being used?

a field has no explicit initialisation automatically initialised default value.

this useful it's common initial value, saves time.

a local has no initialisation in state can not used.

this useful because did wrong (especially if there several paths determine initial value), setting default hide bug.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -