| | |
Problem casting generic object to specific object
Please support our C# advertiser: Intel Parallel Studio Home
![]() |
•
•
Join Date: Oct 2009
Posts: 2
Reputation:
Solved Threads: 0
I've created the following generic method
Which is called by
However, when I compile this I get the error
Error 1 foreach statement cannot operate on variables of type 'T' because 'T' does not contain a public definition for 'GetEnumerator'
I cannot cast the generic collection to the known collection directly i.e.
But have to take the intermediary step
This is clearly a lack of understanding about generics (and my 1st attempt at it) but any answers relating to why I get the problems (and solution) would be much appreciated.
Thanks
Dhaval
C# Syntax (Toggle Plain Text)
protected int GetSpecifiedIndexByName<T>(T collection, string itemName) { int count = 0; foreach (MyElement claim in collection) { if (itemName.Equals(claim.Name)) { return count; } count++; } }
Which is called by
C# Syntax (Toggle Plain Text)
int index = GetSpecifiedIndexByName<MyCollection>(claimColl, itemName);
However, when I compile this I get the error
Error 1 foreach statement cannot operate on variables of type 'T' because 'T' does not contain a public definition for 'GetEnumerator'
I cannot cast the generic collection to the known collection directly i.e.
C# Syntax (Toggle Plain Text)
MyCollection foo = (MyCollection)collection;
But have to take the intermediary step
C# Syntax (Toggle Plain Text)
Object foo = collection; MyCollection foobar = (MyCollection)foo;
This is clearly a lack of understanding about generics (and my 1st attempt at it) but any answers relating to why I get the problems (and solution) would be much appreciated.
Thanks
Dhaval
0
#2 Oct 8th, 2009
Upload a sample project demonstrating this behavior. You can upload a project by clicking on "Go Advanced" and then "Manager Attachments". You need to implement
IEnumerable to use foreach() . 4
#3 Oct 8th, 2009
•
•
•
•
I've created the following generic method
C# Syntax (Toggle Plain Text)
protected int GetSpecifiedIndexByName<T>(T collection, string itemName) { int count = 0; foreach (MyElement claim in collection) { if (itemName.Equals(claim.Name)) { return count; } count++; } }
You shouldn't be using generics for this kind of behavior. Instead, you should just have the function take an object that implements the IEnumerable interface:
C# Syntax (Toggle Plain Text)
protected int GetSpecifiedIndexByName(IEnumerable collection, string itemName) { int count = 0; foreach (MyElement claim in collection) { if (itemName.Equals(claim.Name)) { return count; } count++; } return -1; }
C# Syntax (Toggle Plain Text)
protected int GetSpecifiedIndexByName(IEnumerable<MyElement> collection, string itemName) { ... }
So, you should not be trying to implement a generic function at all. You just want a function that takes a parameter of type IEnumerable<MyElement>.
•
•
•
•
I cannot cast the generic collection to the known collection directly i.e.
•
•
•
•
But have to take the intermediary step
C# Syntax (Toggle Plain Text)
Object foo = collection; MyCollection foobar = (MyCollection)foo;
By the way, here's another possible way to write the function you want. It uses the where clause that I mentioned at the beginning of my reply. This would be a spurious use of generics, though, since generics are only useful when you want to prove that two types are equal.
C# Syntax (Toggle Plain Text)
protected int GetSpecifiedIndexByName<T>(T collection, string itemName) where T : IEnumerable<MyElement> { int count = 0; foreach (MyElement claim in collection) { if (itemName.Equals(claim.Name)) { return count; } count++; } return -1; }
All my posts may be redistributed under the GNU Free Documentation License.
0
#4 Oct 8th, 2009
IEnumerable, which supports a simple iteration over a collection of a specified type.
C# Syntax (Toggle Plain Text)
protected int GetSpecifiedIndexByName<T>(T collection, string itemName) { int count = 0; foreach (MyElement claim in collection as IEnumerable<MyElement>){ if (itemName.Equals(claim.Name)){ return count; } count++; } return count; }
•
•
Join Date: Oct 2009
Posts: 2
Reputation:
Solved Threads: 0
-1
#5 Oct 9th, 2009
Thanks for the replies.
The suggestion I liked
returns a
System.NullReferenceException : Object reference not set to an instance of an object.
I assume in this case because this is because we don't know what the collection passed in is at runtime?
To put into context what I'm trying to do, I want to have one method which can handle two sets of collections which both extend IEnumerable and both of which collections have their own results elements i.e. in HelloWorldCollection
which returns a MyElement object and similarly for FooBarCollection, a FooElement can be returned. Rather than writing two separate methods (or in my case below, one method with two separate for loops dependent on collection type) is there a better way I can implement this? Or, in short, as said earlier, this isn't a good use of generics and shaft this idea completely? Note that HelloWorldCollection and FooBar Collection both extend MyFooCollection.
The suggestion I liked
C# Syntax (Toggle Plain Text)
foreach (MyElement claim in collection as IEnumerable<MyElement>){
returns a
System.NullReferenceException : Object reference not set to an instance of an object.
I assume in this case because this is because we don't know what the collection passed in is at runtime?
To put into context what I'm trying to do, I want to have one method which can handle two sets of collections which both extend IEnumerable and both of which collections have their own results elements i.e. in HelloWorldCollection
C# Syntax (Toggle Plain Text)
public MyElement this[int index] { get { return (MyElement)ElementRaw(index); } }
which returns a MyElement object and similarly for FooBarCollection, a FooElement can be returned. Rather than writing two separate methods (or in my case below, one method with two separate for loops dependent on collection type) is there a better way I can implement this? Or, in short, as said earlier, this isn't a good use of generics and shaft this idea completely? Note that HelloWorldCollection and FooBar Collection both extend MyFooCollection.
C# Syntax (Toggle Plain Text)
protected int GetSpecifiedIndexByName<T>(T collection, string itemName) where T : MyFooCollection { int count = 0; if (collection is HelloWorldCollection) { foreach (MyElement claim in collection) { if (itemName.Equals(claim.Name)) { return count; } count++; } } else if (collection is FooBarCollection) { foreach (FooElement commission in collection) { if (itemName.Equals(commission.Name)) { return count; } count++; } } throw new ApplicationException("Type with name " + itemName + " not found"); }
Last edited by dhaval_shah; Oct 9th, 2009 at 8:08 am. Reason: Additional notes on thread
![]() |
Similar Threads
- Problem in counting number of ArrayList object in ArrayList (Java)
- template object as function parameter (C++)
- Problem with Radio Button error "[object HTMLInputElement]" (PHP)
- Element object from a Node object (JavaScript / DHTML / AJAX)
- Separating parts of an object (Java)
- call a method in an object, by giving the same object as the parameter (Java)
- Object Oriented Programming (Computer Science)
- Question about object lock (Java)
Other Threads in the C# Forum
- Previous Thread: Validations in textbox
- Next Thread: Comparing values inside TextBoxes( which is present inside a GridView)
| Thread Tools | Search this Thread |
Tag cloud for C#
.net access ado.net algorithm array barchart bitmap box broadcast buttons c# chat check checkbox class client color combobox control conversion csharp custom database datagrid datagridview dataset datetime degrees development draganddrop drawing encryption enum event excel file files form format forms function gdi+ httpwebrequest image index input install java list listbox listener login mandelbrot math mouseclick mysql networking object operator oracle path photoshop picturebox pixelinversion post prime programming radians regex remote remoting resource richtextbox save saving server sleep socket sql statistics stream string table tcp text textbox thread time timer treeview update usercontrol validation view visualstudio webbrowser windows winforms wpf xml






