Cast - string for Custom <string>

I have my own wrapper for my properties: MyType<t> . I have private members of these types and public members of type t.

I try to load an object and get an error while translating:

Cannot overlay object of type "System.String" on type "Model.MyType`1 [System.String]

I have a method for the following:

 private t _value; public static implicit operator t(MyType<t> obj) { return obj._value; } 

Any help is what I am missing to make acting excellent.

Update:

The item is as follows:

  MyType<string> PostalCode = new MyType<string>(); 

I load properties using Dapper , and the methods that have been suggested don't hit. Therefore, when the reflection engine tries to load objects, the implicit throw does not work.

+4
source share
2 answers

Your operator is the reverse. It supports casting from MyType<t> to t . You want it differently. Perhaps something like this is what you are looking for.

  private t _value; private MyType(t val) { _value = val; } public static implicit operator MyType<t>(t obj) { return new MyType<t>(obj); } 

Using a constructor is optional, I personally just find it cleaner. You could simply use the default constructor and also explicitly specify the field in your statement.

+5
source

Your implicit substitution operator works in the opposite direction to what the error is complaining about, you need to implement another implicit operator to go from t to MyType<t> .

You can also do the same with explicit casting (where you do something like string foo = (string)someObject; ):

http://msdn.microsoft.com/en-us/library/xhbhezf4(v=vs.71).aspx

+1
source

All Articles