c# - Is it legit code to tag an object like this? -


i've once written piece of code add name task. code below seems same, less code. wonder, legit. production code ready. garbage collection? instance of class being moved around in code (because not pinned), still work when moved around? how can put code test?

using system.runtime.interopservices;  namespace consoleapplication1 {     class program     {         static void main(string[] args)         {             var obj = new object();             obj.tag("link data");             var tag = obj.tag();         }     }      public static class objectextensions     {         private class tagger         {             public string tag { get; set; }         }          [structlayout(layoutkind.explicit)]         private struct overlay         {             [fieldoffset(0)]             public tagger tagger;             [fieldoffset(0)]             public object instance;         }          public static string tag(this object obj)         {             var overlay = new overlay {instance = obj };             return overlay.tagger.tag;         }          public static void tag(this object obj, string tag)         {             var overlay = new overlay {instance = obj };             overlay.tagger.tag = tag;         }     } } 

no, not legitimate @ all. frankly, i'm surprised .net , c# allow without /unsafe switch. proposal has obvious risks, have admit in these years of coding in c#, never occurred me 1 able violate safe memory access in c#, without explicitly enabling unsafe code.

consider variation on example:

class {     public string text { get; set; } }  class program {     static void main(string[] args)     {         a = new { text = "text" };          a.tag("object tag");          string tag = a.tag(), text = a.text;     } } 

you find that, on last statement, text variable has been set "object tag". in other words, "overlay" approach has allowed code reinterpret reference object of class a, reference object of class overlay, without sort of compiler warning or run-time error @ all.

in above example, consequence benign hope for: original property value of text has been changed correct value text passed "tag". bad enough, in other contexts find class has been corrupted in horrible ways, leading further data corruption or (if you're lucky) immediate termination of program resulting kind of access violation or other exception.

don't this. it's dangerous, , when used in way proposed here, never work correctly. you'll overwriting data shouldn't have.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -