I am trying to design a class that will be flexible enough to chart data about different kinds of data. I’m new to OOP in C#, so I’m fumbling around trying to achieve this using some combination of generics, delegates and classes.
Here’s the class that I’ve written so far:
using System;
using System.Collections.Generic;
namespace Charting
{
public class DataChart<T>
{
public Func<T, object> RowLabel { get; set; }
}
}
And here’s how I’m trying to call it:
var model = new DataChart<MyClass>()
{
RowLabel = delegate(MyClass row)
{
return String.Format("{0}-hello-{1}", row.SomeColumn, row.AnotherColumn);
}
};
The problem with this approach is that I’d have to explicitly cast the object emitted by RowLabel. I was hoping I could somehow make the output type a generic and add constraints to it, like so:
public class DataChart<T>
{
// The output of the RowLabel method can only be a value type (e.g. int, decimal, float) or string.
public Func<T, U> RowLabel where U : struct, string { get; set; }
}
Is this possible? And if so, how do I do it? Thanks in advance!
You can do some of this.
First, genericizing the output: just add another type parameter to the class.
But those type constraints you mentioned do not make sense. Type constraints are “and”-ed, not “or”-ed. A
stringis not astruct, so you can’t confine it to that specific combination of types. It will still work if you leave it unconstrained, although you lose some compile-time safety.Edit: Also, it turns out you can’t specify
stringas a type parameter, anyway. It’s a sealed class! Having a generic that only accepts types of a sealed class would be pointless, and the compiler prevents it.