description | title | ms.date | ms.topic | helpviewer_keywords | ms.assetid | |
---|---|---|---|---|---|---|
Learn more about: Consuming Generics (C++/CLI) | Consuming Generics (C++/CLI) | 10/12/2018 | reference |
| e6330ef5-e907-432e-b527-7a22f5899639 |
Generics authored in one .NET (or UWP) language may be used in other languages. Unlike templates, a generic in a compiled assembly still remains generic. Thus, one may instantiate the generic type in a different assembly and even in a different language than the assembly in which the generic type was defined.
This example shows a generic class defined in C#.
// consuming_generics_from_other_NET_languages.cs// compile with: /target:library// a C# programpublicclassCircularList<ItemType>{classListNode{publicItemTypem_item;publicListNodenext;publicListNode(ItemTypeitem){m_item=item;}}ListNodefirst,last;publicCircularList(){}publicvoidAdd(ItemTypeitem){ListNodenewnode=newListNode(item);if(first==null){first=last=newnode;first.next=newnode;last.next=first;}else{newnode.next=first;first=newnode;last.next=first;}}publicvoidRemove(ItemTypeitem){ListNodeiter=first;if(first.m_item.Equals(item)){first=last.next=first.next;}for(;iter!=last;iter=iter.next)if(iter.next.m_item.Equals(item)){if(iter.next==last)last=iter;iter.next=iter.next.next;return;}}publicvoidPrintAll(){ListNodeiter=first;do{System.Console.WriteLine(iter.m_item);iter=iter.next;}while(iter!=last);}}
This example consumes the assembly authored in C#.
// consuming_generics_from_other_NET_languages_2.cpp// compile with: /clr #using <consuming_generics_from_other_NET_languages.dll> usingnamespaceSystem;classNativeClass {}; ref classMgdClass {}; intmain() { CircularList<int>^ circ1 = gcnew CircularList<int>(); CircularList<MgdClass^>^ circ2 = gcnew CircularList<MgdClass^>(); for (int i = 0 ; i < 100 ; i += 10) circ1->Add(i); circ1->Remove(50); circ1->PrintAll(); }
The example produces this output:
90 80 70 60 40 30 20 10