c# - Serialize null reference object -


i'm trying 'serialize' type iterating through properties , write down every value type dictionary.

pseudo

serialize(object)     foreach(prop in object.gettype().getproperties()          value = prop.getvalue(object);         if (prop.propertytype.isvaluetype)             writetodict(prop.name, value)         else             serialize(value) 

given type

public class complextype {     public string prop1 { get; set; }     public int prop2 { get; set; }     public othertype prop3 { get; set; } }  public class othertype {     public string prop4 { get; set; } } 

now, when create instance of complextype , try 'serialize' it, works fine until iterates on prop3 (othertype). when try call value.gettype() on it, run nullreferenceexception because, of course, there has never been reference set prop3.

is there way work around this? how other serialization frameworks this? (i mean, can't create default instance of type because don't know type @ runtime!)

oh, , yes, can't skip property because i'm interested in structure (even if doesn't have value set).

okay, figured out. nullreferenceexception happened because stupid.

for in future tries type of uninitialized reference type:

if call .gettype() on object, .net frameworks looks reference of object in memory. because object hasn't been initialized, there nothing there up, nullreferenceexception thrown. if want iterate through properties of instance, need @ least type of upper parent, can types of further reference type properties via propertyinfo.propertytype (and not directly of object pulled out of parent property).


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -