Tobias Weger
Tobias Weger

Reputation: 135

Subclass of Generic in C#

I have a Generic Class in Unity and I want to be able to have an additional variable in it when I use i.e. the type int.

My generic class Grid<int>:

public class Grid<T>
{
    public T[] array;
}

I've tried to extend my generic class Grid<T> with a class named Grid<int> to be able to add the variable there:

public class Grid<int> : Grid<T>
{
    string additionalVariable;
}

But that throws the error

The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)

How can I achieve that creating a new Grid<int> class gives me access to Grid<int>.additionalVariable, but i.e. new Grid<float> wouldn't?

Upvotes: 0

Views: 98

Answers (2)

John Wu
John Wu

Reputation: 52240

When a developer "extends" a class, that actually means they are creating a new class that extends the existing one. For example, to add a string variable, you might have this:

public class Grid<T>
{
    public T[] array;
}

public class ExtendedGrid<T> : Grid<T>
{
    string additionalVariable;
}

var grid = new Grid<int>();
grid.additionalVariable = "Hello world"; //Error: method does not exist

var extendedGrid = new ExtendedGrid<int>();
extendedGrid.additionaVariable = "Hello world"; //Works

When you extend the class, you have the option of leaving the generic type open (as it is above) or closed (as in this following example).

public class Grid<T>
{
    public T[] array;
}

public class ExtendedGrid : Grid<int>  
{
    string additionalVariable;
}

var extendedGrid = new ExtendedGrid(); //No need to specify int as the type argument

If you don't want to modify the original class, but want to add a member to it, your only option is to add an extension method:

static public class ExtensionMethods
{
    public static string GetAdditionalVariable<T>(this Grid<T> source)
    {
        return "Hello world";
    }
}

var grid = new Grid<int>();
var s = grid.GetAdditionalVariable();

Unfortunately there is no such thing as an extension field, so I'm guessing you want one of the first two examples.

Upvotes: 1

Immorality
Immorality

Reputation: 2174

If you want to make a concrete class, you should give the class a unique name and define the type parameter in the inheritance definition.

public class IntGrid : Grid<int>
{
     // Yourvariablehere
} 

Upvotes: 1

Related Questions