Generic

N

nicol

hi;
this program has two error if u can help me;
Error 1 The type or namespace name 'T' could not be found (are you
missing a using directive or an assembly reference?)

Error 2 The type or namespace name 'T' could not be found (are you
missing a using directive or an assembly reference?)

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

namespace ConsoleApplication93
{
class Program
{
static void Main(string[] args)
{
sum (12.509, 49.4);
}

public double sum (T a, T b) // place 0f this error
{
if (typeof(T) == typeof(int))
{
return (double)(Convert.ToInt32(a) +
Convert.ToInt32(b));
}
if (typeof(T) == typeof(double))
{
return Convert.ToDouble(a) + Convert.ToDouble(b);
}
if (typeof(T) == typeof(byte))
{
return (double)(Convert.ToByte(a) +
Convert.ToByte(b));
}
return 0;
}


}
}
 
A

Alberto Poblacion

nicol said:
this program has two error if u can help me;
Error 1 The type or namespace name 'T' could not be found (are you
missing a using directive or an assembly reference?)

Error 2 The type or namespace name 'T' could not be found (are you
missing a using directive or an assembly reference?)

In order to use Generics, either the class should be generic, or you
should rewrite your methods to take a generic declaration.

Just change your method as follows:

public double sum<T> (T a, T b)

(Note the <T> ).
 
N

nicol

    In order to use Generics, either the class should be generic, or you
should rewrite your methods to take a generic declaration.

    Just change your method as follows:

       public double sum<T> (T a, T b)

   (Note the <T> ).

thanks;
i get what was the problem
 
P

Patrice

T is just a type. Generics types are noted within <> characters (the type
name can be whatever you want even if in most cases it is noted <T>). See
http://msdn.microsoft.com/en-us/library/512aeb7t.aspx for details...

As a side note, I'm not sure this case (likely just used as a sample ?) is
well suited to using generics. Testing the type instead the method defeats
the whole purpose of using Generics.

In this particular case I would just use overloads.

If this is just to give a try and see how it works, you could try to
reimplement Generic.List<T> yourself...

--
Patrice


"nicol" <[email protected]> a écrit dans le message de groupe de
discussion :
(e-mail address removed)...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top