Following is the code that I have been trying to deploy. As you can see I am deploying a blank interface to make a special datatype “mydatatype” for the list “mylist”.
And in the output I expect the assigned values to be displayed. But I am getting gibberish data. Can somebody explain?
public class list
{
interface mydatatype
{
}
public class mystring : mydatatype
{
public string mystrings{ get; set; }
}
public class myint : mydatatype
{
public int myints{ get; set; }
}
public class mydouble : mydatatype
{
public double mydoubles{ get; set; }
}
public static void Main()
{
List<mydatatype> mylist = new List<mydatatype>
{
new mystring(),
new myint(),
new mydouble(),
};
mystring ab = new mystring();
myint mi = new myint();
mydouble mf = new mydouble();
ab.mystrings = "asdf";
mi.myints = 12;
mf.mydoubles = 12.223;
mylist.Add(ab);
mylist.Add(mi);
mylist.Add(mf);
foreach (mydatatype element in mylist)
{
Console.WriteLine(element);
}
Console.ReadLine();
}
}
}
“gibberish data” isn’t a real error description…
However, what is happening here is that
Console.WriteLine(element);is the same asConsole.WriteLine(element.ToString());. Because you haven’t overriddenToStringin your classes, it will output the class names instead of the values. You would do that like this: