I Hurt When It Comes To C# Generic Methods? How Important Are They?

  • (2 Pages)
  • +
  • 1
  • 2

25 Replies - 2357 Views - Last Post: 15 October 2011 - 11:37 AM Rate Topic: -----

#1 adn258  Icon User is offline

  • D.I.C Addict

Reputation: 11
  • View blog
  • Posts: 762
  • Joined: 31-August 11

I Hurt When It Comes To C# Generic Methods? How Important Are They?

Posted 12 October 2011 - 06:11 PM

So How often do you use Generics? How important Are They with most C# coding? I have been reading on generics I understand the generics list (sort of), but methods? Get out of here. I have been reading about them but I don't get it. Can someone show examples that are easy to understand and also explain how important they are i.e. questions above?

Thanks in advance
Is This A Good Question/Topic? 0
  • +

Replies To: I Hurt When It Comes To C# Generic Methods? How Important Are They?

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4354
  • View blog
  • Posts: 12,160
  • Joined: 18-April 07

Re: I Hurt When It Comes To C# Generic Methods? How Important Are They?

Posted 12 October 2011 - 07:19 PM

Well understand that generics are great for code flexibility, reuse and can be faster than non generic code. There was a time when we would program without generics, so it can certainly be done. However, generics is an important thing to understand, even if you don't find you use them all that often.

Imagine you want to create a function which stores a list of items. Perhaps it is a stack. Now lets say you wanted this function to create different types of lists. A list for integers, perhaps a list for strings, perhaps another is a list of Person class instances.

Without generics you would have to either create a function that can build each type of list (three separate list making functions which are very very similar except for the data types you are using) where you would replace everywhere it says "int" with "string". You could go a different route and create one function that takes the base class "object" but that would require you to pack up an integer into an object, put it in the list and when you wanted it back, take out the object and convert it to an integer again. Very slow process.

Generics allow you to generalize a function (like a template) where you can then specify various data types at runtime. The same function could be used to store strings or store integers or store Person classes etc. No repetition.

It is faster because when you define your list you specify the data type and thus the compiler knows that this function is creating a list of integers (unlike before where you have a list of objects with who knows what inside). Since it knows you are working with integers, it can optimize operations knowing that it is working with ints rather than Person classes or unknown object classes.

For instance we have this code...

public class Stack<T>
{
   T[] m_Items; 
   public void Push(T item)
   {...}
   public T Pop()
   {...}
}
Stack<int> stack = new Stack<int>();



This class here allows us to create a Stack of items. Here <T> is whatever data type it was initialized with. In the example, it would become "int" because notice how we created it using <int>. Everywhere it encounters "T" it is going to replace it with "int".

Taking the same stack if I said Stack<string> stack = new Stack<string>();, everywhere you see "T" (known as a type parameter... as in a parameter that will be filled with a data type) would now be "string". So T[] mItems; would in essence become string[] m_Items; or in other words an array of strings. Now that the compiler knows that it will be working with an array of strings, it can optimize the code to work with strings. It is "safe" for the compiler to "assume" that it is working with strings.

Now of course they get a little bit more technical and fancy with type parameters. Some parameters that are wildcards or inherit from other parameter types. I personally haven't really needed to go that far except in a few occasions but you can do a lot with just the basics.


Hope this helps. :)

This post has been edited by Martyr2: 12 October 2011 - 07:25 PM

Was This Post Helpful? 3
  • +
  • -

#3 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4498
  • View blog
  • Posts: 7,850
  • Joined: 08-June 10

Re: I Hurt When It Comes To C# Generic Methods? How Important Are They?

Posted 12 October 2011 - 07:47 PM

I've actually written a tutorial on this subject.

http://www.dreaminco...enerics-primer/

Should be helpful to you.
Was This Post Helpful? 0
  • +
  • -

#4 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,960
  • Joined: 21-March 08

Re: I Hurt When It Comes To C# Generic Methods? How Important Are They?

Posted 12 October 2011 - 07:49 PM

For a couple of examples, here is a snippet I wrote that will serialize and deserialize any class.

http://www.dreaminco...snippet6212.htm

That's two methods that will handle any .Net class(custom classes and internal types).

Another example is this snippet that takes an XElement(Linq-To-XML) and converts it's value to just about any type.

http://www.dreaminco...snippet6261.htm

These are examples of why generics methods are great. How many methods would I have had to create if I wanted to convert an XML element value to each type? It would be a ton of methods. Now it's only one.
Was This Post Helpful? 1
  • +
  • -

#5 adn258  Icon User is offline

  • D.I.C Addict

Reputation: 11
  • View blog
  • Posts: 762
  • Joined: 31-August 11

Re: I Hurt When It Comes To C# Generic Methods? How Important Are They?

Posted 13 October 2011 - 05:24 PM

So Like I am learning a little bit now finally, but I am still not seeing an advantage, what am I missing?

Using the example below for example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    //class for adding numbers
    class adding
    {
        public void Add<T>(ref T a, ref T B)/>
        {
            //add the two numbers converting them to int32
            Console.WriteLine(Convert.ToInt32(a) + Convert.ToInt32(B)/>);

        }



    }
    class Program
    {
        static void Main(string[] args)
        {
            //create a new instance of the method
            adding one = new adding();

            int x = 3; int y = 3;

            one.Add<int>(ref x, ref y);
            Console.ReadLine();
            x = 10; y = 20;
            one.Add<int>(ref x, ref y);
            Console.ReadLine();

            




        }
    }
}






This code I wrote is a Generic method that adds two numbers right? How is this at ALL an advantage? Like I could do this with a simple function so how is this helping? Sorry someone explain lol?

Thanks
Was This Post Helpful? 0
  • +
  • -

#6 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2264
  • View blog
  • Posts: 9,469
  • Joined: 29-May 08

Re: I Hurt When It Comes To C# Generic Methods? How Important Are They?

Posted 13 October 2011 - 05:45 PM

Think about the follow generic class (written in vb.net, sorry)
Public Class Cup(Of T As IBeverage)
  Protected _drink As T

  Public Sub New(drink As T)
    _drink As T
  End Sub

  Public ReadOnly Property Drink() As T
    Get
      Return _drink
    End Get
  End Property

  Public Sub Refill(ByVal drink As T) 
    _drink = drink
  End Sub

End Class



The Cup can contain any Type (class / structure) that implement the IBeverage Interface.


Public Class Tea
  Implement IBeverage
End Class
Public Class Coffee
  Implement IBeverage
End Class


For example
Dim myDrink As New Cup(Of Coffee)(New Coffee)
Dim yourDrink As New Cup(Of Tea)(New Tee)



There is one implementation of the class Cup but it used to create two different instances. Cup(Of Coffee) Cup(Of Tea)
Now consider the method Refill(drink As T) because we have stated that one cup contains Coffee, it can only ever be refilled with Coffee, not Tea. And the Cup of Tea can only be refilled with Tea, not Coffee.

Generics allows code to reused more generally but in a type-safe manner.

This post has been edited by AdamSpeight2008: 13 October 2011 - 06:05 PM

Was This Post Helpful? 0
  • +
  • -

#7 brep  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 23
  • View blog
  • Posts: 169
  • Joined: 26-August 11

Re: I Hurt When It Comes To C# Generic Methods? How Important Are They?

Posted 13 October 2011 - 06:12 PM

So, let's say you had to do some arithmetic with a project you are working on for a company. This program has to have a GUI, and the program should be able to add all the different binary variable types.

Without generics, the following methods can be made:
publice double add(double num1, double num2) {

    return(num1 + num2)

}

publice int add(double num1, double num2) {

    return(num1 + num2)

}

publice byte add(double num1, double num2) {

    return(num1 + num2)

}



And so on.

But in generics, that can be simplified to (taken from my snippet.):

class GenericOperation<T> where T : struct
    {
     public T Add(T num1, T num2)
     { 
 
            T result = DynamicAdd(num1, num2); 
 
            return result; 
 
      }
      private static dynamic DynamicAdd(dynamic Num1, dynamic Num2)
      { 
 
            return (Num1 + Num2); 
      }
}



This gives the advantage of minimizing repetitive code, making your program easier to understand.

Also note that the way you added the integers will probably not work for say an application built in Windows Forms. The example shown above should work in all adding scenarios, GUI, Console, or anything else.

Hope this helps.
preb

Edit: showed code in generic class for clarity.

This post has been edited by preb: 13 October 2011 - 06:49 PM

Was This Post Helpful? 0
  • +
  • -

#8 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2264
  • View blog
  • Posts: 9,469
  • Joined: 29-May 08

Re: I Hurt When It Comes To C# Generic Methods? How Important Are They?

Posted 13 October 2011 - 06:21 PM

But that example throws a runtime exception (because of the dynamic) if the operation can not be done. Generics happen a compile time. Also if you did it on strings it'll concatenate them (doesn't do what the method name states).

This post has been edited by AdamSpeight2008: 13 October 2011 - 06:23 PM

Was This Post Helpful? 0
  • +
  • -

#9 brep  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 23
  • View blog
  • Posts: 169
  • Joined: 26-August 11

Re: I Hurt When It Comes To C# Generic Methods? How Important Are They?

Posted 13 October 2011 - 06:22 PM

See my edit (struct). Also, I had no exceptions in my full snippet when I submitted it.

This post has been edited by preb: 13 October 2011 - 06:23 PM

Was This Post Helpful? 0
  • +
  • -

#10 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2264
  • View blog
  • Posts: 9,469
  • Joined: 29-May 08

Re: I Hurt When It Comes To C# Generic Methods? How Important Are They?

Posted 13 October 2011 - 06:25 PM

Still applies, you can define your own structures that don't implement operators. It doesn't handle nullable types. The "Number" types don't implement anything that you can restrict the generic parameter T on, and check at compile time.

This post has been edited by AdamSpeight2008: 13 October 2011 - 06:31 PM

Was This Post Helpful? 0
  • +
  • -

#11 brep  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 23
  • View blog
  • Posts: 169
  • Joined: 26-August 11

Re: I Hurt When It Comes To C# Generic Methods? How Important Are They?

Posted 13 October 2011 - 06:28 PM

I see your point, but I would assume though that you wouldn't want to use nullable types anyway. Is that correct?

Edit: Oh, wait. Do you mean if there is a user error and the user accidentally passes nullable types?

Edit 2: also, strings are reference types, and struct refers to binary types. I would assume that the struct constriant would be sufficient then and protect from adding strings, correct?

This post has been edited by preb: 13 October 2011 - 06:32 PM

Was This Post Helpful? 0
  • +
  • -

#12 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2264
  • View blog
  • Posts: 9,469
  • Joined: 29-May 08

Re: I Hurt When It Comes To C# Generic Methods? How Important Are They?

Posted 13 October 2011 - 06:52 PM

Good enough for strings. Remember though that Dynamic calls happen at runtime and are not checked at compile time.

Two examples where it fails

Following Error when it doesn't implement a + operator
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException was unhandled
  Message=Operator '+' cannot be applied to operands of type 'ArithmeticUsingGenerics.c' and 'ArithmeticUsingGenerics.c'
  Source=Anonymously Hosted DynamicMethods Assembly
  StackTrace:
       at CallSite.Target(Closure , CallSite , Object , Object )
       at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
       at ArithmeticUsingGenerics.GenericOperation`1.DynamicAdd(Object Num1, Object Num2) in c:\Users\Adam\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs:line 32
       at ArithmeticUsingGenerics.GenericOperation`1.Add(T num1, T num2) in c:\Users\Adam\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs:line 23
       at ArithmeticUsingGenerics.MainMethod.Main() in c:\Users\Adam\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs:line 53
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 


Does implement an operator +, but doesn't return the same type as T
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException was unhandled
  Message=Cannot implicitly convert type 'int' to 'ArithmeticUsingGenerics.c'
  Source=Anonymously Hosted DynamicMethods Assembly
  StackTrace:
       at CallSite.Target(Closure , CallSite , Object )
       at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
       at ArithmeticUsingGenerics.GenericOperation`1.Add(T num1, T num2) in c:\Users\Adam\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs:line 23
       at ArithmeticUsingGenerics.MainMethod.Main() in c:\Users\Adam\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs:line 57
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 


Was This Post Helpful? 0
  • +
  • -

#13 brep  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 23
  • View blog
  • Posts: 169
  • Joined: 26-August 11

Re: I Hurt When It Comes To C# Generic Methods? How Important Are They?

Posted 13 October 2011 - 06:59 PM

That's interesting because I ran it in Visual Studio earlier, and no errors were produced with doubles. Of course, that was about 2 weeks ago, but in the afternoon tomorrow I can check it again.

I am aware that dynamic types are checked at runtime, which is exactly why I implemented it in the first place.

Also, sorry if I am missing something obvious here, and sorry adn258 if this is getting confusing.

This post has been edited by preb: 13 October 2011 - 07:00 PM

Was This Post Helpful? 0
  • +
  • -

#14 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,960
  • Joined: 21-March 08

Re: I Hurt When It Comes To C# Generic Methods? How Important Are They?

Posted 13 October 2011 - 07:00 PM

View Postadn258, on 13 October 2011 - 08:24 PM, said:

So Like I am learning a little bit now finally, but I am still not seeing an advantage, what am I missing?

Using the example below for example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    //class for adding numbers
    class adding
    {
        public void Add<T>(ref T a, ref T B)/>
        {
            //add the two numbers converting them to int32
            Console.WriteLine(Convert.ToInt32(a) + Convert.ToInt32(B)/>);

        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            //create a new instance of the method
            adding one = new adding();

            int x = 3; int y = 3;

            one.Add<int>(ref x, ref y);
            Console.ReadLine();
            x = 10; y = 20;
            one.Add<int>(ref x, ref y);
            Console.ReadLine();
        }
    }
}






This code I wrote is a Generic method that adds two numbers right? How is this at ALL an advantage? Like I could do this with a simple function so how is this helping? Sorry someone explain lol?

Thanks


That really isn't a generic method. While it's generic in it's declaration(using T), it's not generic in it's implementation. You are still using the values as integers instead of as type T.
Was This Post Helpful? 0
  • +
  • -

#15 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2264
  • View blog
  • Posts: 9,469
  • Joined: 29-May 08

Re: I Hurt When It Comes To C# Generic Methods? How Important Are They?

Posted 13 October 2011 - 07:11 PM

Let Anders Explain
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2