473,702 Members | 2,335 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

passing a generic type to a generic class

I apologize if this question has been asked before, but after about
half an hour of searching I haven't been able to find an answer online.

My code is beloiw, with comments pertaining to my question
In short my question is why when I pass a generic type directly to the
formatObject function it works fine, but when I pass it to the
checkText function where it is itself a generic argument, and then it
is passed to formatObject, it is seen as an Object and not as the type
it is? Any help would be greatly appreciated.

Here are the relevant sections of my code (I apologize for any typos as
the actual code is on a remote system that I cannot cut and past from)

public class FormatObject
{
public static string formatObject(Ob ject o)
{
return o.ToString();
}

public static string formatObject<K, V>(KeyValuePair <K,Vkvpo)
{
//do some reflectiony sort of things to build up string
// that looks like (KeyValuePair<I nt32, Int32= {10,10})

message += formatObject(kv po.Key);
// call formatObject on the key and value
// recursively in case they are of a type handled
// by other formatObject calls
return message
}

// a few other overridden formatObject functions taking different
// types (List<T>, List<List<T>>, etc)

}

public class CheckText
{
public bool void checkText(T t, string matchPattern)
{
string ostr;
ostr = FormatObject.fo rmatObject(t);
return (ostr.IndexOf(m atchPattern) != -1)
}
}

public void Main(string[] args)
{
KeyValuePair<in t, intk = new KeyValuePair<in t, int>(10,.10);
string formatted = FormatObject.fo rmatObject(k);
// Calls the appropriate function and returns a string consisting of
// (KeyValuePair<I nt32, Int32= {10,10})

bool doesContain = CheckText.check Text(k,"(KeyVal uePair");
// returns false as it calls the Object overriden version
// of formatObject. which returns a string
// consisting of "{10,10}"
}

Aug 24 '06 #1
4 3141
Charles,

Can you please post compilable sample that demonstrates the problem -
console application is preferable.

--
Stoitcho Goutsev (100)

"Charles Churchill" <gy******@gmail .comwrote in message
news:11******** **************@ p79g2000cwp.goo glegroups.com.. .
>I apologize if this question has been asked before, but after about
half an hour of searching I haven't been able to find an answer online.

My code is beloiw, with comments pertaining to my question
In short my question is why when I pass a generic type directly to the
formatObject function it works fine, but when I pass it to the
checkText function where it is itself a generic argument, and then it
is passed to formatObject, it is seen as an Object and not as the type
it is? Any help would be greatly appreciated.

Here are the relevant sections of my code (I apologize for any typos as
the actual code is on a remote system that I cannot cut and past from)

public class FormatObject
{
public static string formatObject(Ob ject o)
{
return o.ToString();
}

public static string formatObject<K, V>(KeyValuePair <K,Vkvpo)
{
//do some reflectiony sort of things to build up string
// that looks like (KeyValuePair<I nt32, Int32= {10,10})

message += formatObject(kv po.Key);
// call formatObject on the key and value
// recursively in case they are of a type handled
// by other formatObject calls
return message
}

// a few other overridden formatObject functions taking different
// types (List<T>, List<List<T>>, etc)

}

public class CheckText
{
public bool void checkText(T t, string matchPattern)
{
string ostr;
ostr = FormatObject.fo rmatObject(t);
return (ostr.IndexOf(m atchPattern) != -1)
}
}

public void Main(string[] args)
{
KeyValuePair<in t, intk = new KeyValuePair<in t, int>(10,.10);
string formatted = FormatObject.fo rmatObject(k);
// Calls the appropriate function and returns a string consisting of
// (KeyValuePair<I nt32, Int32= {10,10})

bool doesContain = CheckText.check Text(k,"(KeyVal uePair");
// returns false as it calls the Object overriden version
// of formatObject. which returns a string
// consisting of "{10,10}"
}

Aug 24 '06 #2
Stoitcho Goutsev (100) wrote:
Charles,

Can you please post compilable sample that demonstrates the problem -
console application is preferable.

--
Stoitcho Goutsev (100)
Here you go:

namespace TestProgram
{
public class FormatObject
{
public static string formatObject(Ob ject o)
{
return o.ToString();
}

public static string formatObject<K, V>(KeyValuePair <K, Vkvpo)
{
return "KeyValuePa ir<" + typeof(K).Name + ","
+ typeof(V).Name + "= " + kvpo.ToString() ;
}
}

public class CheckText
{
public static bool checkText<T>(T t, string matchThis)
{
string ostr = FormatObject.fo rmatObject(t);
return (ostr.IndexOf(m atchThis) != -1);
}

}

class Program
{
static void Main(string[] args)
{
KeyValuePair<in t, intk = new
KeyValuePair<in t,int>(500,2000 );
Console.WriteLi ne(FormatObject .formatObject(k ));
bool found = CheckText.check Text(k, "KeyValuePair") ;
Console.ReadLin e();
}
}
}

Thanks

Aug 24 '06 #3

Charles Churchill wrote:
I apologize if this question has been asked before, but after about
half an hour of searching I haven't been able to find an answer online.

My code is beloiw, with comments pertaining to my question
In short my question is why when I pass a generic type directly to the
formatObject function it works fine, but when I pass it to the
checkText function where it is itself a generic argument, and then it
is passed to formatObject, it is seen as an Object and not as the type
it is? Any help would be greatly appreciated.

Here are the relevant sections of my code (I apologize for any typos as
the actual code is on a remote system that I cannot cut and past from)

public class FormatObject
{
public static string formatObject(Ob ject o)
{
return o.ToString();
}

public static string formatObject<K, V>(KeyValuePair <K,Vkvpo)
{
//do some reflectiony sort of things to build up string
// that looks like (KeyValuePair<I nt32, Int32= {10,10})

message += formatObject(kv po.Key);
// call formatObject on the key and value
// recursively in case they are of a type handled
// by other formatObject calls
return message
}

// a few other overridden formatObject functions taking different
// types (List<T>, List<List<T>>, etc)

}

public class CheckText
{
public bool void checkText(T t, string matchPattern)
{
string ostr;
ostr = FormatObject.fo rmatObject(t);
return (ostr.IndexOf(m atchPattern) != -1)
}
}

public void Main(string[] args)
{
KeyValuePair<in t, intk = new KeyValuePair<in t, int>(10,.10);
string formatted = FormatObject.fo rmatObject(k);
// Calls the appropriate function and returns a string consisting of
// (KeyValuePair<I nt32, Int32= {10,10})

bool doesContain = CheckText.check Text(k,"(KeyVal uePair");
// returns false as it calls the Object overriden version
// of formatObject. which returns a string
// consisting of "{10,10}"
}
I'm not using generics yet, but a couple of minutes looking at your
code leads me to believe that your problem has nothing to do with
generics, as such. Rather, it involves the following:

"Which overload of a method should be called is determined at compile
time, not run time. Method overRIDES are resolved at run time; method
overLOADS are resolved at compile time."

So, in your case, the line

ostr = FormatObject.fo rmatObject(t);

will result in a call to FormatObject.fo rmatObject(Obje ct o) unless T
is a subtype of KeyValuePair<K, V>. Even if at run time the variable t
refers to an instance of a class that implements the correct interface
/ inherits from the correct class so that a call to
FormatObject.fo rmatObject<K, Vwould be possible, it still won't
happen because the compiler has no way of knowing that that will be the
case.

Take a simpler, non-generic example:

public class Foo : IComparable
{
public int CompareTo(objec t other)
{
// Native Foo object greater than any other kind of object
return 1;
}

public int CompareTo(Foo otherFoo)
{
... do some stuff to compare Foos ...
}
}

public class Other
{
public static int CompareFoo(Foo aFoo, object something)
{
return aFoo.CompareTo( something);
}
}

A call such as myOther.Compare ToFoo(...) will _always_ return -1. Why?
Because no matter what is passed as the argument "something" , the
compiler has already determined that the correct signature to call is
Foo.CompareTo(o bject), based on the fact that the "something" argument
is declared as an object type. Even if you pass a Foo instance at run
time, it still calls the Foo.CompareTo(o bject) method.

The usual way around this is to do the testing yourself, at run time,
to determine whether the more specific method is appropriate:

public int CompareTo(objec t other)
{
Foo otherFoo = other as Foo;
if (otherFoo != null)
{
return this.CompareTo( otherFoo);
}
else
{
// Native Foo object greater than any other kind of object
return 1;
}
}

.... or something like that.

In your case, you need to test, within formatObject(ob ject o) whether
"o" is an instance of something that could be passed to the generic
method, and then call the generic method if appropriate.

Maybe. As I said, I'm not on V2.0 yet. :-)

Aug 24 '06 #4
Charles,

Here is the problem - when you call the method
public static bool checkText<T>(T t, string matchThis)
inside the method the only thing that the compiler knows about the type T is
that it has derived from Object. That's why it will treat the *t* as an
object of type System.Object. It won't even consider the generic
formatObject overload since it cannot infer the types of V and K from the
method's type-argument list. You can easily check this by commenting out the
non-generic formatObject. The compiler will report an error.

Normally one gives hints to the compiler constraining types in the
type-argument list.
Unfortunately in your case I don't think the problem can be solved using
constraints.

My solution to the problem is to use one special overload of the checkTest
method that will provide the compiler with the information it lacks at the
moment.

public static bool checkText<K, V>(KeyValuePair <K, Vt, string matchThis)
{
string ostr = FormatObject.fo rmatObject(t);
return (ostr.IndexOf(m atchThis) != -1);
}

Using this overload the compiler will be able to infer correctly K and V,
thus call generic overload of formatObject.

I also don't see the point of using generic method for the other overload of
that method. It is equivalent of having Object as the parameter type.

Here is your sample reworked:

namespace TestProgram
{
public class FormatObject
{
public static string formatObject(Ob ject o)
{
return o.ToString();
}

public static string formatObject<K, V>(KeyValuePair <K, Vkvpo)
{
return "KeyValuePa ir<" + typeof(K).Name + ","
+ typeof(V).Name + "= " + kvpo.ToString() ;
}
}

public class CheckText
{
public static bool checkText(objec t t, string matchThis)
{
string ostr = FormatObject.fo rmatObject(t);
return (ostr.IndexOf(m atchThis) != -1);
}

public static bool checkText<K, V>(KeyValuePair <K, Vt, string
matchThis)
{
string ostr = FormatObject.fo rmatObject(t);
return (ostr.IndexOf(m atchThis) != -1);
}

}

class Program
{
static void Main(string[] args)
{
KeyValuePair<in t, intk = new
KeyValuePair<in t, int>(500, 2000);
Console.WriteLi ne(FormatObject .formatObject(" 100"));
Console.WriteLi ne(FormatObject .formatObject(k ));
bool found = CheckText.check Text("KeyValueP air100", "KeyValuePair") ;
found = CheckText.check Text(k, "KeyValuePair") ;
Console.ReadLin e();
}
}
}
--
HTH
Stoitcho Goutsev (100)

"Charles Churchill" <gy******@gmail .comwrote in message
news:11******** **************@ b28g2000cwb.goo glegroups.com.. .
Stoitcho Goutsev (100) wrote:
>Charles,

Can you please post compilable sample that demonstrates the problem -
console application is preferable.

--
Stoitcho Goutsev (100)

Here you go:

namespace TestProgram
{
public class FormatObject
{
public static string formatObject(Ob ject o)
{
return o.ToString();
}

public static string formatObject<K, V>(KeyValuePair <K, Vkvpo)
{
return "KeyValuePa ir<" + typeof(K).Name + ","
+ typeof(V).Name + "= " + kvpo.ToString() ;
}
}

public class CheckText
{
public static bool checkText<T>(T t, string matchThis)
{
string ostr = FormatObject.fo rmatObject(t);
return (ostr.IndexOf(m atchThis) != -1);
}

}

class Program
{
static void Main(string[] args)
{
KeyValuePair<in t, intk = new
KeyValuePair<in t,int>(500,2000 );
Console.WriteLi ne(FormatObject .formatObject(k ));
bool found = CheckText.check Text(k, "KeyValuePair") ;
Console.ReadLin e();
}
}
}

Thanks

Aug 25 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
4798
by: justanotherguy63 | last post by:
Hi, I am designing an application where to preserve the hierachy and for code substitability, I need to pass an array of derived class object in place of an array of base class object. Since I am using vector class(STL), the compiler does not allow me to do this. I do realize there is a pitfall in this approach(size of arrays not matching etc), but I wonder how to get around this problem. I have a class hierachy with abstract base...
7
4750
by: Ken Allen | last post by:
I have a .net client/server application using remoting, and I cannot get the custom exception class to pass from the server to the client. The custom exception is derived from ApplicationException and is defined in an assembly common to the client and server components. The custom class merely defines three (3) constructors -- the null constructor; one with a string parameter; and one with a string and innner exception parameter -- that...
2
3555
by: Jeff Bush | last post by:
I am trying to create a generic Command object (following the Command design pattern) that allows me to specify a generic type, an object to operate on, and most importantly, a public Property on that object for getting and setting the value in question. Currently the only approach I've found to work is to use delegates along with Get and Set functions (instead of using a Property). See code below. Anyone have a better approach than...
7
10238
by: Tim | last post by:
When there is a need to pass some dynamic information between 2 managed assemblies, the "Dictionary object" in Generic form can be used as a method parameter to pass the information. The information that needs to be passed can be stored as Key-Value pairs, and the method signature remains the same. That way, handling future requirements of passing additional details to the callee can be handled without changing the method signature. Is...
1
1676
by: A. Burch | last post by:
What is wrong with this type of generic... I get this error.... Error 1 Inconsistent accessibility: parameter type 'System.Collections.Generic.Queue<TMQ.TheRec>' is less accessible than method 'TMQ.Prod.Prod(System.Collections.Generic.Queue<TMQ.TheRec>)' C:\MQueue\TMQ\Program.cs 21 16 TMQ
1
4854
by: Néstor Sánchez A. | last post by:
Hi, is there a way, maybe using reflection, to use a generic class passing the type parameter dynamicly (not kwnowing the exact type at compile time)? I tried the next example, but doesn't work: public abstract class Vehicle { ... } public class Aircraft : Vehicle { ... }
17
7248
by: =?Utf-8?B?U2hhcm9u?= | last post by:
Hi Gurus, I need to transfer a jagged array of byte by reference to unmanaged function, The unmanaged code should changed the values of the array, and when the unmanaged function returns I need to show the array data to the end user. Can I do that? How?
8
3152
by: MMAS | last post by:
Hey everyone -- Curious about some strange behaviour I'm seeing that seems to be related to my lack of understanding on how generics work in C#. Here's some simplified code (sorry for strange formatting) to show what my issue is. I have a generic abstract class here: public abstract class MyGenericAbstractClass<Twhere T : MyInterface
2
2468
by: Andrus | last post by:
Winforms UI assembly has static FormManager.FormCreator method which creates forms taking entity as parameter. I need to pass this method to business objects in business assembly so that business methods can also create forms but does not have reference to UI assembly. I tried code below but got compile errows shown in comments. How to fix ? Andrus.
0
8739
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8652
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9089
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8940
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6575
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5907
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3107
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2402
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2036
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.