Click here to Skip to main content
15,867,756 members
Everything / Generics

Generics

generics

Great Reads

by Thomas Nielsen - getCore
This article will take a dive into one of the reasons why code sometimes sands over.
by Muraad Nofal
A haskell monad/(applicative)functor like interface in C# that extends IEnumerable.
by Razi Syed
Easily bind a class to .NET data controls like GridView, FormView, etc., and get an updated object or list back in the code-behind effortlessly.
by Andrew Rissing
How to get that last little nagging line to be covered...

Latest Articles

by Robert P. Howard
How to deserialize a JSON string that contains nested polymorphic objects
by Aram Tchekrekjian
Demystifying generics in C#
by johnniealan
ArcNet Protocol basics
by Bertus van Zyl
A tutorial about generics in C#, aimed at beginners

All Articles

Sort by Score

Generics 

21 Sep 2015 by Thomas Nielsen - getCore
This article will take a dive into one of the reasons why code sometimes sands over.
18 Sep 2013 by Muraad Nofal
A haskell monad/(applicative)functor like interface in C# that extends IEnumerable.
25 Apr 2012 by Razi Syed
Easily bind a class to .NET data controls like GridView, FormView, etc., and get an updated object or list back in the code-behind effortlessly.
2 Apr 2011 by Andrew Rissing
How to get that last little nagging line to be covered...
16 Aug 2011 by Damian Flynn
Here's a couple of gems...From IList to DataTable.From DataTable to array of T.// DataTable: from IListpublic static DataTable ToDataTable(this IList iList){ DataTable dataTable = new DataTable(); PropertyDescriptorCollection propertyDescriptorCollection = ...
2 Sep 2014 by DiponRoy
Let’s see how to make a simple model or Entity mapper using reflections in C#
31 Jan 2015 by Mayur Shah
Markup Extension that allows you to declare Generic classes in Xaml
22 Aug 2013 by OriginalGriff
Neither the Expression or the params are datatypes: the former is similar to Func but returns a tree rather than a value (There is a good description here: http://stackoverflow.com/questions/793571/why-would-you-use-expressionfunct-rather-than-funct[^]).params is a C# keyword that lets you...
5 Sep 2013 by BillWoodruff
I think as you "get to know" Generics, and have a "feeling" for how to use them, you will find them immensely useful. I also predict that your sense of what Generics can be used to do ... and to greatly simplify the coding of ... will come in "stages."So, let me outline a few of what I...
1 Feb 2017 by BrettPerry
A helper class to run functions in an asynchronous pattern using the Func delegate
1 Aug 2011 by Abhinav S
Nothing, as far as your example is concerned.In the first case, you could actually define the array count in the first statement but add values to it later.E.g.List withParentheses = new List[4];withParentheses[0]=1;withParentheses[1]=2;In the second case, you don't have that...
11 Jul 2012 by Sergey Alexandrovich Kryukov
Ah, finally I got it. Maybe an interesting problem, but not making much sense.Here is the thing: you are facing some limitation which is not 100% logically required. Your code sample looks convincing (not many people will really understand your explanation of it, it just so happens that I am...
21 Jul 2014 by Alexandr Stefek
This article show another way to implement generic operators. Vector is in middle of attention.
25 Jul 2014 by Kishor Deshpande
Methods which facilitate the conversion from string to value type
30 May 2011 by Sergey Alexandrovich Kryukov
You don't need a data special structure for the tree. Having such data type in a standard library would be absolutely redundant, because a tree is just a list of some elements which has a "children" member of the same type.Here is the simplest example:using Tree =...
29 Jun 2011 by Abhinav S
Not much I would think - since there is no boxing / unboxing here.Implementing List might just still come out better in terms of performance because there is no need to do any type checking at runtime.Two more interesting reads on this topic -...
13 Aug 2011 by Vano Maisuradze
Very nice!I've modified ToCollection(this DataTable dt) extension function, so if DataTable column names and class property names are different, then you can use this alternative:public static List ToCollection(this DataTable table, Dictionary dic){ List lst = new...
29 Jun 2012 by Sergey Alexandrovich Kryukov
This is something which could called generic specialization, by the analogy with C++ template specialization.It looks like your efforts are useless until you work with generic methods; it is not possible to specialize the implementation via overriding for a concrete type. I want to give you...
15 Aug 2012 by Sergey Alexandrovich Kryukov
The idea is very simple. You almost got it, should just think about it.The kind of late binding you use is of the level of plug-in (your "registered" DLL) and the plug-in architecture. You need to look at it as at the whole architecture, and it all will be clear to you. The think is: the...
30 Nov 2013 by tgrt
vehicles.Find(v => v is Car).Speed();
21 Dec 2013 by OriginalGriff
No, you can't.The whole idea of Generics is that they are type unspecific - they are general purpose rather than linked to a specific class: so you can declare a List class that work as a collection of a generic class, and it will work the same with an integer and an SqlCommand.Declaring...
19 Mar 2014 by Sergey Alexandrovich Kryukov
The idea is simple: you should provide one more parameter (method parameter, not generic parameter): the delegate instance converting the element of the type T1 to the type T2. Your type constraints for T1 and T2 are absolutely redundant and useless. You can work with elements of any types, not...
6 Feb 2015 by Richard Deeming
This is an alternative for "Markup Extension for Generic classes"
2 Aug 2016 by F-ES Sitecore
You need to add the generic definition to the class, and that is then available inside the classclass BackupVirtualDataSource : AbstractVirtualListDataSource
1 Mar 2018 by Richard Deeming
Covariance and Contravariance in Generics | Microsoft Docs[^] It's not a simple topic. :) Imagine a world where I was equivalent to I. That would mean that the following code would work: class Base { } class Derived : Base { } class OtherDerived : Base { } List list =...
15 Nov 2018 by lmoelleb
It doesn't work as the compiler can't check if T is always an int when using IntegerReturner etc. For example, the following call would be valid according to the method signature: factory.CreateValueReturner("IntegerReturner") where it would have to return an IReturnsValue as an...
5 Oct 2020 by Robert P. Howard
How to deserialize a JSON string that contains nested polymorphic objects
20 Nov 2020 by RickZeeland
See: INotifyPropertyChanged.PropertyChanged Event (System.ComponentModel) | Microsoft Docs[^] And also: c# - Implementing INotifyPropertyChanged - does a better way exist? - Stack Overflow[^]
24 Feb 2011 by _Ashish
When we are unsure about what Type a function will return, we should use Object in that scenario.you can achieve this without generic. look at the following code. protected void Page_Load(object sender, EventArgs e) { // method call object ret = method(0); ...
13 Jun 2012 by Member 4548634
Here is my situation. I have a BusinessObjectBase class. I have my business objects defined as: public class Appointment inherits businessObjectBaseThen I made a base collection class defined as Public Class BusinessObjectCollectionBase(of T as {BusinessObjectBase}) ...
19 Jun 2012 by OriginalGriff
Try:Dim MyList as List(Of String) = ReturnMultiple()func(MyList(0), MyList(1))
3 Oct 2013 by BC3Tech
How to constrain generic types to parameterized constructors
19 Mar 2014 by BillWoodruff
I think Sergey "got there" first, and gave you the key insight you need; I suggest you accept his answer.While I am not familiar with the ObjectModel.Collection class, I have written an extension method to convert a Generic List of one Type to a Generic List of another Type:public static...
14 Nov 2014 by Tomas Takac
Signature of an event handler is usually this:void HandleThis(object sender, MyEventErgs args);You need to create a delegate for that in order to use it with an event:public delegate MyEventHandler(object sender, MyEventErgs args);And your event declaration is this:public event...
24 Nov 2014 by BillWoodruff
I am averse to refactoring code when that's part of my consulting practice, but I do want to give you some suggestions:1. more Generic ? For this I think that 'ind 'khia, and 'app objects would have to all implement a common Interface that you could program with/to, to make a kind of "class...
5 Jan 2015 by PIEBALDconsult
The field a is never set.
31 Jul 2015 by Wendelius
In order to fix the errors, you need to add using System.Data.SqlClient;or you need to specify the namespace for the classes, for exampleSystem.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection("Your Connection String");Also ensure that System.Data...
26 Sep 2015 by OriginalGriff
The problem is that you are are redefining a new T type separate from the one declared on the class level. Try with one less generic: class A { private T[] stuff; public A(int n) { stuff = new T[n]; } public T get(int i) { return...
31 Oct 2015 by Maciej Los
Problem is here:You use 'Item No' and 'Item Name' names to define headers. But in your (NOT-generic) class, you have only INo and IName. What it means? You have to define datafields to bind. See: BoundField...
21 Jul 2016 by Bernhard Hiller
Quote:and i need to pass body as parameter to another methodThat other method needs to be generic, too; or at least accept a type compatible with T. Otherwise, the encapsulation in the generic class does not make sense.
11 Sep 2017 by Graeme_Grant
I think that this is what you are trying to do: Tuple> TupleFactory(string value, List values) { return new Tuple>(value, values); } To use: var listOfTuples1 = TupleFactory("test value", new List { "test value 1", "test...
2 Jan 2018 by F-ES Sitecore
You can do this using reflection public static Report GetReport(ReportTypes reportType) { Type t = Reports[reportType]; MethodInfo method = typeof(ReportFactory) .GetMethods(BindingFlags.Static | BindingFlags.NonPublic) .First(m => m.Name == "Create"); MethodInfo...
14 Apr 2018 by OriginalGriff
The question mark indicates it's not a long any more, but a nullable long. As you know, long variables are value types, and value types cannot contain null - so you can use the question mark to create a special version of a value type that can also contain null: Nullable Types (C# Programming...
16 Jun 2018 by George Swan
You can do most of the work in one line of code. private void RenumberPreferredSequence(Item record) { int seq = 2; foreach(var itemVendor in record.ItemVendors) { itemVendor.PreferredSequence = itemVendor.PrimaryVendor ? 1 : seq++; } }
19 Feb 2020 by Tomas Takac
I'm offering a more object-oriented solution to your problem. Read about double-dispatch design pattern. In your case this goes like this: 1) I'd remove the static methods. You could adapt this to use the static processors but this is how I...
23 Oct 2020 by Patrick Skelton
Can someone please tell me where I am going wrong with the following code? (I'm hoping the answer is not 'Everywhere'.) My problem is that I can't figure out how to write the factory function to create actual instances of the graphics objects....
23 Oct 2020 by F-ES Sitecore
I added a comment to your other thread, you're not really using the factory pattern correctly. You need to think about what the calling code is doing and what factory patterns are for. The factory has to return an object that supports an...
20 Nov 2020 by BillWoodruff
Calling some code when Fields change value is not going to happen: change the Fields into Properties. With individual Properties, you can implement the INotifyPropertyChanged interface in your class, and then modify the 'set methods of...
12 Jun 2021 by Greg Utas
In taking a few minutes to scan your code, it looks like you're trying to sort strings. But you create them by passing them as C strings ("Charlie" and "Bob"). Doing this creates a temporary string as an argument, and it disappears right after...
11 Dec 2010 by DarkFigure
Hi Andi.I see your point, but being not much clear to me, the progress of C# and .NET and within the scope of my readings about covariance and contravariance I thought it could be possible.It is really simple though if I do not mind to use generics at the very base of my class hierarcy....
28 Mar 2011 by Xmen Real
Use IList, eg.private IList _AvailableAssignments = null; public IList AvailableAssignments { get { return _AvailableAssignments; } set { _AvailableAssignments = value; ...
30 May 2011 by Monjurul Habib
http://www.google.com/#hl=en&sugexp=ldymls&xhr=t&q=generic+tree+c+sharp&cp=14&pq=generic%20c%23%20&pf=p&sclient=psy&source=hp&aq=0v&aqi=&aql=&oq=generic++tree+C%23+&pbx=1&bav=on.2,or.r_gc.r_pw.&fp=f99e8c741a251b45&biw=1024&bih=558[^]
30 May 2011 by Espen Harlinn
Just a followup on SAKryukovs' answer, how about:public class TreeNode{ public class ChildList : BindingList > {} private ChildList children; private T data; public TreeNode() { children = new ChildList(); } public TreeNode(T...
1 Nov 2011 by Jephunneh Malazarte
Generic class:public class GenericEntityMapping{ public T Map(XmlNode xNode, T entityObject) { //FYI. //PropertyInfo[] entityProperties = typeof(T).GetProperties(); //foreach (PropertyInfo pInfo in entityProperties){...} //somewhere in...
1 Nov 2011 by Sergey Alexandrovich Kryukov
For a type, being generic and begin static are not related. Both generic and non-generic types can be static or not static.—SA
1 Nov 2011 by Jephunneh Malazarte
Hello SAKryukov,Thanks for the quick reply.I found the solution:MethodInfo method = typeof(GenericEntityMapping).GetMethod("Map");MethodInfo generic = method.MakeGenericMethod(Type.GetType(pInfo.PropertyType.FullName));object[] objParam = { node,...
26 Dec 2011 by Sergey Alexandrovich Kryukov
Polymorphism is not a phenomena which can be allowed or prohibited. Generics cannot change the situation, because they have nothing to do with polymorphism, because they have nothing to do with inheritance, "virtual" and late binding. Generics are static; any type which can be instantiated...
7 May 2012 by CPallini
I don't see direct issues related with this choice. However you have at least two places where threads start (and possibly stop). This additional complexity, in my opinion, should be justified by an overall improvement of your design.My two cents.
7 May 2012 by Sergey Alexandrovich Kryukov
There is practically no difference between main thread and other threads. Strictly speaking, there is not such thread as "main", this is merely some initial thread, the one where the entry point is executed. This kind of design cannot add any hassles or problems. There is only one thing: each...
18 May 2012 by VJ Reddy
The reason is that the DataGridView can display only one level of Tabular data. It cannot show Tables nested inside a cell. To get the desired result modify the code as follows:namespace ShowEntityOfInherited{ public partial class Form1 : Form { public Form1() ...
27 May 2012 by Wendelius
That means, phe parameterless constructor must exist, one way or another.Consider the following:public class Test1 { public Test1(string somestring) { }}public class Test2 where T1 : new() {}Now if I try to define an instanceTest2 testInstance = new...
20 Jun 2012 by Pankaj Nikam
I guess the Return statement is missing from the Function calculate.Please include the following line before the End FunctionReturn Sol So the overall code will look like... :Private Function calculate(ByVal eid As String, ByVal fn As String, ByVal from As String) As List(Of...
20 Aug 2012 by Clifford Nelson
You have two ways to associate Employees and Departments using objects. One is to have a Department property in the Employee object and the other is to have a collection of Employee objects in the Department object. You will also, at the minimum have either a collection of all Department or all...
26 Sep 2012 by cpquest
Hi all,i have implemented a Extension method for ICollection f in project that bacically i am trying to do some datagrid related operation on ApplicationIdle state. here is the code. public static class CollectionExtension { /// /// Set item Binding to...
26 Sep 2012 by Clifford Nelson
I have used the Dispatcher, and it does not seem to be very reliable. Had much more luck with tasks: First get a TaskScheduler from somewhere that is on the UI thread:TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();Then in the place you need to make changes...
5 Oct 2012 by Bryan Lyman
Generic list wrapper that returns a smaller strongly typed sub-list which modifies the parent-list when changed, without using events
8 Nov 2012 by mehrdad_safa
hi!you can read all text from the file and split it to sentences using String.Split method. like this:foreach(string sentence in System.IO.File.ReadAllText(d).Split(new char[]{'.',',','!','?',';'}) { if (!lst.Contains(sentence )) { ...
26 Feb 2013 by Andreas Gieriet
This code compiles: class MyClass{ public T Value { get; private set; } public MyClass(T value) { Value = value; } public static int Func(int x) { MyClass inst = new MyClass(x); ... return inst.Value; } ...
30 Jun 2013 by Sergey Alexandrovich Kryukov
You are confusing method parameters and generic parameters. Read about both, to see how they work. Your InitializeComponent is the auto-generated code, generated from your XAML. It is designed to work with classes derived from the class Window, and the constructor should have no...
30 Jun 2013 by Elan.Cao
To #1:I do like this now:public partial class Choosen : Window where T1 : UserControl, new() where T2 : Entities, new(){public Choosen(T1 usercontrol, List list, bool canChooseAll) { InitializeComponent(); }}to do like...
25 Sep 2013 by pasztorpisti
There are many ways to implement for example containers. None of them are so clean as using templates/generics.1. One trick is using void pointers in the container implementation and later you store pointers to the items you want to store in the container. Of course you have to do ugly casts...
1 Oct 2013 by Sergey Alexandrovich Kryukov
The question itself is incorrect. You cannot possibly convert this fragment of code to generic. You can add a generic parameters to a type declaration (it will make an incomplete generic type, a complete type should be obtained by instantiation with concrete generic parameters) or to a method...
5 Nov 2013 by Ron Beyer
What you are probably wanting to do is this:public bool post(T model,Int id){ //code to set common fields //code to check which type using type of if(model is candidatecomment) { ((candidatecomment)model).candidateId = id; }else { ...
6 Mar 2014 by OriginalGriff
You just list the values: List l1 = new List { "heelo", "goodbye" }; List l2 = new List { "heelo", "goodbye" }; List l3 = new List { 1, 2, 3, 4 }; var x = AllCombinationsOf(l1, l2); ......
9 Oct 2014 by Richard Deeming
You might be able to get away with specifying the correct generic type name:System.Collections.Generic.List`1[BusinessObject.Products]However, the simplest solution would be to use a custom non-generic collection class:using System;using System.Collections.Generic;namespace...
15 Nov 2014 by BillWoodruff
The Generic 'event delegate Type (available since .NET 2.0) that uses where 'T may be a Type that inherits from (whose base class is) EventArgs is used when you need to pass custom data from the context in which the Event is triggered to the "consumers" of the Event who create EventHandlers...
24 Feb 2015 by Mohibur Rashid
You have lots of ambiguity in your code. Such as:On stackNew function you have passed sizeof (char*)sizeof any pointer will return 4.you tried to free stringStack but you never allocate it. You have allocated stringStack->elemsin stackPop function you are trying to set value to...
31 Jul 2015 by DamithSL
1. Include using statements for system.Data and System.Data.SqlClient as belowusing System.Data;using System.Data.SqlClient;2. Fill Data Set using stored procedure using(SqlConnection conn = new SqlConnection("ConnectionString")) { SqlCommand...
1 Aug 2015 by DamithSL
1. Try yourself first, if you have proper connection string and stored procedure which returning multiple tables, you will get DataSet with multiple tables.2. DataSet can have multiple DataTables, if your stored procedure returning multiple tables, then you can access each table by using...
22 Jul 2016 by Philippe Mori
You should probably add the following function to your Envelope class:public abstract Type GetBodyType();And then implement it in the derived class Envelope:return typeof(T);Or maybe you need to reconsider the whole design... Are you trying to convert a pattern from another language?
21 Aug 2016 by Afzaal Ahmad Zeeshan
The following type is not possible, static List passed(List)Because static cannot be generic. Remove the infront of static and you are left with the same generic function declaration that you had previously. :laugh: If you want to use generic return types...
19 Oct 2016 by johannesnestler
So which error? - what you do here makes no sense to me... - a generic type that represents a list (hard to know from your naming) that contains a generic list of the same type - is this what you wanted?But anyway I guess that your problem is just the declaration of RemplirDataGridList - it...
10 Dec 2016 by gfazzola
In this article I will explain the implementation of an infrastructure to host and manage windows services in a practical and interactive way.As a practical example of the solution will be implemented a dynamic ip update client of DucDNS
18 May 2017 by jimmson
Hello, there's not much to simplify here. You are calling a different method in each of them. That's not something that generic can help you with.
18 May 2017 by Dave Kreskowiak
Those methods are only similar in structure, not in function. The problem is each method deals with different data and executes different code depending on different conditions imposed on that data. There's no way to condense that code down to a single method in any elegant manner.
11 Sep 2017 by F-ES Sitecore
You could try using inheritance but Solution 1 is probably better if it can be used public class MyData : List>> { } MyData dataA = new MyData(); dataA.Add(new Tuple>("String 1", new List { "A", "B", "C" }));...
23 Sep 2017 by CPallini
Quote: Do you know whether there is a way to access to private class from outside package? You have to modify the bagPackage source. You could, for instance, use a public interface to expose the private class, see java - Exporting non-public type through public API - Stack Overflow[^].
24 Oct 2017 by Richard Deeming
You'd need a non-generic base class or interface containing the members of your class which don't rely on the generic type parameter. Public MustInherit Class EventSerializer ' Non-generic members here... Public Shared Function Create(Of TEvent As {New, IEvent})(ByVal evt As...
2 Jan 2018 by Thomas Daniels
They way you're using generics, isn't supported in C#. Between , the name of a type is expected, not a Type object that isn't known at compile-time. To create something based on a Type object, you can use Activator.CreateInstance[^].
20 Jun 2018 by Clifford Nelson
Not sure if this is what you want, but think so: private void RenumberPreferredSequence(Item record) { var seq = 2; foreach (var itemVendor in record.ItemVendors) { itemVendor.PreferredSequence = 0; if...
17 Jan 2020 by phil.o
You could define MyBaseLogicClass as public abstract class MyBaseLogicClass where T : MyBaseBusinessObjectClass { public abstract void PrintParamName( T param ); } public class LogicHandlingOnes : MyBaseLogicClass { // ... } public class LogicHandlingTwo :...
17 Jan 2020 by F-ES Sitecore
The generic type "T" is defined when you create the class so it has to go on the class definition public abstract class MyBaseLogicClass { public abstract void PrintParamName(T param); } public class LogicHandlingOnes : MyBaseLogicClass { public override void...
26 Feb 2020 by Richard Deeming
GetProperty returns a PropertyInfo; you need to call the GetValue method on that PropertyInfo, passing in the instance of the class, to get the actual value of the property. But there's a much simpler solution: have your entity classes implement...
21 Oct 2020 by F-ES Sitecore
Try something like public abstract class GraphicsBase where T : LogicBase { public GraphicsBase(T logicObject) => StronglyTypedLogicObject = logicObject; public LogicBase LogicObject => StronglyTypedLogicObject; public virtual T...
23 Oct 2020 by RickZeeland
Maybe this will be helpful: Generic Factory Class[^]
23 Oct 2020 by Richard MacCutchan
Snesh Prajapati[^] has written a nice set of articles at Factory Patterns - Simple Factory Pattern[^].
24 Oct 2020 by BillWoodruff
fyi: the DoFactory design-pattern collection (commercial software) has some good tutorials (free): check out their tut on the Factory Pattern: [^]. note: i purchased their software a few years ago, and have learned a lot with/from its rigorously...
31 Jan 2022 by Richard Deeming
A collection initializer can work with multiple parameters - for example: private static Dictionary _dataStructure = new() { ["Foo"] = new MyDataPlot { { 0, 1 }, { 2, 3 }, { 4, 5 }, }, }; ...