Sonny Childs Sonny Childs - 1 year ago 56
C# Question

Can you auto-generate code for assigning properties of an object in C#? (Visual Studio)

Example: I am working with an API that has definitions for various objects with many properties.

This object has about 40 properties, and I'd like to set them all.

Is there a way to auto-generate the following code from an object?

contact.AddressId = null;
contact.Anniversary = null;
contact.AssistantId = null;
contact.BirthDay = null;
contact.Children = null;
contact.CompanyAddressInfo = null;
contact.CompanyIdentifier = null;
contact.DisablePortalLogin = null;
contact.Email = null;
contact.Emails = null;
contact.ExtensionData = null;
contact.Fax = null;
contact.Faxes = null;
contact.FaxExt = null;
contact.FirstName = null;
contact.Gender = null;
contact.Id = null;
contact.Inactive = null;
contact.LastName = null;
contact.LastUpdated = null;
contact.ManagerId = null;
contact.Married = null;
contact.NickName = null;
contact.PersonalAddress = null;
contact.PersonalAddressFlag = null;
contact.Phone = null;
contact.PhoneExt = null;
contact.Phones = null;
contact.PortalPassword = null;
contact.PortalSecurityLevel = null;
contact.Relationship = null;
contact.School = null;
contact.SID = null;
contact.SignificantOther = null;
contact.SiteName = null;
contact.Title = null;
contact.Type = null;
contact.UnsubscribeFlag = null;
contact.UpdatedBy = null;

The purpose is for visualization and for me to see what I am and am not setting in my code.

Edited to be more specific.

Answer Source

So using Jonathan's answer I've created a method that accepts an object and a name, and spits out all properties with null as a placeholder, as shown in the question:

    static void Main(string[] args)
        ObjectGenerateNullValues(new Contact(), "contact");

    private static void ObjectGenerateNullValues(object objectType, string objectName)
        var props = objectType.GetType().GetProperties();

        using (StreamWriter sw = new StreamWriter(@"c:\temp\ObjectPropertiesOutput.txt", true))
            foreach (var p in props)
                sw.WriteLine("{0}.{1} = null", objectName, p.Name);

I suppose I shall write a little lightweight GUI to do this for me as I continue to explore these APIs.