c# - Setting properties of an instance the same way as object initializer -


what i'd having object initializer, instance of object has been created. this:

myclass myobj = myclass.newobj(); //... myobj { prop1 = val1, prop2 = val2, ... prop50 = val50 }; 

this better writing:

myobj.prop1 = val1; myobj.prop2 = val2; //... myobj.prop50 = val50; 

because you'd list of remaining properties (and properties!) haven't been given value (just object initializer). there syntax construct allows currently? (c# 6.0)

i think looking with operator in vb. answer no. there no such thing in c#. although can code workarounds if need , if agree use dynamic objects. check example below:

public class program {     public static void main(string[] args)     {         //your code goes here         console.writeline("first:");         myclass c = new myclass();         c.set(new {property1="1", property2="2", property4="4"});         console.writeline(c);         console.writeline("second:");         c.setwithreflection(new {property1="11",property2="22", property4="44"});         console.writeline(c);      } } public class myclass{     public void set(dynamic d){         try{ property1=d.property1;}catch{}         try{ property2=d.property2;}catch{}         try{ property3=d.property3;}catch{}     }      public string property1{get;set;}     public string property2{get;set;}     public string property3{get;set;}     public override string tostring(){         return string.format(@"property1: {0} property2: {1} property3: {2}", property1,property2,property3);     }                 } public static class extensions{     public static void setwithreflection<t>(this t owner, dynamic d){         var dynamicprops = d.gettype().getproperties();         foreach(propertyinfo p in dynamicprops){             var prop = typeof(t).getproperty(p.name);             if(prop!=null){                 try{ prop.setvalue(owner, p.getvalue(d)); } catch{}             }         }     } }  

the concept simple. use object initializer create dynamic class , assign properties instance via method.


Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -