iko popo
iko popo

Reputation: 57

Generic Values assign datatype in list

my first question regarding generics https://stackoverflow.com/posts/comments/115132005?noredirect=1

Now I am unsure how to assign data when returning them to a List.. some are string and some ImageSource

 var dataFields = new List<DataField<string>>();

 if ( imageFront != null )
            {
                var data = DataField<ImageSource>.DocumentFront;
                data.Value = ImageSource.FromStream(() => imageFront.AsPNG().AsStream());
                
                dataFields.Add(data);
            }

but this way I can't add the data as its image source to string even if I tried to convert it. Not sure if that would even be a good way to do it.Can you please advise one how to achieve this?

Upvotes: 0

Views: 53

Answers (1)

A possible solution is to use an interface in your "DataField" class, example (you need to adapt it to your needs):

1- Interface:

public interface IDataType
{
    string GetValue();
}

2- Class (Datatype):

public class DataType<T> : IDataType
{
    public T Value { get; set; }
    public DataType(T value)
    {            
        Value = value;
    }

    public string GetValue()
    {
        return Value.ToString();
    }
}

3- Use

var list = new List<IDataType>();
list.Add(new DataType<string>("Hello"));
list.Add(new DataType<int>(1));
list.Add(new DataType<bool>(true));
list.ForEach(dataType =>
{
    Console.WriteLine(dataType.GetValue());
});

Upvotes: 1

Related Questions