I have a method that iterates the fields of a class, returning their values as a CSV. I need a way to give classes access to this method in a generic fashion.
For some reason, Statics must derive from object or you get a compile error. In this case, deriving from a different base class does increase code re-useability for me. Is there another way to accomplish my goal?
I believe the only choice I have is to make my static class an instance class.
//a data container used for Mocking in inversion of control
public class FieldContainer : ReflectionHelper<FieldContainer>
{
public static string Field1 = "Some Data";
public static string Field2 = "Persons Name";
public static string Field3 = "3030 Plane Ave.";
}
public class ReflectionHelper<T>
{
public static string ToCSV()
{
StringBuilder fieldCollector = new StringBuilder();
Type type = typeof(T);
FieldInfo[] fields = type.GetFields();
foreach (FieldInfo f in fields)
{
fieldCollector.Append(f.GetValue(null) + ",");
}
return fieldCollector.ToString();
}
}
Your code is perfectly valid (at least technically). Your class
FieldContaineris not astaticclass and therefore it can derive fromReflectionHelper<T>.However, you normally would not implement the method
ToCSVin a base class, because it can basically work on ANY class. Because you want to work on static members, an extension method isn’t the best way either. The simplest and cleanest way to do it, will be to have a static helper class that implements this method:You can use it like this:
However, I fail to see, why you would want to implement something like that at all. It doesn’t seem to make too much sense.