c# - Why can`t I seem to assign values to my constant fields? -
c# - Why can`t I seem to assign values to my constant fields? -
i using c# , trying assign logical (not null) values custom type constant fields. here how.
public class types_of_accuracy{ 1 public const types_of_accuracy decimal_places=type_of_accuracy(false); 2 private bool sd; 3 public const types_of_accuracy significant_digits=type_of_accuracy(true); 4 private static types_of_accuracy type_of_accuracy(bool significant_digits){ 5 types_of_accuracy ta=new types_of_accuracy(); 6 ta.sd=significant_digits; 7 homecoming ta; 8 } }
when seek compiling. these errors.
line 1|'types_of_accuracy.decimal_places' of type 'types_of_accuracy'. const field of reference type other string can initialized null. (cs0134) line 3|'types_of_accuracy.significant_digits' of type 'types_of_accuracy'. const field of reference type other string can initialized null. (cs0134)so far, favorite solution replace code above, code below.
public class types_of_accuracy{ 1 static types_of_accuracy(){ 2 decimal_places.sd=false; 3 significant_digits.sd=true; 4 } 5 public const types_of_accuracy decimal_places=null; 6 private bool sd; 7 public const types_of_accuracy significant_digits=null; }
any improvements appreciated.
constant fields must initialized constant values. and have of value type, or string, or initialized null.
types_of_accuracy
class (reference type), , you're trying initialize constants method calls, not constants. workaround, can declare fields static readonly
instead:
public static readonly types_of_accuracy decimal_places = type_of_accuracy(false); public static readonly types_of_accuracy significant_digits = type_of_accuracy(true);
it's not same constant: using value of readonly field read field @ runtime, while using constant replace value @ compile time. in cases, difference doesn't matter.
c# sharpdevelop
Comments
Post a Comment