Reputation: 1663
I need to concat all the properties in my class at compile time to build a string. I have seen similar questions, but they were all dealing with runtime scenarios. Basically, I have a thousand properties, and would rather not list them out by hand again. I know about using reflection to use typeof(X).getProperties(...), but I don't wan't any performance hit for doing this at runtime with reflection. Is there a way for me to loop through all the properties in my class to make a string of all my properties?
Class1 : SomeInterface
{
int1;
int2;
...
int1000;
string stringOfAllProperties;
public getAllPropertiesAsString()
{
return stringOfAllProperties = int1+int2+int3...;
}
}
Upvotes: 1
Views: 354
Reputation: 172280
As others have mentioned, you might have a design problem if you have a thousand properties. Solving that design problem would be my first choice, but if that is not an option...
Visual Studio supports compile-time (or, to be precise: save-time) code generation via T4 templates, i.e., you can do something like this:
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
class MyClass
{
<# var properties = new string [] {"int1", "int2", "int3", ...}; #>
<# foreach (string property in properties) { #>
private int <#= propertyName #>;
<# } #>
public string getAllPropertiesAsString()
{
return ""
<# foreach (string property in properties) { #>
+ <#= propertyName #>;
<# } #>
}
}
Note that you will have to install the "Visual Studio extension development" workload during Visual Studio 2017 setup.
Upvotes: 1
Reputation: 3001
If you want it done every time you compile and then not during runtime, I would build a method using reflection that never gets called at runtime. You could then have a second console application whose only purpose it to trigger that method and write the string to a text file or something. In project properties (of your main project), you can do command line stuff (such as running your console app).
Without knowing what framework you are using, I can't tell you how your console app would interact with the main app. Your main app could be a dependency of the console app, though, and then your console app could directly use classes in the main app if they are public.
Upvotes: 1
Reputation: 675
I think only reflection will help you here. What you can do is to introduce dictionary where keys will be types and values will be string concatenation results. The dictionary will be used as a singleton in your application. Thereby, you will calculate your string only once per type, hence eliminating performance penalty almost completely.
Upvotes: 1