Destroy yourself

Well, I probably just have an epic setback here, but my mind wants to say that this should work.

Suppose DataProtect.DecryptData takes an encrypted string as input and a decrypted string as output. Suppose that deserializeXML makes the corresponding object and returns it from a recently decrypted string.

So. Why is this not working?

class ArrivedDetails { ///... internal ArrivedDetails(string encrypted) { this = DataProtect.deserializeXML(DataProtect.DecryptData(encrypted)); } ///... 

Gives an error

 Cannot assign to '<this>' because it read only 

In particular, how can I make this work? I essentially want to decrypt the serialized version of the XML object and then deserialize it inside the constructor.

I am open to β€œyou cannot” (with an explanation), because I can put it in another place and just assign values, but my mind says something like this should be possible.

+8
object c # serialization
source share
4 answers

No, this is not possible with the constructor; you cannot reassign this .

Use the static method instead:

 public static ArrivedDetails CreateFromString(string encrypted) { return DataProtect.deserializeXML(DataProtect.DecryptData(encrypted)); } 

Name it:

 ArrivedDetails details = ArrivedDetails.CreateFromString(encrypted); 
+12
source share

You cannot assign anything to "this". Change ArriveDetails to a static returning a deserialized object.

 class ArrivedDetails { static ArrivedDetails Create(string encrypted) { return DataProtect.deserializeXML(...) } } 
+3
source share

You can archive this with a reflection as follows.

 A config = DataProtect.deserializeXML(DataProtect.DecryptData(encrypted)); foreach (var property in GetType().GetProperties()) if (property.GetCustomAttributes(typeof (XmlIgnoreAttribute), false).GetLength(0) == 0) property.SetValue(this, property.GetValue(tmp, null), null); 

This assigns a temporary variable to the deserialized object and copies the value in each public property to this with reflection. This snippet avoids copying properties using the XmlIgnore attribute.

+3
source share

What you want is a static factory method that creates the required object.

 class ArrivedDetails { ///... public static ArrivedDetails CreateFromEncryptedKey(string encrypted) { return DataProtect.deserializeXML(DataProtect.DecryptData(encrypted)); } ///... 

The reason your initial approach does not work is because this is a private read-only field that returns the object from which it is being called. You cannot write this .

+2
source share

All Articles