I'm learning C#! (please help)


#1

I mentioned elsewhere, elsewhen, that I’ve recently been drafted into a low-key gamedev team, working in Unity/C#. They’ve got me working on a serious data-crunching item at the moment, and I have SEVERAL questions.

Here’s one of them, for now:

Right now I have a class that I built to be fairly generic because this project involves dealing with many data items which all have a nearly-identical signature except for the datatype they contain, so I just made one class, which privately has a field each for all the possible datatypes.

What I want is to give this class a public Value property, which will just evaluate to the proper datatype on the fly. Is this possible/acceptable in C#?


#2

Generics can help you out here:

public class BaseClass<T> {
  public T Value { get; set; }
}
public class SubclassTypeA : BaseClass<TypeA> {}
public class SubclassTypeB : BaseClass<TypeB> {}

If you need the T type to conform to an interface or be a subclass of something, you can do something like:

public class BaseClass<T> where T : IComparable { ... }

I haven’t tried this code out because I don’t have any work stuff installed at home but this is how I recall it should work. Go look up generics documentation if you need more info really.

edit: oh I should mention you can just use BaseClass<TypeA> just as if it was a class by itself to save yourself having to write / generate subclasses for all the value types you need to support, as long as you don’t need to extend it with additional type-specific behavior. SubclassTypeA and SubclassTypeB in my example only serve as nicer type aliases


#3

These definitely sound like they’ll put me on the right track! thanks!