What are the generic methods in C#


#1

Hi, i am looking for some example code that help me to learn generic methods in C# which allows defining the class, method etc without binding it to work with a specific data type, instead it is created with a substituted type which get replaced with the data type passed at run time. While working on projects I have faced many issues related with C# questions & answers, so I am hoping for valuable valuable suggestions & great support from the online community.


#2

The generic methods are used when you have a type of processing that needs to be performed on a set of classes with similar interfaces or identifications, instead of having the same method to work on classA : IClass and classB : IClass, you can define a generic method that works on both and takes IClass as a T parameter.

In my specific case, I have a method to write out structs for binary output to interface with an external application. The ToBinaryWriterBloc< T >(T item, BinaryWriter bw) where T : struct accepts any struct I need to use. ( https://github.com/ewinnington/core-minimal/blob/master/src/data/BinaryStructs.cs )

Does this help understand where a generic method in C# is used or might be helpful?

I would also recommend you have a read of the MSDN Documentation on Generics.


.NET Foundation Website | Blog | Projects | Code of Conduct