472,796 Members | 1,488 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,796 software developers and data experts.

Type Casting With Generics

I've been reading a discussion thread at
http://groups.google.com/group/micro...9f8362a9f5ff52
regarding typecasting generic collections to classical collections and
vice-a-versa

I faced a similar problem and solved it slightly differently... The
apporach i seems to work but i am sure someone has a better apporach
for solving this problem.

In my case i was using nHibernate which was returning Classic IList
collections and I needed to convert those to Generic driven
collection... so i wrote up a General class that will convert all
ILists to IList<T>... Below is my code:

/// <summary>
/// Converts All Non Generic Lists of n-Hibernate to Generics
/// </summary>
/// <typeparam name="T"></typeparam>
class NSList<T> : IList<T>
{

public NSList(T users)
{

}
public NSList(List NonGenericItems)
{
//TODO: Better ways of doing this same thing? ConvertAll
function of
//dotnet ? (rajiv popat)
for (int ncounter = 0; ncounter < NonGenericItems.Count;
ncounter++)
{
this.Add((T)NonGenericItems[ncounter]);
}
}

}

While this seems to do the job the Ugly for loop concerns me... Would
it be a problem if the collection had more objects in future? Any
better ways of doing it?

Bruce / Lebesgue / Anyone else, When this thread talks about Creating
an interface - does it mean
mean an interface that would do somoething similar to what i do in the
class here?

I've just started playing around with the Beta 2.0 so my questions
might be slightly stupid :) and strangely enough i could not reply to
that thread so i started a new one.

regards,
rajiv.

Nov 17 '05 #1
2 2845
rajivpopat,

This code will work, but it will create a copy of the collection which
could get out of synch.

If this is a concern, what I would do is create a class which acts as a
wrapper to the IList implementation. It would take the IList in it's
constructor, and the type would take a generic type parameter for the
IList<T> implementation. You then just forward the calls to the underlying
IList implementation.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"rajivpopat" <ra********@gmail.com> wrote in message
news:11*********************@g47g2000cwa.googlegro ups.com...
I've been reading a discussion thread at
http://groups.google.com/group/micro...9f8362a9f5ff52
regarding typecasting generic collections to classical collections and
vice-a-versa

I faced a similar problem and solved it slightly differently... The
apporach i seems to work but i am sure someone has a better apporach
for solving this problem.

In my case i was using nHibernate which was returning Classic IList
collections and I needed to convert those to Generic driven
collection... so i wrote up a General class that will convert all
ILists to IList<T>... Below is my code:

/// <summary>
/// Converts All Non Generic Lists of n-Hibernate to Generics
/// </summary>
/// <typeparam name="T"></typeparam>
class NSList<T> : IList<T>
{

public NSList(T users)
{

}
public NSList(List NonGenericItems)
{
//TODO: Better ways of doing this same thing? ConvertAll
function of
//dotnet ? (rajiv popat)
for (int ncounter = 0; ncounter < NonGenericItems.Count;
ncounter++)
{
this.Add((T)NonGenericItems[ncounter]);
}
}

}

While this seems to do the job the Ugly for loop concerns me... Would
it be a problem if the collection had more objects in future? Any
better ways of doing it?

Bruce / Lebesgue / Anyone else, When this thread talks about Creating
an interface - does it mean
mean an interface that would do somoething similar to what i do in the
class here?

I've just started playing around with the Beta 2.0 so my questions
might be slightly stupid :) and strangely enough i could not reply to
that thread so i started a new one.

regards,
rajiv.

Nov 17 '05 #2
Hi Nicholas,

You're 100% correct in saying that the copy of the collection could get
out of sync. And now that i think about it - i realize how ... crappy
my code was :) becuase it just made a one time snap shot copy of the
list and then doesn't do anything! Thanks for pointing this out.

So, what i understand from your suggestion is that i have just one
non-generic list which is actually maintained. The Class that inherits
off IList<T> just implements methods and ensures that any updates on
the generic list are actually passed back to the non-generic list by
invoking it's native methods. Here's the code i wrote up based on your
idea:
(Again, this code 'seems to work' but PLEASE do let me know what you
think about this... just want to be sure i am on the right learning
track).

/// <summary>
/// Converts All Non Generic Lists of n-Hibernate to Generics
/// </summary>
/// <typeparam name="T"></typeparam>
public class NSList<T> : IList<T>
{
IList _NonGenericItems = null;

public NSList(T GenericItems)
{

}
public NSList()
{

}
public NSList(IList NonGenericItems)
{
_NonGenericItems = NonGenericItems;
// If the 'wrapping has occurred successfully then
technically this
// crappy code is not required!
/*
for (int ncounter = 0; ncounter < NonGenericItems.Count;
ncounter++)
{
this.Add((T)NonGenericItems[ncounter]);
}
*/

}
#region IList<T> Members

public int IndexOf(T item)
{
return _NonGenericItems.IndexOf(item);
}

public void Insert(int index, T item)
{
_NonGenericItems.Insert(index, item);
}

public void RemoveAt(int index)
{
_NonGenericItems.RemoveAt(index);
}

public T this[int index]
{
get
{
return (T) _NonGenericItems[index];
}
set
{
_NonGenericItems[index] = value;
}
}

#endregion

#region ICollection<T> Members

public void Add(T item)
{
_NonGenericItems.Add(item);
}

public void Clear()
{
_NonGenericItems.Clear();
}

public bool Contains(T item)
{
return _NonGenericItems.Contains(item);
}

public void CopyTo(T[] array, int arrayIndex)
{
_NonGenericItems.CopyTo(array, arrayIndex);
}

public int Count
{
get { return _NonGenericItems.Count; }
}

public bool IsReadOnly
{
get { return _NonGenericItems.IsReadOnly; }
}

public bool Remove(T item)
{
// This Remove always returned a void so i am always going
to
// return a true?
_NonGenericItems.Remove(item);
return true;
}

#endregion

#region IEnumerable<T> Members

public IEnumerator<T> GetEnumerator()
{
// I am not sure if this is Correct.
return (IEnumerator < T >)
_NonGenericItems.GetEnumerator();
}

#endregion

#region IEnumerable Members

IEnumerator IEnumerable.GetEnumerator()
{
// Not sure if this is correct
return (IEnumerator<T>)_NonGenericItems.GetEnumerator();
}

#endregion
}

Nov 17 '05 #3

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

Similar topics

2
by: MattC | last post by:
Hi, How can do runtime casting? MyCollection derives from ArrayList I will store lost of different objects that all derive from the same parent class. I then want to be able to pass in the...
8
by: Ashish | last post by:
Hi all, I have interface declared like public IBaseInterface { } then a generic collection like
4
by: krahenbuhl | last post by:
Dear All, I've a question related to Generics and casting in c# 2.0. I've a class called Client which implements interface IClient. I'd like to do: LinkedList<Client> clients; public...
5
by: anders.forsgren | last post by:
This is a common problem with generics, but I hope someone has found the best way of solving it. I have these classes: "Fruit" which is a baseclass, and "Apple" which is derived. Further I have...
8
by: Kris Jennings | last post by:
Hi, I am trying to create a new generic class and am having trouble casting a generic type to a specific type. For example, public class MyClass<Twhere T : MyItemClass, new() { public...
7
by: Ajeet | last post by:
hi I am having some difficulty in casting using generics. These are the classes. public interface IProvider<PROF> where PROF : IProviderProfile { //Some properties/methods }
9
by: Steve Richter | last post by:
in a generic class, can I code the class so that I can call a static method of the generic class T? In the ConvertFrom method of the generic TypeConvert class I want to write, I have a call to...
4
by: Random | last post by:
I want to define a generics method so the user can determine what type they expect returned from the method. By examining the generics argument, I would determine the operation that needs to be...
3
by: BombDrop | last post by:
Can any one help I have a method that will return a List to be bound as a datasource to a combobox see code for population below. I get the following error when i try to compile Error 29 ...
4
by: =?Utf-8?B?RXRoYW4gU3RyYXVzcw==?= | last post by:
Hi, I have written a generic method which does different things depending on the type of the parameter. I got it to work, but it seems really inelegant. Is there a better way to do this? In the...
3
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Sept 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
5
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

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.