Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate properties programmatically

Tags:

c#

properties

I want to load a properties file (it's a .csv file having on each line a name and associated numeric value) and then access those property values like so: FileLoader.PropertyOne or FileLoader.PropertyTwo. The problem is I don't want to have to write a property for each value, I want them to be generated from the file. So

public class FileLoader
{
    public int Property1 { get; private set; }
}

is not what I'm looking for. Is this possible? I can't see any way to do it because obviously the compiler wouldn't know about the property names. Perhaps something similar?

like image 405
Johnny Avatar asked Feb 04 '10 16:02

Johnny


2 Answers

In C# 4.0, you could use the ExpandoObject, link contains good explanation and a couple of use cases, like :

dynamic contact = new ExpandoObject();
contact.Name = "Patrick Hines";
contact.Phone = "206-555-0144";
contact.Address = new ExpandoObject();
contact.Address.Street = "123 Main St";
contact.Address.City = "Mercer Island";
contact.Address.State = "WA";
contact.Address.Postal = "68402";

Though the awesomeness of the ExpandoObject is to dynamically create complex hierarchical objects, I suppose you could use it in general for it's shiny syntax even for simple dynamically defined objects.

EDIT: Here is another answer on SO adding details about the benefits of ExpandoObject by the same columnist that wrote the previously linked article

What are the true benefits of ExpandoObject?

like image 178
Dynami Le Savard Avatar answered Nov 04 '22 21:11

Dynami Le Savard


Code generation like this can be done in several different ways.

  • Visual Studio has T4 templates.
  • You can use external tools like My Generation (it is geared towards ORM code generations, not sure it supports CSV).
  • Or roll out your own code to read the file and write out such classes (to be created with a .generated.cs suffix).
like image 2
Oded Avatar answered Nov 04 '22 22:11

Oded