c# - Is a string reference equality check guaranteed to be static? -


i have function signature:

public void dosomething(string name); 

the string name special in application. can either arbitrary string, or special known value. because non-empty string value valid input means need use object reference equality empty strings, so:

public class foo {      public const string specialvalue1 = "";     public const string specialvalue2 = "";      public void dosomething(string name) {          if( object.referenceequals( name, specialvalue1 ) ) {            } else if( object.referenceequals( name, specialvalue2 ) {           } else {          }     }      public void usageexample() {          dosomething( specialvalue1 );         dosomething( "some arbitrary value" );     } } 

i want know if technique, using empty strings , object reference equality safe, respect string interning.

antimony right reasons not work.

i suggest define type argument. let's call exampleargument.

public class exampleargument {     private readonly int _knownvalue;     private readonly string _arbitraryvalue;      public exampleargument(string arbitraryvalue)     {         _arbitraryvalue = arbitraryvalue;         _knownvalue = 0;     }      private exampleargument(int knownvalue)     {         _knownvalue = knownvalue;         _arbitraryvalue = null;     }      public static readonly exampleargument firstknownvalue = new exampleargument(1);     public static readonly exampleargument secondknownvalue = new exampleargument(2);      // obvious equals , gethashcode overloads      // possibly other useful methods depend on application } 

oh, , if want calling syntax in example, add:

    public static implicit operator exampleargument(string arbitraryvalue)     {         return new exampleargument(arbitraryvalue);     } 

which implicit conversion operator string exampleargument.

dosomething(exampleargument.firstknownvalue); dosomething(new exampleargument("hello")); dosomething("hello"); // equivalent previous line, uses implicit conversion operator 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -