To be honest I wasn't sure how to word this question so forgive me if the actual question isn't what you were expecting based on the title. C# is the first statically typed language I've ever programmed in and that aspect of it has been an absolute headache for me so far. I'm fairly sure I just don't have a good handle on the core ideas surrounding how to design a system in a statically typed manner.
Here's a rough idea of what I'm trying to do. Suppose I have a hierarchy of classes like so:
abstract class DataMold<T>
{
public abstract T Result { get; }
}
class TextMold : DataMold<string>
{
public string Result => "ABC";
}
class NumberMold : DataMold<int>
{
public int Result => 123
}
Now suppose I want to make a list of item where the items can be any kind of mold and I can get the Result
property of each item in a foreach
loop like so:
List<DataMold<T>> molds = new List<DataMold<T>>();
molds.Add(new TextMold());
molds.Add(new NumberMold());
foreach (DataMold<T> mold in molds)
Console.WriteLine(mold.Result);
As you probably already know, that doesn't work. From what I've read in my searches, it has to do with the fact that I can't declare the List to be of type DataMold<T>
. What is the correct way to go about something like this?
interface IDataMold<T>
would work as a List<IDataMold<T>>`, if an interface suites your needs. – Cohbertclass TextMold : DataMold<string> { public string Result { get; set; } }
OR it would just have a getter:class TextMold : DataMold<string> { public string Result { get; private set; } }
– Vikki