Generics...

Status
Not open for further replies.

lobobo

Ars Scholae Palatinae
778
Hello,

I'm using generics in C# and I have several questions.

Code:
class TestClass<T>
{
    public T ReturnSomeData(T SomeArgument)
    {
        return SomeArgument.DataReturnMethod();
    }
}

The above generates a compile-time error because .DataReturnMethod is "invisible", it's a method for a specific class such as...

Code:
class DataClass
{
    private int Data;
    
    public int DataReturnMethod()
    {
        return Data;
    }
}

So if I'm understanding this correctly, this behavior is prohibited because this would violate the reason for using generics in the first place? If I was using the example TestClass with int for example and not DataClass (ex: TestClass<int> as opposed to TestClass<DataClass>), it would be nonsense to call DataReturnMethod on an integer type since that method is undefined for the integer value type. Am I right or just wrong?
 

andrewme

Senator
7,120
Subscriptor
lobobo":3qro0syf said:
So if I'm understanding this correctly, this behavior is prohibited because this would violate the reason for using generics in the first place? If I was using the example TestClass with int for example and not DataClass (ex: TestClass<int> as opposed to TestClass<DataClass>), it would be nonsense to call DataReturnMethod on an integer type since that method is undefined for the integer value type. Am I right or just wrong?

It sounds like you have it right.
 

technophile

Ars Legatus Legionis
23,768
Bhelyer is correct, any use of a type T must be the same for all instances of T in a given method. You can use multiple type parameters, although for this purpose it's awkward:

Code:
public R SomeMethod(T SomeArgument, R returnType)
{
    return SomeArgument.SomethingThatReturnsAnR();
}

The above will still fail to compile, though, because the compiler doesn't know if T will always have a SomethingThatReturnsAnR method.

To resolve that, you can make calls to specific methods allowable using either a base class or interface, for example:

Code:
public interface ISomething
{
    int SomethingThatReturnsAnInt();
}
public int SomeMethod(T SomeArgument) where T: ISomething
{
    return SomeArgument.SomethingThatReturnsAnInt();
}
 

drogin

Ars Tribunus Angusticlavius
8,283
Subscriptor++
Well, at the end of the day you have to remember that unlike templates in C++, Generics in C# are runtime constructs.

There for the compiler isn't able to determine that your method actually exists on all the uses of that generic.

What you can do, is define an interface with whatever the logical set of operations are, then require any T to implement it.

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string juice = "juice";
            string yellow = "yellow";

            var paint = ContainerPacker<PaintCan>.Pack(yellow);
            var jug = ContainerPacker<Jug>.Pack(juice);
        }
    }

    public interface IOpenable
    {
        void Open();
    }

    public interface ICloseable
    {
        void Close();
    }

    public interface IFillable
    {
        void Fill(object stuff);
    }

    public class ContainerPacker<TContainer> where TContainer : IOpenable, ICloseable, IFillable, new()
    {
        public static TContainer Pack(object stuff)
        {
            var container = new TContainer();

            container.Open();
            container.Fill(stuff);
            container.Close();

            return container;
        }
    }

    public class PaintCan : IOpenable, ICloseable, IFillable
    {
        public void Open() { }
        public void Close() { }
        public void Fill(object stuff) { }
    }

    public class Jug : IOpenable, ICloseable, IFillable
    {
        public void Open() { }
        public void Close() { }
        public void Fill(object stuff) { }
    }
}

Not a sterling example, but it should get the point across. You can also specify a base class instead of an interface, but in all honestly the interface is typically more flexible.

Also, note the "new()" constraint at the end. In my example the generic class instantiates new TContainers, and therefore needs to call the default constructor. The "new()" constraint essentially forces the generic argument to have a default constructor.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Well, at the end of the day you have to remember that unlike templates in C++, Generics in C# are runtime constructs.

That's a bit of a gross oversimplification. There's plenty in the compiler that deals with the type of the generic arguments, mainly when using constraints but there's still a bunch of logic for making sure plain generics deal with things like boxing, that the specific types used agree (and/or are co/contra variant as required in c# 4) for example.

The important difference to the end user here is that they differ from c++ templates in that they are not exposed as if any use of one was simply* substituted into the code textually and then compiled. Instead each generic class is compiled to intermediate form and then used in much the same way as normal classes with the free types filled in as appropriate, the JIT then does some magic to handle value types later and share common code amongst reference types.

If you know f# it's conceptually like the difference between a generic function and an inline one.

* well as simple as a Turing complete behemoth can ever be
 

drogin

Ars Tribunus Angusticlavius
8,283
Subscriptor++
ShuggyCoUk":2prsp721 said:
Well, at the end of the day you have to remember that unlike templates in C++, Generics in C# are runtime constructs.

That's a bit of a gross oversimplification. There's plenty in the compiler that deals with the type of the generic arguments, mainly when using constraints but there's still a bunch of logic for making sure plain generics deal with things like boxing, that the specific types used agree (and/or are co/contra variant as required in c# 4) for example.

The important difference to the end user here is that they differ from c++ templates in that they are not exposed as if any use of one was simply* substituted into the code textually and then compiled. Instead each generic class is compiled to intermediate form and then used in much the same way as normal classes with the free types filled in as appropriate, the JIT then does some magic to handle value types later and share common code amongst reference types.

If you know f# it's conceptually like the difference between a generic function and an inline one.

* well as simple as a Turing complete behemoth can ever be

I agree that it is an oversimplification, but it is really important to realize. It's also why the OP can't "just do" what he wanted.
 

Prototyped

Ars Legatus Legionis
11,126
Question: why would you even bother with a generic type if you require it to implement an interface?

i.e.

Code:
public interface ISomeDataReturner
{
    public int dataReturnMethod();
}

class TestClass
{
    public ISomeDataReturner ReturnSomeData(ISomeDataReturner SomeArgument)
    {
        return SomeArgument.dataReturnMethod();
    }
}

i.e. restricting the type of the generic parameter makes it not so generic.

(Though I imagine if the interface itself were generic parameterized on a type, this would make more sense.)

Code:
public interface ISomeDataReturner<T>
{
    public int dataReturnMethod();
}

class TestClass<T>
{
    public ISomeDataReturner<T> ReturnSomeData(ISomeDataReturner<T> SomeArgument)
    {
        return SomeArgument.dataReturnMethod();
    }
}
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Question: why would you even bother with a generic type if you require it to implement an interface?

* It's the only way you can ever have a variable which indicates multiple (independent) interfaces are implemented without knowing the exact type.
* You can also constrain other things at the same time (though still not enough)
* new()
* class (technically can be assigned null)
* struct (technically cannot be assigned null)
* sub/base constraints (which I have almost never used)
* The interface itself is generic in another type (likely with self referentiality to the original types)
* If the generic type used is a struct then calls to interfaces it implements will not result in a boxing operation

There are other compelling reasons for the end users of said classes like the result can be used with multiple specific instances while keeping full type information (no casting).
 
Status
Not open for further replies.