11
I have a class with two properties (Name
and Value
). The estate Name
is a string
, already the property Value
I want to leave the variable type.
public class Field<TValue>
{
public string Name { get; set; }
public TValue Value { get; set; }
public Field()
{
}
public Field(string name, TValue value)
{
this.Name = name;
this.Value = value;
}
}
In this case it would be simple to instantiate this class with the desired type:
var field1 = new Field<int>("Nome1", 1);
var field2 = new Field<string>("Nome2", "Valor2");
The problem is I have an intermediate class that uses the class Field
as property:
public class MyClass
{
public string Prop1 { get; set; }
public int Prop2 { get; set; }
public Field<TValue>[] FieldArray { get; set; }
}
I mean, I want to be able to have a array
of Field’s generic, but this last example is not valid for the compiler.
My ultimate goal is something like this:
var myClassObject = new MyClass();
myClassObject.Prop1 = "Teste";
myClassObject.Prop2 = 10;
myClassObject.FieldArray = new Field<TValue>[10];
myClassObject.FieldArray[0] = new Field<string>();
myClassObject.FieldArray[0].Name = "Field1";
myClassObject.FieldArray[0].Value = "Value1";
myClassObject.FieldArray[1] = new Field<int>();
myClassObject.FieldArray[1].Name = "Field2";
myClassObject.FieldArray[1].Value = 2;
Does language allow you to do something like that? What would be the right way?
Instead of
TValue
, wouldn’t it be better to useobject
?– Felipe Avelar
@Felipeavelar no. never.
– Maniero
I wish I could force a stronger type. I think the
object
very subjective, but I believe it will be the way...– Jedaias Rodrigues
I understand you want to, the strongly typed type, the problem is that you want to vary this type within an array and this is problematic. Of course this will require some greater complexity in dealing with types, but, I imagine, within an array is not feasible...
– Felipe Avelar
@Jedaiasrodrigues You want the same instance of
MyClass
has arrays ofField
with different types?– Jéf Bueno
Exactly @LINQ ! Is it possible?
– Jedaias Rodrigues
@Jedaiasrodrigues I’m not a great C#connoisseur, but I think this is not possible (at least not in the way you thought) because the types need to be known at compile time and this dynamism you need does not allow it.
– Jéf Bueno
@LINQ still thank you very much for your collaboration, I believe I will have to use
object
as @Felipeavelar commented.– Jedaias Rodrigues
Only a pitaco: between
object
anddynamic
I would go fromobject
, @Jedaiasrodrigues– Jéf Bueno