0

Let's say I have School model

public class School {

public string Name {get; set;} // property

}

I have a array list of Properties coming from database

var arraylist = ["ComputerParts","CellphoneParts"]

is there a way that can I add new property in School Model using for loop?

this what i'm thinking

  1. for loop arraylist
  2. Add new property in school model
//add this -> public string ComputerParts{get; set;} -> in school model
// add this -> public string CellphoneParts {get; set;} -> in school model 

Here's the expected result

public class School {

public string Name {get; set;} 
public string ComputerParts{get; set;}
public string CellphoneParts {get; set;}

}
9
  • 1
    are you building a code generator or something? Otherwise, I don't see how the question really makes sense. Commented Oct 12, 2020 at 9:35
  • 3
    Sounds like XY Problem. Commented Oct 12, 2020 at 9:37
  • You need tell us what's you want to do, a code generator or database migration ? Commented Oct 12, 2020 at 9:37
  • 1
    sure there is a way - dynamic or reflection + subclass. But this is tricky and hard to maintain (reflection + subclass way). You should avoid it at all cost! Commented Oct 12, 2020 at 9:42
  • 2
    Dictionary<string, string> ExtraColumns { get; } ? Commented Oct 12, 2020 at 9:46

1 Answer 1

2

Looks like you are looking for a way to transfer some dynamic set of key-value pairs over network with your DTO. Instead of dynamicly adding properties to some class (which is actually also possible, but a lot more tricky to implement), I would suggest you to use a simple Dictionary<string, string> or even Dictionary<string, object>:

public class SchoolDTO {
    public string Name { get; set; } 
    public Dictionary<string, string> ExtraColumns { get; set; }
        = new Dictionary<string, string>();
}

var schoolDTO = new SchoolDTO
{
    Name = "Sample school",
    ExtraColumns =
    {
        { "ComputerParts", "part1,part2,part3" },
        { "CellphoneParts", "part1,part2,part3" }
    }
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.