473,403 Members | 2,071 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,403 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 2880
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.