How to declare an array containing a generic type?

Let's say I have the following type:

public class Field<T> { public string Name { get; set; } public T Value { get; set; } } 

How can I declare a variable that will contain an array of such fields? I tried the following:

 var customFields = new Field[] { new Field<string> { Name = "nickname", Value = "Bob" }, new Field<int> { Name = "age", Value = 42 }, new Field<DateTime> { Name = "customer_since", Value = new DateTime(2000, 12, 1) } }; 

but I get the following exception for compilation:

Using the generic Field type requires 1 type argument

I also tried var customFields = new Field<object>[] , but I get the following errors:

Cannot Implicitly Convert Field Type to Field

Cannot Implicitly Convert Field Type to Field

Cannot Implicitly Convert Field Type to Field

+6
source share
2 answers

As Matthias said, this is not possible because Field<int> and Field<string> are completely different types. What you can do is:

Create a Field base that is not shared:

 public class Field { public string Name { get; set; } } public class Field<T> : Field { public T Value { get; set; } } 

And then:

 var customFields = new Field[] { new Field<string> { Name = "nickname", Value = "Bob" }, new Field<int> { Name = "age", Value = 42 }, new Field<DateTime> { Name = "customer_since", Value = new DateTime(2000, 12, 1) } }; 

As Matthias commented, getting a Value for different types will require a reduction. If there is a certain logic for each type of Value to execute, a good way to handle this would be to use the Factory design template. factory will return for each Field correct " FieldHandler<T> ", which will lower, perform the operation and return what is needed.

+13
source

Another thing you can do is simply use a common base class for all of these types - Object.

 class Field { public string Name { get; set; } public Object Value { get; set; } } var customFields = new Field[] { new Field { Name = "nickname ", Value = "Bob" }, new Field { Name = "age", Value = 42 }, new Field { Name = "customer_since", Value = new DateTime(2000, 12, 1) } }; 

However, this will lead to offloading the processing of a certain type to the consumer customFields, but it should be good if the types of values โ€‹โ€‹associated with a specific field name are known.

+2
source

Source: https://habr.com/ru/post/1011558/


All Articles