c# - Is it possible to change default value for value types variables? -


this question has answer here:

i'm curious know, possible change default value of e.g. int in c# , can have value -1 instead of 0.

public class foo {     public int i; } ... foo = new foo(); console.write(foo.i); 

so code must return

-1 

without explicit initializing

public class foo {     public int = -1; } 

can sure, don't print somewhere like

#define true false 

but default value of int

p.s. interest purposes only.

no, basically. assuming don't initialize fields, memory space zeroed. shouldn't expose fields directly anyway.

one trick have seen around (used capnp serializer, works against raw memory, not objects) use xor. example: if default -1, can xor value in , out:

public class foo {     private int i;     public int {         { return ^ -1; }         set { = value ^ -1; }     } } 

this has no initialization, , want. use types other bools , integers more complex, still possible - easier use initializer.

note -1 case, use "not" rather "xor":

public class foo {     private int i;     public int {         { return ~i; }         set { = ~value; }     } } 

however: field initializer (int = -1;) or constructor (public foo() { = -1; }) simpler.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -