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

16 Dec 2023 by VijayShimpi,Dharwad
I have this C# function internal static SortedList doSList(string list) { SortedList ret = new SortedList(); char[] charSeparators = new char[] { '|' }; ...
15 Dec 2023 by George Swan
Assuming that the Key is always a string as the input has a comma separated value format; something along these lines should do the trick. public static SortedList DoSList(string csv) where TValue : IConvertible { ...
24 May 2022 by dzadel
Hi everyone! Say i have two generic methods: int GetValue() where T: unmanaged {} int GetAnotherValue() {} I need to forward a call to one of those methods like this: void Init() { int i; //here is my problem if( T is...
24 May 2022 by Richard Deeming
The first problem you'll have is that there doesn't seem to be any built-in way to identify an "unmanaged" type from your code. If you're using .NET Core 2.0 or later, you can use the RuntimeHelpers.IsReferenceOrContainsReferences[^] method,...
1 Feb 2022 by Patrick Skelton
In C#, I thought the rule was that any collection with an Add() function could participate in declarative initialisation? I have two such collections that are nested one inside the other. Is there a way to declaratively initialise it, rather than...
31 Jan 2022 by Patrick Skelton
This is perhaps as close as I am going to get: private static Dictionary _dataStructure = new Dictionary { [ "One" ] = new MyDataPlot { { 2, 6 }, { 7, 4 } }, [ "Two" ] = new MyDataPlot { { 5, 16...
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 }, }, }; ...
31 Jan 2022 by OriginalGriff
Because Add is a void method, you can't use it directly in an initializer. Change it to return the MyDataPlot instance, and it works: public class MyDataPoint { public MyDataPoint(int x, int y) { X = x; Y = y; } public...
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() { ...
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...
12 Jun 2021 by Raghad Aea
I am stuck please help , i get a segmentation fault this is something you can debug if you want to help me : debug.h ``` #ifndef DEBUG_H_ #define DEBUG_H_ template class SortedList { T** data; int size; int max_size; void...
12 Jun 2021 by OriginalGriff
A segmentation fault doesn't mean that the poitner was null: it means the pointer was invalid - it pointed at memory that didn't exist, or that doesn't "belong" to that process. The first thing you need to do is us eteh debugger to find out the...
30 Nov 2020 by Sni.DelWoods
Is there a way to call a notifier each time a property or field in a class is changed? I created a simple demontration class Foo: A container holds some other classes. I need a notification if any field in the class or the sub class is changed....
30 Nov 2020 by Maciej Los
Seems, you don't understand how property change notifier works... I'd suggest to read Daniel's Pratt answer (and the comments below the answer) in this thread: ObservableCollection in Winforms and possible alternatives - Stack Overflow[^] ...
29 Nov 2020 by Sni.DelWoods
Thank you all for your comments. All concepts are more or less based on changing the setter of the property. That's not what I need. For my specific case I've created the "dirty" solution using reflection. (yes, it is not type safe and will...
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...
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 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...
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 Richard MacCutchan
Snesh Prajapati[^] has written a nice set of articles at Factory Patterns - Simple Factory Pattern[^].
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...
23 Oct 2020 by RickZeeland
Maybe this will be helpful: Generic Factory Class[^]
21 Oct 2020 by Patrick Skelton
Apologies for the vague nature of the question. I couldn't think of a concise way to explain the problem I seem to be facing for the Nth time and which I think must be an extremely common scenario. Code explains it best... abstract class...
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...
5 Oct 2020 by Robert P. Howard
How to deserialize a JSON string that contains nested polymorphic objects
28 May 2020 by RickZeeland
You can find a nice overview with examples here: .NET Design Patterns in C# and VB.NET - Gang of Four (GOF) - doFactory.com[^]
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...
6 Apr 2020 by istudent
I need to create generic method that return dictionary of Enum values with display attribute name. I would also like to see if it can be done as an extension method for Enum. What I have tried: I only able to do with non generic method. ...
6 Apr 2020 by MadMyche
How about an Extension Method that can return an int/string dictionary across whatever type of Enum it sees?namespace System { public static class SysExtension { public static Dictionary ToDictionary(this Enum EnumList) {...
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...
26 Feb 2020 by Herman<T>.Instance
Hi Friends, I Have created a generic class called DropDownListFiller In T I put an EntityClass that hold a variable called DataFromService DataFromService is of IQueryable type. How do I get SelectedEntity have the values of...
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...
19 Feb 2020 by Sni.DelWoods
Idea The following code uses an overloaded method which expects the base class or the concrete derrived class as parameter. Problem The problem is that FieldTypeBase field = new TextFieldType(); is passed as type FieldTypeBase and calls...
18 Feb 2020 by Sni.DelWoods
Thanks for your comments. I have already done it the right way and moved the function to the base class. The code above is just a test snippet from am bigger system. I was just wondering why the system does always use the base class version. ...
18 Feb 2020 by OriginalGriff
The correct method is being called. FieldTypeBase field = new TextFieldType(); Unless you upcast the base class variable when you call the method, the system has to assume that field can contain any derived class, and will always call teh "safe"...
18 Feb 2020 by phil.o
Look at your code:public static string DoWork(FieldTypes.FieldTypeBase fieldType) => "DoWork[error:NoWorkerDefined]"; What your interpret as an error is just the string that you actually return in case the DoWork(FieldTypes.FieldTypeBase...
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...
17 Jan 2020 by Patrick Skelton
My question is, I think, perfectly illustrated by the following code (which does not compile as it stands): public abstract class MyBaseBusinessObjectClass { public abstract string BusinessObjectName { get; } } public class BusinessObjectOne : MyBaseBusinessObjectClass { public...
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 :...
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...
22 Nov 2019 by OriginalGriff
Start by changing the signature: public static string ExecuteProcedureReturnString(string connString, string procName, params SqlParameter[] paramters) Becomes public static List ExecuteProcedureReturnString(string connString, string procName, params SqlParameter[]...
8 Sep 2019 by Gerry Schmitz
If you can't figure out how to model something in SQL, don't expect EF to be able to. At some point EF is better at "database first" than "code first". Create a few (test) relationships in SQL that work, see what EF does with it, THEN create the generic code based on the pattern.
8 Sep 2019 by Member 11380736
I'm trying to create a dynamic MySQL "EntityFramework Core" connection object, that is responsible for connection junction tables. This is my interface for specifying a junction table: public interface IJunctionTable { int ID { get; set; } int CompositeKeyA { get; set; } ...
25 Aug 2019 by Member 11380736
I'm trying to create a dynamic architecture for a Audio/Video player application. I want to be able to change the type of playlist and type of repository from inside the ioc container. This should be injected in constructors around the application: IPlaylist playlist,...
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...
14 Nov 2018 by Patrick Skelton
This is one case where code really is worth a thousand words. The code that follows does not compile. I hope it is close enough to show what I am trying to do. I don't see anything conceptually wrong with what I am trying to do but seem to be in a complete mix-up with syntax. Of course, if...
15 Jul 2018 by Eric Lynch
A System.Collections.Generic.HashSet is typical for detecting duplicates. Basically, you do the following... string text = "Some Text"; var mySet = new HashSet(); if (mySet.Contains(text)) Console.WriteLine("Duplicate!"); else mySet.Add(text);
15 Jul 2018 by Waqar (Vicky)
Lets say There is a collection of Items When item 1 added with type "grocery" more than 1 times then i need to show the popup icon on the basis of some boolean flag "isShowIcon = true/false". when item 1 added with type "grocery" (no information popup icon) when item 2 added with type "grocery"...
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.”); }
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.
9 Jul 2018 by F-ES Sitecore
Your extension is acting on the type Owngeneric so that's what needs to be your "this" public static int extnlenght(this Owngeneric entity) { return entity.Count; // We also need to create the Count property } Next your custom class needs a way of returning the count of the items...
9 Jul 2018 by Graeme_Grant
Have a read of this great answer: c# - Why isn't Array a generic type? - Stack Overflow[^] You would be better off working with List for collections. Here is a starter: Collections tutorial - C# local quickstarts | Microsoft Docs[^]
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...
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++; } }
16 Jun 2018 by Waqar (Vicky)
private void RenumberPreferredSequence(Item record) { foreach (var itemVendor in record.ItemVendors) { itemVendor.PreferredSequence = 0; } foreach (var itemVendor in record.ItemVendors) { if...
9 Jun 2018 by Richard Deeming
If you need to access properties or methods from your generic type parameter, the simplest option is to have your types implement an interface, and constrain the type parameter to types which implement that interface. For example: public interface IObjectWithId { Guid ObjectId { get; } } ...
9 Jun 2018 by Member 13839622
I'm storing objects, in a List. In my RemovePoolObject and GetPoolObject functions to work. But, I can't access the TestClass fields. #region ObjectPooler public class PooledObject { public Func ObjectInitializer { get; } ...
8 Jun 2018 by Gerry Schmitz
Use GetHashCode() of the underlying object to track your objects' "id's".
30 Apr 2018 by Patrice T
Quote: I have tried C# Generics Dictionary and HashTable feature but both have limitations that Key must be unique. Non empty unique keys are the principle of dictionary. No dictionary will break this rule, ever. The dictionary smells like a wrong solution to your problem. In order to get a...
30 Apr 2018 by Waqar (Vicky)
I am going to parse first two csv lines (headers,values) and then split them on base of comma ',' and then add them both parallel to the collection. I am able to do this with dictionary but when the two headers same or empty it gives error "n item with the same key has already been added in...
30 Apr 2018 by Dave Kreskowiak
I have no idea what you're doing but it sounds like a List> could do the trick.
30 Apr 2018 by Gerry Schmitz
You seem to have an issue with the fact that you have "empty lines" and "duplicate headers". Nobody can figure out if you think this is a "feature" or a "problem". You have gotten reasonable answers to a foggy "question" (if you can call it that). You need a better "problem definition".
29 Apr 2018 by PIEBALDconsult
How about using two Dictionary -- one for column names and one for data? However, I recommend reading them into a DataTable (you never know what the future may hold) -- name the columns with the index and set the Captions to the name.
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...
14 Apr 2018 by The_Unknown_Member
C# What does the "?" symbol do when it's placed after a generic parameter I've come across this code: public static Task GetPageLength() { // Code ... } What I have tried: Googling but didn't find any information.
9 Apr 2018 by Sni.DelWoods
The method FillDerrivedFromBase(object classDerrived, object classBase) copies all values of a base class to the derrived class. This works also fine with List and I don't have to worry about the types. Simple way to fill the derrived instance with the data of the base instance: public...
9 Apr 2018 by Sni.DelWoods
I have a logger class with wrapper and entries. The type of entries varies from the case I'm using the log functions. (Class for imports, exports, statistics, etc.) Is there a way to set the type in List by a parameter in the constructor? What I have tried: public abstract class...
3 Apr 2018 by Sni.DelWoods
Thanks for the comments. I've found my working solution: using System; using System.Collections; using System.Collections.Generic; using System.Data; public abstract class LogBase { public class EntryBase { public DateTime Timestamp { get; set; } = DateTime.Now; public...
3 Apr 2018 by Maciej Los
If i understand you correctly, a Log class has to be a generic class[^], which gets as an input a class derived from EntryBase class. It 's called constraints. See: Constraints on Type Parameters (C# Programming Guide) | Microsoft Docs[^] Seems, your Log class have to behave as a List[^]...
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...
31 Mar 2018 by Richard MacCutchan
Covariance and Contravariance work Generic Interfaces - Google Search[^]
20 Mar 2018 by saifullahiit
I'm Trying to update entry using EF 6.0, and generic repository. here is my base class code: public virtual void Edit(T entity) { _entities.Entry(entity).State = EntityState.Modified; _entities.SaveChanges(); } public virtual T GetById(int id) { ...
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 =...
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...
5 Feb 2018 by Suren97
I have a two classes` Employee and Controller,Employee's fields is` name,surname,sallary.in Controller class I have a Generic array which has 4 Objects, like this` public List e = new List() { new Employee("Vazgen","Vazgenyan",3000$), new...
5 Feb 2018 by Richard MacCutchan
public void Insert_Data() { Console.WriteLine("Please type new Emplyoee's data"); string text = Console.ReadLine(); string[] arr = text.Split(','); } What happens to arr when this method ends? It just disappears. You need to add the data from...
5 Feb 2018 by OriginalGriff
We don;t do your homework, so you get no code! But this is trivial: 1) Read the line from the console. 2) Use string.Split to break it in the comma 3) Check there are exactly three parts after the split. If not, complain. 4) Create a Employee instance from the entered data, using new 5) Use the...
25 Jan 2018 by Aram Tchekrekjian
Demystifying generics in C#
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...
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...
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[^].
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
8 Dec 2017 by Richard Deeming
As already pointed out, there's no standard way to convert a string to a specified class. But what you can do is pass in a delegate to do the conversion, which pushes that responsibility back onto the caller: class MyGenericArray { private readonly T[] arr; public...
7 Dec 2017 by OriginalGriff
When you read from the console, it always returns a string. You can't use a Generic specifier to change that to your required type, because that requires a specific Parse (or TryParse, or even Convert.ToXXX) method call to change it. And there is no specific conversion from a string to any type...
7 Dec 2017 by Richard MacCutchan
Collections in C#. Learn to use sequences and collections in C#. | Microsoft Docs[^]
24 Oct 2017 by Duncan Edwards Jones
I have a generic class used to serialise an event to/from a name-value pairs dictionary. It has the following class signature:- Public Class EventSerializer(Of TEvent As {New, IEvent}) It has a factory method that can create it from an instance of the class thus:- Public Function...
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...
27 Sep 2017 by Nick4978
Not really sure how to explain it in a one-liner but here's my situation. I have an abstract base class called "Deal" which has a property in it which is of a class "Inventory" Now a deal can be either Cash, Finance, Lease, Wholesale or Rent-To-Own which is why it's of type Deal. It's also...
27 Sep 2017 by Richard MacCutchan
But both Deal and Inventory are abstract classes so you cannot create either of them. You could make Deal a real class and use an enumeration to decide which type it is; same with Inventory. And you cannot do something like public class Car : Inventory You cannot create a type that has...
23 Sep 2017 by Member 13425520
Hi, I'm trying to make "Node" class outside of LinkedBag using package from an inner class of LinkedBag1.java(I attached the code as below). But It did not work. I could compile Node.java, but not LinkedBagDemo1.java and LinkedBag1.java. The error as below came up. How could I fix the problem...
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[^].
12 Sep 2017 by Patrick Skelton
I get the feeling the answer to this must either be obvious or so obscure I need to find a better way, but I have been trying to include a generic type in a Tuple. The following code, which does not compile, shows the idea of what I am trying to do: List>> listOfTuples...
12 Sep 2017 by johannesnestler
I'm wondering why no one said the obvious - Why you mess arround with tuples for such cases? They are not for "complicated cases" just create a type to hold your information and make a list of that.... just my 2c
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" }));...
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...
4 Jul 2017 by santhosepriya
Hi I am using Zip archive[System.IO.Compression] for collect the multiple xml memory stream and convert into zip memory stream then sent to remote server [where I am storing zip file]. My intention is not to store any files[including xml file,zip file] in local machine, and not to use any 3rd...