.net - Is there any way to implicitly construct a type in C#? -


i read of useful trick how can avoid using wrong domain data in code creating data type each domain type you're using. doing compiler prevent accidentally mixing types.

for example, defining these:

public struct meter {     public int value;      public meter(int value)     {         this.value = value;     } }  public struct second {     public int value;      public second(int value)     {         this.value = value;     } } 

allows me not mix meters , seconds because they're separate data types. great , can see how useful can be. i'm aware you'd still need define operator overloads handle kind of arithmetic these types, i'm leaving out simplicity.

the problem i'm having approach in order use these types need use full constructor every time, this:

meter distance = new meter(5); 

is there way in c# can use same mode of construction system.int32 uses, this:

meter distance = 5; 

i tried creating implicit conversion seems need part of int32 type, not custom types. can't add extension method int32 because need static, there way this?

you can specify implicit conversion directly in structs themselves.

public struct meter {     public int value;      public meter(int value)     {         this.value = value;     }      public static implicit operator meter(int a)     {          return new meter(a);     } }  public struct second {     public int value;      public second(int value)     {         this.value = value;     }      public static implicit operator second(int a)     {          return new second(a);     } } 

Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c# - Copy ObservableCollection to another ObservableCollection -

All overlapping substrings matching a java regex -