Click here to Skip to main content
15,888,177 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 Updated

Generics 

29 Jun 2011 by #realJSOP
A generic List is more efficient because it deals with just the specified object type. An ArrayList requires boxing because it supports multiple types in a single list. It's almost always better to use a List rather than an ArrayList.
2 Apr 2018 by #realJSOP
0) I would like to point out that you have an abstract class without any virtual methods or properties to override. 1) I would combine Import and Export objects into a single object with an enum that indicates which direction (import/export) is applicable to the object. 2) I would define Log...
15 Jul 2018 by #realJSOP
Before the new item is added, do something like this: var found = mycollection.FirstOrDefault(x=>x.name == text); if (found == null) { mycollection.Add(text); } else { MessageBox.Show(“Duplicate names are not allowed.”); }
2 Jan 2018 by -Dr_X-
I'm unable to call the Create function due to compile errors. Any ideas? enum ReportTypes { Report1, Report2, Report3 } abstract class Report { protected abstract bool Run(); } class Report1 : Report { protected override bool Run() { return true; } } class Report2...
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); ...
20 Jun 2012 by Aakash Sharma
hello I am new with generic types.I have made a function which returns list of integers.Private Function calculate(ByVal eid As String, ByVal fn As String, ByVal from As String) As List(Of Integer)Dim Sol As New List(Of Integer) Sol.Add(CountNoOfInstallment) ...
20 Sep 2015 by Aaronman7155
I need to Update a record in my Generic Repository Application..... Using Code first.
19 Oct 2016 by abboudi_ammar
hello,how to centralize that part of code with the use of a generic list. DG.DataSource = null; var source = new BindingSource(); source.DataSource = Lcls.lc; DG.DataSource = source; that is my source code I insert and my problem is localized in...
4 Aug 2015 by Abdul Ahad Monty
Convert DataTable to List using Generics.
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 -...
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...
25 Nov 2013 by Adam Zgagacz
The following code makes the trick: private void test() { Type tDict = Type.GetType("System.Collections.Generic.Dictionary`2[System.Int32, System.String]").GetGenericTypeDefinition(); var tDict3 = tDict.MakeGenericType(typeof(string),...
24 Nov 2014 by Afzaal Ahmad Zeeshan
As I already told you that there is no way you can minimize the block, or the switch usage you're going to use them because they're all different conditions. Until you posted that comment - which was helpfull and here would be the block for your application. Inside the first block, you're...
7 Mar 2015 by Afzaal Ahmad Zeeshan
This article is for the concept of Random URLs and how they can be generated in ASP.NET for creating Random URLs for your application.
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...
22 Nov 2019 by Afzaal Ahmad Zeeshan
That would require an introduction to generics here and a change in the result that you return in the end. But here is something that can get you started: // Add the T for type annotation. public static List ExecuteProcedureReturnString(string connString, string procName, params...
22 Nov 2019 by ahmed_sa
problem How to change return of function from string to return generic list by using csharp ? I have stored procedure name getcompanies return list of companies id as following create proc getcompannies as select compnyid from companes where compnyid > 10 so that result will be as following...
10 May 2015 by AhmedYehiaK
I ask about if i can do something like that://In classlib1.dllclass Context : IdentityDbContext { .............}//In classlib2.dllclass MyUser : IdentityUser{ extend IdentityUser.......}Dependency injection registration:=> When you find...
11 Jul 2016 by Alberto Nuti
In a console application, there is often the need to ask (and validate) some data from users. For this reason, I have created a function that makes use of generics and delegates to speed up programming.
6 Sep 2012 by alc_aardvark
Simple Generic Tree in c#
21 Jul 2014 by Alexandr Stefek
This article show another way to implement generic operators. Vector is in middle of attention.
9 Jun 2013 by AlexCode
Take your Generic Handlers to the next level...
18 Sep 2012 by AmitGajjar
Hi,Ofcours...
9 May 2017 by Ammar Shaukat
C# 7.0 has been introduced with many new useful features. One of them is new datatype "ValueTuple". In this article, I'll be writing about Tuples in C# 7 briefly.
12 Dec 2010 by Andreas Gieriet
Generics and polymorphism are two orthogonal concepts.You try to use polymorphism where you have generic classes.E.g. x.value is obviously not polymorphic since it has separate implementations depending on some generic types.If you can afford to loose compile time type checks and are...
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; } ...
26 Jul 2014 by Andreas Gieriet
If it's about having various collating sequences, you might use the approach as described in Sorting C# collections that have no collating sequence[^].CheersAndi
24 Feb 2015 by Andreas Gieriet
Learn about the magic numbers on VS C++: see Magic Numbers in Visual C++[^].You try to be very generic in a language that does not really support this.You have to employ void pointers and book keeping length of elements, cast forth and back a lot. Just not maintainable.Your code has...
2 Apr 2011 by Andrew Rissing
How to get that last little nagging line to be covered...
23 Aug 2015 by Andy Lanng
I hope I have this correct:They way you propose to do this is not a good idea, but there are ways to achieve the same end result that are a good idea.Take a look at this://Generic Factory (Reflection)//Specify the worker and the return typeList addresses =...
2 Sep 2016 by Andy Lanng
Hi,I have a "T GetConfig" method. This could return a base type or a ListI now have a case where T is List, my result is List, but I "cannot cast List to Type T".Is there an easy way around this?Or do I have to create a "List GetConfigList" method?Ta...
2 Sep 2016 by Andy Lanng
I'm very proud of myself for this:I didn't explain it fully, but the methods do need to do different things to get the base type or list type setting. I could have shunted this down to the Configuration class, but I had already started creating a second List method anyway.Separating the...
2 Apr 2013 by AnkitGoel.com
I created a Generic User Control with following signature..public partial class GridMastercontrol : UserControlwhere TMainEntity : classwhere TChildEntity : class{// more code here}A reference is created as...
8 Aug 2013 by Ankur\m/
It gives you a concatenated output because that's what you are asking it to do.Instead of concatenating the columns, project columns in a new anonymous type.Change your code as below:var NameList = (from r in dataset.Tables["MyTableName"].AsEnumerable() select...
9 Oct 2014 by AnoopGharu
Hello everybody, I am work on the asp.net Profile and currently I am trying to work on the multiple properties to showing in the form page using table's but when I run the application then it shows the this following error:Using the generic type 'System.Collections.Generic.List' requires...
1 Jan 2015 by Anton Kaminsky
Hi,I'm working on migrating a C# project to java.In the C# project I have a factory class holding a dictionary between Type, and a delegate which creates appropriate type.I expose a generic method:T Create()So the user can write:var someObject =...
30 May 2011 by apaka
Is anybody aware of generic tree for c# that has all of net4 goodies and is stable,fast snd tested. or some for java (maybe I could port it).(probably I'll just get use a google sanswer , but ...) Thanks in advance.
25 Jan 2018 by Aram Tchekrekjian
Demystifying generics in C#
27 Sep 2013 by aref.bozorgmehr
i have a class with two property and i fill that with linq querypublic class a{ public int ID { set; get; } public string Name { set; get; }}passed now i passed my generic list to the below function List a1 = new List();a1 = (from p in context.TblTest select...
11 Aug 2013 by ARIA 5
I have an interface called IAuditable as follows:public interface IAuditable{ string AuditSummary { get; } string AuditDetails { get; } }And two generic method in AuditTrail class as follows:public T GetActualOldValue() where T :...
21 Jul 2016 by ArunRajendra
Check this link. Hope it gives you a clue.c# - How to get the type of T from a generic List - Stack Overflow[^]
12 Oct 2013 by ASP.NET Community
Template MethodThe Template Method is know as a behavioral pattern which lets subclasses implement behaviour that can vary. In the example below we
28 May 2020 by Aswin Francis
I have an existing C# console application that takes arguments and based on the arguments creates an instance of markets (UK, US, MX..) using dependency injection. Each market class does a 'string GetData()', 'string ProcessData()' and 'bool...
31 Jul 2021 by Attaullah Khan 2021
Hi! I'm trying to create a class that accepts a class parameter and its print function prints the name of provided class. class A(val t: T) { fun print() { println(t!!::class.java.simpleName) } } class B {} fun main() { ...
21 Mar 2013 by Azad R Chouhan
Hello friends I studied lots about generics from different websites and books but still i do not know about generics in C sharp? Please explain in simple and easy way so that i can understand what is this and what is its use?
3 Apr 2017 by Balachandar Jeganathan
Demo for generic retry mechanism
3 Oct 2013 by BC3Tech
How to constrain generic types to parameterized constructors
5 May 2014 by Benjamin Nguyễn Đạt
Please have a look at this code block:using Local = Local.Ausing Global = Global.Apublic void TreeViewBinding(T t) where T : Local where T : Global{ //My code goes here} I know this code does not work. So my question is : " Is...
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.
12 Jun 2017 by Bertus van Zyl
A tutorial about generics in C#, aimed at beginners
12 Jun 2017 by Bertus van Zyl
We continue exploring the basics of generics.
10 Jul 2018 by Bhanu Pratap Verma
Hi, I am trying to create my own class like a list generic class provided my microsoft. below is my code: namespace OwnGenricClass { class Program { static void Main(string[] args) { Owngeneric _test = new Owngeneric(); ...
10 Jul 2018 by Bhanu Pratap Verma
Hi, The above code suggestion work for me. Thank you for you response guys, Its really appreciated.
22 Sep 2014 by Bill Warner
Hi,I have a large application using EF 6 and need a way to process calls to SaveChanges() in a generic fashion. I have Googled this repeatedly and found only outdated materials. I have a partial class setup that intercepts the SaveChanges call just fine. The current error I am receiving...
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...
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...
13 Nov 2014 by BillWoodruff
The interesting challenge here is how to make this a generic method, but ensure that every List passed into it for manipulation implements a Property named 'Sno.The way that is done is with a method constraint based on an Interface:public interface ISno{ int Sno { set; get;...
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 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...
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...
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...
26 Sep 2015 by binsafir
I am running into a compiler error "cannot implicitly convert type T to T..." when I have code similar to this:class A{ private T[] stuff; public A(int n) { stuff = new T[n]; } public T get(int i) { return stuff[i]; }}class B{ private A things; public B()...
2 Apr 2015 by Boothalingam
1. I'm Using html page,Javascript file,Generic Handler,Class File2. Sending a Request from Button click and Using ajax Request in Json format.3. From Class File i'll got Two Tables in Dataset.4. How to convert that two tables in Json format and retrieve that data in Javascript file...
7 May 2015 by Brady Kelly
I realize this question sounds stupid, but please bear with me. I have a class like this:public class DropDownListViewModel{ private bool _valueIsSet; private TScalar _value; //private Nullable _nullableValue; private SelectList _selectList; ...
1 Feb 2017 by BrettPerry
A helper class to run functions in an asynchronous pattern using the Func delegate
6 Feb 2017 by BrettPerry
A helper class to run func in ThreadPool.QueueUserWorkItem and receive the response from a delegate
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
25 Sep 2013 by Captain Price
Back in the days when C was widely used than C++, how was the data structures handled ? I mean when creating data structures in C++, we usually get the use of templates, which is a huge advantage for the programmer. With C++ you can implement a linked list (or some other data structure) once and...
21 Aug 2012 by Christian Graus
If you want the data shown in different areas, you need to write cod eto show it, and if your AJAX call updates it, update them all.
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 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...
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...
24 Feb 2011 by Close Network
Hi,I have a webservice which has a method that returns a List of Payment objects provided with some input parameters. However if the input parameters are not in the correct format, I would like to return an error message which is of type string, not a List of Payment objects. I would like do...
14 Nov 2014 by conradsmith
I'm currently revisiting C# and oop after a few years programming PLCs. I'm reading up on delegates and events working through a few examples. I was wondering what are the advantages of using generic event handlers over non-generic event handlers? for example,what is the benefit of...
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.
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[^].
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...
20 May 2012 by cpsglauco
How to use delegate in List.Find() predicate in C#
1 Mar 2018 by csrss
I am trying to dig around generics for a bit now, and do not understand the following example: interface IBaseObject { } interface ITest where T : class, IBaseObject { } abstract class Test : ITest where T : class, IBaseObject { } class...
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 = ...
24 May 2014 by DamithSL
var minDate =ds.Tables[0].AsEnumerable().Select(record => record.Field("DateTime")).Max();
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...
9 Aug 2015 by DamithSL
use SelectManyparaMovies.Where(m=>m.Cast.Any()).SelectMany(m=>m.Cast).ToArray()
23 Aug 2012 by Dan Randolph
How to get faster sorting in List(T) string collections
10 Dec 2010 by DarkFigure
Hello EveryoneI am trying to form a base class to manage values of value-types and instances of classes.To do that I tried the following:public interface IBase{ T Value { get; set; }}public abstract class Base : IBase{ private T value; public...
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....
15 Sep 2015 by Darko Jurić
Portable generic image library for C#
13 Jun 2012 by Dave Kreskowiak
Yeah, you can't do that. I know, it sucks.The easy way to work around is to throw in a AddRange method to your BusinessObjectCollectionBase:Public Class BusinessObjectCollectionbase(Of T As BusinessObjectBase) Inherits BindingList(Of T) Public Sub AddRange(values As...
7 May 2015 by Dave Kreskowiak
I don't know what you're doing but it looks like you need to determine if TScalar is nullable?Perhaps you're looking for this: Type valueType = _value.GetType(); if (valueType.IsGenericType && valueType.GetGenericTypeDefinition() == typeof(Nullable)) { // Handle...
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.
30 Apr 2018 by Dave Kreskowiak
I have no idea what you're doing but it sounds like a List> could do the trick.
5 May 2014 by David A. Gray
Are you sure you understand the intended use for constraints on generics? Are Global and Local types (classes)?
1 Oct 2013 by David Knechtges
I haven't used generics before in my C# programming, but I think I have found a use for them. I just don't know how to go about converting this boilerplate code to a single generic...In the example code below, the PlayBall method and the variable passed to it (along with the variable's type)...
1 Aug 2013 by Dev Leader
A post about what makes a good API
8 Dec 2017 by dhivya N
How to take input from user for generic arrays? What I have tried: class MyGenericArray { T[] arr; public MyGenericArray(int size) { T[] arr = new T[(size)]; Console.WriteLine("Pls enter {0} no of values", size); for (int i = 0; i
21 Aug 2012 by dilzz
HI, am doing an asp.net project and am using jquery ajax for post the data and retrive it.Here is the below code.$.ajax({ type: "POST", url: "../../GeneralService.asmx/ShowBooked_Items", dataType: "json", data: JSON.stringify({ "Item_ID": $(this).attr('id') }), ...
21 Aug 2012 by dilzz
Hi,How can I return dataset from webservice to .aspx page and bind two tables in the .aspx page.I need to use jquery ajax, json. Please help me to do it.Thanks in advanceDileep
29 Jun 2011 by Dima Popov
The difference is that you perform boxing/unboxing (casting the string to object and vice verca) with ArrayList, and generic List allows you to avoid it. Performance of generic classes is better.And that's what Google came up with.[^]