Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping generic type in c#

Tags:

c#

generics

I need to make the graph and I want to the edges and the vertices to be generic type

public interface IVertex<TVertex, TEdge>
        where TVertex : IVertex<?>
        where TEdge : IEdge<?>
{
    bool AddEdge(TEdge e);
    TEdge FindEdge(TVertex v);
}

public interface IEdge<TVertex> where TVertex : IVertex<?>
{
    TVertex From { get; }
}

But, the edge required the vertex type and the vertex required the edge type What should I do?

like image 715
AnZeky Avatar asked Feb 23 '16 16:02

AnZeky


People also ask

What are generics in C?

C # in Telugu Generics allow you to define the specification of the data type of programming elements in a class or a method, until it is actually used in the program. In other words, generics allow you to write a class or method that can work with any data type.

Is string a generic type?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.

How do you define generic type?

Definition: “A generic type is a generic class or interface that is parameterized over types.” Essentially, generic types allow you to write a general, generic class (or method) that works with different types, allowing for code re-use.

What is generic type arguments?

The generic argument list is a comma-separated list of type arguments. A type argument is the name of an actual concrete type that replaces a corresponding type parameter in the generic parameter clause of a generic type. The result is a specialized version of that generic type.


2 Answers

I think you're making it more complicated then it needs to be.
Would something like this work?

public interface IVertex<T>
{
    bool AddEdge(IEdge<T> e);
    IEdge<T> FindEdge(IVertex<T> v);
}

public interface IEdge<T>
{
    IVertex<T> From { get; }
}
like image 81
Dennis_E Avatar answered Sep 23 '22 18:09

Dennis_E


While it's arguable whether or not it's actually a good idea, there's nothing the compiler minds about such "looping" definitions:

interface IVertex<TVertex, TEdge> where TVertex : IVertex<TVertex,TEdge>
                                  where TEdge : IEdge<TVertex,TEdge>
{

}

interface IEdge<TVertex, TEdge> where TVertex : IVertex<TVertex, TEdge>
                                where TEdge : IEdge<TVertex, TEdge>
{

}

Then you can write, for example:

class FooVertex : IVertex<FooVertex,BarEdge>
{

}

class BarEdge : IEdge<FooVertex,BarEdge>
{

}
like image 31
Ben Aaronson Avatar answered Sep 23 '22 18:09

Ben Aaronson